Add editable settlement areas while preserving map anchors

This commit is contained in:
Nick Beckley 2026-11-14 14:47:32 +00:00
parent b2033ff68f
commit cfbc86c659
16 changed files with 512 additions and 50 deletions

View File

@ -0,0 +1,26 @@
# Settlement areas and geographical containment
Capital, City, Town, Village, Hamlet and Settlement remain Marker features with their existing FeatureID, LocationID and X/Y anchor. New pieces receive an editable boundary. Older records stay visually unchanged until the author selects **Convert to area**; conversion is undoable and preserves road references.
Select a settlement to choose **Move settlement**, **Edit boundary** or **Move anchor**. Whole movement translates anchor and outline; boundary movement, resizing, rotation and control-point edits leave the anchor fixed; independent anchor movement leaves the outline fixed. Roads continue following the original anchor. Buildings never follow an enclosing boundary automatically. Shape controls reuse the area editor, including adding points and removing a focused point with Delete or its context menu. Smoothing leaves original control points intact. Appearance controls override theme defaults; locks protect boundary and anchor edits.
**Geographical containment** lists all containing areas and enclosed pieces, including overlaps and nesting. It uses each placed piece's anchor and the rendered outline, including its smoothing, rather than distance from the centre. These associations are derived and never change story Location parents. Containment is invalidated on edits and calculated lazily after editing, with spatial buckets for contents queries; it is not recalculated during each pointer movement.
**Fit boundary to contents** uses geometrically enclosed pieces and pieces linked to descendant story Locations, excludes paths, and adds a margin. It preserves the anchor and all independent piece coordinates. It is explicit and undoable; with no suitable contents it is disabled.
## Storage and compatibility
No schema migration is required. Optional `GeometryJson.boundary` holds offsetX/offsetY relative to the anchor, width/height, rotation, normalized polygon points, coast smoothing and optional appearance (fillColor/fillOpacity/borderColor/borderWidth/borderStyle). It has no identity or connection target of its own. Existing feature save procedures, project backup/restore and JSON import/export carry this geometry. Server validation rejects invalid dimensions, points, smoothing and styles. Canvas units do not imply physical distance.
Containment samples the same cubic outline used for display (eight samples per segment); points extremely close to a curved edge have the normal approximation tolerance. There is no zoom-dependent representation engine. Existing point markers remain supported indefinitely.
## Verification
- `dotnet build PlotLine.slnx`
- `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj`
- `node PlotLine.Tests/Browser/maps-settlements-engine.cjs`
- `PD_MAPS_TEST_URL=http://127.0.0.1:5238 node PlotLine.Tests/Browser/maps-settlements.cjs` with the toolbar browser host running.
- Explicit isolated Development persistence/restore: `--map-settlements-database /tmp/pd-dev-browser-<fixture>/identity.json` using a dedicated disposable identity.
- Authenticated Development browser: `node PlotLine.Tests/Browser/maps-settlements-development.cjs /tmp/pd-dev-browser-<fixture>/identity.json`.
The database test creates and restores only its own uniquely named fixture project. Browser tests use fixtures or the dedicated disposable account; they never open the author's Birmingham map.

View File

@ -0,0 +1,42 @@
/* 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('Settlement Development acceptance '+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');assert(await page.locator(`a[href="/Maps?projectId=${projectId}"]`).isVisible(),'direct Maps launcher lists the signed-in author’s project');
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);}
await place('Town',.5,.5);await place('House',.51,.51);await place('Road',.3,.5);
const ids=await page.evaluate(()=>{const d=window.PlotDirectorMapWorkspace.document;return Object.fromEntries(['Town','House','Road'].map(t=>[t,d.features.find(f=>f.type===t).featureID]));});
const select=id=>page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),id);
await select(ids.Road);await page.locator('[data-field=endFeatureID]').selectOption(ids.Town);
await select(ids.Town);assert.equal(await page.locator('[data-boundary-feature-id="'+ids.Town+'"]').count(),1);
await page.locator('[data-area-frame=width]').fill('480');await page.locator('[data-area-frame=width]').blur();
const road=()=>page.locator('[data-feature-id="'+ids.Road+'"] .map-shape').getAttribute('d');const originalRoad=await road();
await page.locator('[data-geometry=coast]').selectOption('Gentle');assert.equal(await road(),originalRoad);
await page.locator('[data-settlement-mode=anchor]').click();await page.locator('[data-feature-id="'+ids.Town+'"]').focus();await page.keyboard.press('ArrowRight');assert.notEqual(await road(),originalRoad);
await page.locator('#mapsUndo').evaluate(e=>e.click());assert.equal(await road(),originalRoad);await page.locator('#mapsRedo').evaluate(e=>e.click());
await page.locator('#mapsSave').click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');
const saved=await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features));await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),saved,'real authenticated Save and reload preserve geometry and references');
assert.equal(await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id.Road).endFeatureID===id.Town,ids),true);
assert.deepEqual(errors,[]);console.log('PASS authenticated Development settlement creation, boundary/smoothing edit, anchor road recalculation, Undo/Redo, Save and reload. Isolated project '+projectId);
await context.close();
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -0,0 +1,31 @@
const assert=require('node:assert/strict'),{performance}=require('node:perf_hooks');
const E=require('../../PlotLine/wwwroot/js/maps-engine.js'),A=require('../../PlotLine/wwwroot/js/maps-appearance-engine.js');
for(const type of E.settlements){const f=E.makeFeature(type,10,20,'new-'+type);assert.equal(f.geometryClass,'Marker');assert(E.hasBoundary(f));assert(E.areaGeometry(f).points.length>=3);assert.deepEqual([f.x,f.y],[10,20]);}
const legacy=E.makeFeature('Town',50,60,'town');const g=E.geometry(legacy);delete g.boundary;legacy.geometryJson=JSON.stringify(g);legacy.locationID=123;
const original=E.copy(legacy),road=E.makeFeature('Road',500,200,'road');road.startFeatureID=legacy.featureID;
const endpoints=E.pathPoints(road,[legacy,road]);assert(E.convertToArea(legacy));assert.equal(legacy.featureID,original.featureID);assert.equal(legacy.locationID,123);assert.deepEqual([legacy.x,legacy.y],[50,60]);assert.deepEqual(E.pathPoints(road,[legacy,road]),endpoints);
const controls=JSON.stringify(E.areaGeometry(legacy).points),outlines=[];
for(const coast of ['Natural','Rugged','Gentle','Natural']){E.updateArea(legacy,b=>b.coast=coast);outlines.push(E.outline(legacy));assert.equal(JSON.stringify(E.areaGeometry(legacy).points),controls);assert.deepEqual(E.pathPoints(road,[legacy,road]),endpoints);}
assert.deepEqual(outlines[0],outlines[3]);assert.notDeepEqual(outlines[0],outlines[1]);
E.updateArea(legacy,b=>{b.width=450;b.height=300;b.rotation=23;b.points[0][0]-=.1;});assert.deepEqual(E.pathPoints(road,[legacy,road]),endpoints,'boundary editing never touches anchored connections');
const boundaryBefore=E.outline(legacy);E.moveAnchor(legacy,150,200);const fixed=E.outline(legacy);
for(let i=0;i<fixed.length;i++){assert(Math.abs(fixed[i][0]-boundaryBefore[i][0])<1e-8);assert(Math.abs(fixed[i][1]-boundaryBefore[i][1])<1e-8);}
assert.deepEqual(E.pathPoints(road,[legacy,road])[0],[150,200]);E.translate(legacy,30,40);const moved=E.outline(legacy);assert.deepEqual(E.pathPoints(road,[legacy,road])[0],[180,240]);
for(let i=0;i<moved.length;i++){assert(Math.abs(moved[i][0]-fixed[i][0]-30)<1e-8);assert(Math.abs(moved[i][1]-fixed[i][1]-40)<1e-8);}
const town=E.makeFeature('Town',0,0,'area'),overlap=E.makeFeature('Village',40,0,'overlap'),forest=E.makeFeature('Forest',0,0,'forest'),house=E.makeFeature('House',10,10,'house');
const things=[town,overlap,forest,house],beforeHouse=JSON.stringify(house);
let contained=E.containment(things);assert.deepEqual(new Set(contained.inside.get('house')),new Set(['area','overlap','forest']),'overlaps all retained');assert(contained.inside.get('overlap').includes('area'),'nested area anchor recognised');
E.updateArea(town,b=>b.offsetX=2000);contained=E.containment(things);assert(!contained.inside.get('house').includes('area'));assert.equal(JSON.stringify(house),beforeHouse,'reshaping/moving boundary never moves buildings');
E.translate(house,900,900);assert.equal(E.containment(things).inside.get('house').length,0,'moving a building out updates geometry');
const houseSnapshot=JSON.stringify(house),anchor=[town.x,town.y],routeBefore=E.pathPoints(road,[town,road]);
assert(E.fitBoundary(town,[house],things));assert.deepEqual([town.x,town.y],anchor);assert.equal(JSON.stringify(house),houseSnapshot);assert(E.pointInPolygon([house.x,house.y],E.outline(town)),'fit encloses contents with margin');
assert.equal(E.fitBoundary(town,[],things),false);town.isLocked=true;assert.equal(E.fitBoundary(town,[house],things),false);assert.equal(E.moveAnchor(town,3,4),false);
const loaded=E.copy(things);assert.deepEqual(loaded,things,'geometry/style survive the existing JSON document format');
for(const preset of ['light','paper','dark','custom']){const palette=A.palette({appearanceJson:JSON.stringify({preset,backgroundColor:'#102030',landColor:'#aabbcc'})});assert.match(palette.settlement,/^#[0-9a-f]{6}$/i);assert.match(palette.settlementLine,/^#[0-9a-f]{6}$/i);}
const many=Array.from({length:2000},(_,i)=>E.makeFeature('House',(i%100)*40,Math.floor(i/100)*40,'h-'+i));
for(let i=0;i<20;i++)many.push(E.makeFeature(i%2?'Forest':'Town',100+i*150,200,'a-'+i));
const start=performance.now();const result=E.containment(many);for(const f of many.slice(0,60))result.inside.get(f.featureID);for(const f of many.filter(E.isArea))result.contents.get(f.featureID);const duration=performance.now()-start;assert.equal(result.inside.size,2020);assert(duration<1500,'bounded end-of-edit containment should be interactive');
console.log('PASS settlement defaults/conversion, stable anchors/IDs/roads, separate boundary/anchor movement, smoothing reversibility, overlap/nesting, fit, locks, serialization and themes.');
console.log(`Containment: 2,020 pieces / 20 areas in ${Math.round(duration)}ms; no pointer-move recalculation.`);
const overlapping=Array.from({length:1200},(_,i)=>E.makeFeature('Town',0,0,'overlap-'+i));const tick=performance.now(),lazy=E.containment(overlapping);assert.equal(lazy.inside.get('overlap-0').length,1199);assert.equal(lazy.contents.get('overlap-0').length,1199);assert(performance.now()-tick<1500,'dense overlap resolves selected lists without an eager quadratic graph');

View File

@ -0,0 +1,58 @@
const{chromium}=require('playwright'),assert=require('node:assert/strict');
const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();try{
for(const pwa of [false,true])for(const theme of ['modern-light','modern-dark','warm-light']){
const context=await browser.newContext({viewport:{width:1700,height:1150}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage(),errors=[],writes=[];page.on('pageerror',e=>errors.push(e.message));
page.on('request',r=>{if(r.method()==='POST')writes.push(new URL(r.url()).pathname);});
let persisted;
await page.route('**/Maps/Save',r=>{persisted=r.request().postDataJSON();persisted.map.revision++;return r.fulfill({json:persisted});});
await page.goto(base+'/fixture?page=maps&settlements=true&theme='+theme);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
await page.locator('#mapsAssetSearch').fill('Town');await page.locator('[data-asset="Town"]').click();
const canvas=await page.locator('#mapsCanvas').boundingBox();await page.mouse.click(canvas.x+canvas.width*.5,canvas.y+canvas.height*.5);
assert(await page.evaluate(()=>window.PlotDirectorMaps.hasBoundary(window.PlotDirectorMapWorkspace.document.features[0])),'new library town defaults to an area');
const ids=await page.evaluate(theme=>{const W=window.PlotDirectorMapWorkspace,E=window.PlotDirectorMaps,ids={town:crypto.randomUUID(),house:crypto.randomUUID(),outside:crypto.randomUUID(),road:crypto.randomUUID(),forest:crypto.randomUUID()};W.edit(()=>{const preset=theme.includes('dark')?'dark':theme.includes('warm')?'paper':'light';W.document.map.appearanceJson=JSON.stringify({preset});
const town=E.makeFeature('Town',0,0,ids.town),g=E.geometry(town);delete g.boundary;Object.assign(town,{name:'Rubery',locationID:11,isProvisional:false,geometryJson:JSON.stringify(g)});
const house=E.makeFeature('House',40,15,ids.house);Object.assign(house,{name:"Maggie's flat",locationID:12,isProvisional:false});
const outside=E.makeFeature('House',480,40,ids.outside);Object.assign(outside,{name:"Beth's flat",locationID:13,isProvisional:false});
const road=E.makeFeature('Road',-300,0,ids.road);Object.assign(road,{name:'A38',endFeatureID:ids.town});
const forest=E.makeFeature('Forest',60,0,ids.forest);forest.name='Lickey Hills';W.document.features=[forest,town,road,house,outside];
});W.fit();return ids;},theme);
const feature=id=>page.evaluate(id=>JSON.parse(JSON.stringify(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id))),id);
const select=id=>page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),id);
const route=()=>page.locator(`[data-feature-id="${ids.road}"] .map-shape`).getAttribute('d');
async function command(id){await page.evaluate(id=>document.getElementById(id).click(),id);}
const original=await feature(ids.town),roadBefore=await route();await select(ids.town);assert(await page.locator('[data-action=convert-area]').isVisible());
await page.locator('[data-action=convert-area]').click();let town=await feature(ids.town);assert.equal(town.geometryClass,'Marker');assert.equal(town.locationID,11);assert.deepEqual([town.x,town.y],[original.x,original.y]);assert.equal(town.featureID,ids.town);assert.equal(await route(),roadBefore);
assert.equal(await page.locator(`[data-boundary-feature-id="${ids.town}"]`).count(),1);assert.equal(await page.locator('.maps-anchor-crosshair').count(),1);
await command('mapsUndo');assert(!JSON.parse((await feature(ids.town)).geometryJson).boundary);await command('mapsRedo');assert(JSON.parse((await feature(ids.town)).geometryJson).boundary);await select(ids.town);
const houseBefore=await feature(ids.house),outline=JSON.parse((await feature(ids.town)).geometryJson).boundary.points;
async function dragBy(selector,dx,dy){const box=await page.locator(selector).boundingBox();await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width/2+dx,box.y+box.height/2+dy,{steps:5});await page.mouse.up();}
await page.locator('[data-settlement-mode=boundary]').click();
const boundaryStart=await page.evaluate(()=>new DOMPoint(100,30).matrixTransform(document.getElementById('mapsCanvas').getScreenCTM()).toJSON());
await page.mouse.move(boundaryStart.x,boundaryStart.y);await page.mouse.down();await page.mouse.move(boundaryStart.x+22,boundaryStart.y+8,{steps:5});await page.mouse.up();
const boundaryMoved=await feature(ids.town);assert.deepEqual([boundaryMoved.x,boundaryMoved.y],[original.x,original.y]);assert.notEqual(JSON.parse(boundaryMoved.geometryJson).boundary.offsetX,0,'dragging outline in boundary mode moves only its frame');assert.equal(await route(),roadBefore);assert.deepEqual(await feature(ids.house),houseBefore);
await page.locator('[data-settlement-mode=boundary]').click();let count=await page.locator('[data-handle=point]').count();assert.equal(count,8);const beforePoint=(await feature(ids.town)).geometryJson;await dragBy('[data-handle=point]:first-child',16,9);assert.notEqual((await feature(ids.town)).geometryJson,beforePoint,'pointer control-point editor changes the boundary');assert.equal(await route(),roadBefore);
await page.locator('[data-action=bend]').click();assert.equal(await page.locator('[data-handle=point]').count(),9);
await page.locator('[data-handle=point]').first().focus();await page.keyboard.press('ArrowLeft');assert.equal(await route(),roadBefore);await page.keyboard.press('Delete');assert.equal(await page.locator('[data-handle=point]').count(),8);
const input=page.locator('[data-area-frame=width]');await input.fill('420');await input.blur();assert.equal(JSON.parse((await feature(ids.town)).geometryJson).boundary.width,420);assert.equal(await route(),roadBefore);assert.deepEqual(await feature(ids.house),houseBefore);
const controls=JSON.stringify(JSON.parse((await feature(ids.town)).geometryJson).boundary.points);
for(const value of ['Rugged','Gentle','Natural']){await page.locator('[data-geometry=coast]').selectOption(value);assert.equal(JSON.stringify(JSON.parse((await feature(ids.town)).geometryJson).boundary.points),controls);assert.equal(await route(),roadBefore);}
await page.locator('[data-area-style=fillOpacity]').fill('0.4');await page.locator('[data-area-style=fillOpacity]').blur();await page.locator('[data-area-style=borderStyle]').selectOption('Dotted');
assert.equal(await page.locator(`[data-boundary-feature-id="${ids.town}"] path`).getAttribute('fill-opacity'),'0.4');
await select(ids.house);const containment=page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Geographical containment")')});await containment.locator('summary').click();assert.match(await containment.innerText(),/Rubery/);assert.match(await containment.innerText(),/Lickey Hills/);
await select(ids.town);await page.locator('[data-settlement-mode=anchor]').click();const worldBefore=await page.evaluate(id=>window.PlotDirectorMaps.outline(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),ids.town);
await page.locator('[data-handle=anchor]').focus();await page.keyboard.press('ArrowRight');town=await feature(ids.town);assert.equal(town.x,original.x+5);assert.notEqual(await route(),roadBefore);
const worldAfter=await page.evaluate(id=>window.PlotDirectorMaps.outline(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),ids.town);assert(worldAfter.every((p,i)=>p.every((v,j)=>Math.abs(v-worldBefore[i][j])<1e-8)),'independent anchor movement leaves outline fixed');await dragBy('[data-handle=anchor]',14,7);const pointerWorld=await page.evaluate(id=>window.PlotDirectorMaps.outline(window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id)),ids.town);assert(pointerWorld.every((p,i)=>p.every((v,j)=>Math.abs(v-worldBefore[i][j])<1e-8)));town=await feature(ids.town);
await page.locator('[data-settlement-mode=whole]').click();await page.locator(`[data-feature-id="${ids.town}"]`).focus();await page.keyboard.press('ArrowDown');const moved=await feature(ids.town);assert.equal(moved.y,town.y+5);assert.deepEqual(await feature(ids.house),houseBefore,'whole settlement movement never moves contained buildings');
await select(ids.house);await page.locator(`[data-feature-id="${ids.house}"]`).focus();await page.keyboard.press('Shift+ArrowRight');await page.evaluate(id=>{const W=window.PlotDirectorMapWorkspace;W.edit(()=>{W.document.features.find(f=>f.featureID===id).x=900;});},ids.house);
const outsideInfo=page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Geographical containment")')});await outsideInfo.locator('summary').click();assert.match(await outsideInfo.innerText(),/No mapped area/);
await select(ids.town);const beforeFit=await feature(ids.town),buildingFit=await feature(ids.house),r=await route();await page.locator('[data-action=fit-boundary]').click();assert.equal((await feature(ids.town)).x,beforeFit.x);assert.equal((await feature(ids.town)).y,beforeFit.y);assert.equal(await route(),r);assert.deepEqual(await feature(ids.house),buildingFit);
await select(ids.house);const fitted=page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Geographical containment")')});await fitted.locator('summary').click();assert.match(await fitted.innerText(),/Rubery/,'story-associated exterior content included by explicit Fit');
await select(ids.town);await page.locator('[data-action=duplicate]').click();const copies=await page.evaluate(id=>window.PlotDirectorMapWorkspace.document.features.filter(f=>f.featureID!==id&&f.name==='Rubery copy'),ids.town);assert.equal(copies.length,1);assert.equal(copies[0].locationID,11);assert(JSON.parse(copies[0].geometryJson).boundary);
await select(ids.town);await page.locator('[data-field=isLocked]').check();assert(await page.locator('[data-action=fit-boundary]').isDisabled());const locked=await feature(ids.town);await page.locator(`[data-feature-id="${ids.town}"]`).focus();await page.keyboard.press('ArrowRight');assert.deepEqual(await feature(ids.town),locked);
await command('mapsSave');await page.waitForFunction(()=>!window.PlotDirectorMapWorkspace.busy);assert(persisted.features.find(f=>f.featureID===ids.town).geometryJson.includes('boundary'));assert.deepEqual(errors,[]);assert(writes.every(p=>p==='/Maps/Save'),'geometry never mutates story relationships');
console.log('PASS settlement editor conversion, preserved road/anchor, control points, modes, containment, fit, style, undo/redo, duplication, locks and Save',pwa?'PWA':'browser',theme);
await context.close();
}
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -66,7 +66,7 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5246';
// 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`});
await page.screenshot({path:`${process.env.PD_MAPS_SCREENSHOT_DIR||'/tmp'}/maps-${pwa?'pwa':'web'}.png`});
const established=await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.map(f=>({id:f.featureID,x:f.x,y:f.y})));
await sourceClick('mapsDefine');const definition=page.locator('dialog[open]');await definition.locator('[name=name]').fill('New northern village');await definition.locator('[name=type]').selectOption('Village');await definition.locator('[name=targetID]').selectOption(towns[0].featureID);await definition.locator('[name=direction]').selectOption('NE');await definition.getByRole('button',{name:'Add place',exact:true}).click();
assert(await page.evaluate(previous=>{const d=window.PlotDirectorMapWorkspace.document,f=d.features.at(-1),target=d.features.find(x=>x.featureID===d.relationships.at(-1).targetID);return f.name==='New northern village'&&window.PlotDirectorMaps.suggestedDirection(f,target)==='NE'&&previous.every(p=>{const f=d.features.find(f=>f.featureID===p.id);return f.x===p.x&&f.y===p.y;});},established),'relationship-first placement moves only the newly defined place');

View File

@ -0,0 +1,52 @@
// Explicit Development-only persistence/restore regression. All data belongs to a disposable test identity.
using System.Data;
using System.Diagnostics;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotLine.Data;
using PlotLine.Models;
internal static class MapSettlementDatabaseTests
{
static void Check(bool ok,string message){if(!ok)throw new InvalidOperationException(message);}
public static async Task Run(string path)
{
if(!Path.GetFullPath(path).StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal))throw new InvalidOperationException("Dedicated Development identity required.");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(path));var account=identity.RootElement;
if(account.GetProperty("Database").GetString()!="PlotDirector_Development"||!account.GetProperty("Email").GetString()!.StartsWith("pwa-browser-"))throw new InvalidOperationException("Wrong identity scope.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
using var process=Process.Start(start)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable.");
var connectionString=environment.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Wrong configured database.");
using var db=new SqlConnection(connectionString);await db.OpenAsync();Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Development","Verify effective Development database.");
var user=account.GetProperty("UserID").GetInt32();Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.AppUser WHERE UserID=@user AND Email=@email",new{user,email=account.GetProperty("Email").GetString()})==1,"Verify disposable account.");
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();var factory=new SqlConnectionFactory(config);
var title="Settlement boundary regression "+Guid.NewGuid().ToString("N");
var project=await db.QuerySingleAsync<int>("dbo.Project_Save",new{ProjectName=title,UserID=user},commandType:CommandType.StoredProcedure);
var locations=new LocationRepository(factory);var root=await locations.SaveAsync(new(){ProjectID=project,LocationName="Settlement fixture"});
var building=await locations.SaveAsync(new(){ProjectID=project,LocationName="Building fixture",ParentLocationID=root});
var maps=new MapRepository(factory);var map=await maps.CreateAsync(new(){ProjectID=project,Name="Boundary fixture",Kind="Local Area"},user);
var document=(await maps.GetAsync(project,map,user))!;
var town=new MapFeature{Name="Settlement fixture",Type="Town",LocationID=root,X=50,Y=70,GeometryJson="""{"boundary":{"offsetX":20,"offsetY":-10,"width":330,"height":220,"rotation":12,"coast":"Rugged","points":[[-0.5,-0.5],[0.5,-0.5],[0.5,0.5],[-0.5,0.5]],"appearance":{"fillColor":"#9977aa","fillOpacity":0.3,"borderColor":"#443355","borderWidth":2,"borderStyle":"Dashed"}}}"""};
var house=new MapFeature{Name="Building fixture",Type="House",LocationID=building,X=60,Y=80};
var road=new MapFeature{Name="Road fixture",Type="Road",GeometryClass="Path",EndFeatureID=town.FeatureID};
document.Features=[town,house,road];await maps.SaveAsync(document,user);document=(await maps.GetAsync(project,map,user))!;
var boundary=town.GeometryJson;Check(document.Features.Single(f=>f.FeatureID==town.FeatureID).GeometryJson==boundary,"Save/reload retains exact boundary/style JSON.");
Check(document.Features.Single(f=>f.FeatureID==road.FeatureID).EndFeatureID==town.FeatureID,"Existing road reference still targets the Marker anchor.");
var export=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,user))!;
var imported=JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(export))!;
Check(imported.Data.MapFeatures.Single(f=>f.FeatureID==town.FeatureID).GeometryJson==boundary,"Real project export/import carries exact geometry.");
document.Features.Single(f=>f.FeatureID==town.FeatureID).GeometryJson="{}";await maps.SaveAsync(document,user);
// Restore only the unique project just created above, never a human project or the database itself.
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@project AND ProjectName=@title",new{project,title})==1,"Verify isolated restore target.");
await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=BookRecoveryRepository.Encode(imported,null)},commandType:CommandType.StoredProcedure,commandTimeout:180);
var restored=(await maps.GetAsync(project,map,user))!;
Check(restored.Features.Single(f=>f.FeatureID==town.FeatureID).GeometryJson==boundary,"Full SQL project restore retains settlement boundaries.");
Check(restored.Features.Single(f=>f.FeatureID==town.FeatureID).LocationID==root && restored.Features.Single(f=>f.FeatureID==road.FeatureID).EndFeatureID==town.FeatureID,"Restore preserves story identity and connection targets.");
Check((await locations.GetAsync(building))!.ParentLocationID==root,"Map edits and restore preserve the building's story parent.");
Check(restored.Map.Revision>document.Map.Revision,"Restore invalidates stale editors.");
Console.WriteLine("PASS Development settlement JSON Save/reload, real backup/export/import, isolated full-project restore, anchor/road/story identity and stale-editor revision. Temporary account owns all fixtures for normal cleanup.");
}
}

View File

@ -0,0 +1,33 @@
using System.Reflection;
using System.Text.Json;
using PlotLine.Models;
using PlotLine.Services;
internal static class MapSettlementTests
{
private static void Check(bool value,string message){if(!value)throw new InvalidOperationException(message);}
public static void Run()
{
const string boundary="""{"boundary":{"offsetX":12,"offsetY":-7,"width":330,"height":220,"rotation":15,"points":[[-0.5,-0.5],[0.5,-0.5],[0.5,0.5],[-0.5,0.5]],"coast":"Natural","appearance":{"fillColor":"#9977aa","fillOpacity":0.25,"borderColor":"#443355","borderWidth":2.5,"borderStyle":"Dashed"}}}""";
var town=new MapFeature{MapID=1,Name="Settlement fixture",Type="Town",X=50,Y=70,GeometryJson=boundary};
var road=new MapFeature{MapID=1,Name="Connected road",Type="Road",GeometryClass="Path",StartFeatureID=town.FeatureID};
var doc=new MapDocument{Map=new(){MapID=1,ProjectID=7},Features=[town,road]};
Check(MapValidation.Validate(doc) is null,"A settlement boundary retains its valid Marker route endpoint.");
var anchor=(town.FeatureID,town.X,town.Y,road.StartFeatureID);
var roundtrip=JsonSerializer.Deserialize<MapDocument>(JsonSerializer.Serialize(doc))!;
Check(roundtrip.Features[0].GeometryJson==boundary,"Existing map serialization retains boundary geometry and style byte-for-byte.");
Check((town.FeatureID,town.X,town.Y,road.StartFeatureID)==anchor,"Validation/serialization never changes the anchor or connection.");
foreach(var invalid in new[]{boundary.Replace("330","0"),boundary.Replace("330","1e100"),boundary.Replace("\"offsetX\":12","\"offsetX\":\"12\""),boundary.Replace("0.25","1.5"),boundary.Replace("#9977aa","url(https://example.invalid)"),boundary.Replace("Dashed","unsafe"),boundary.Replace("Natural","unsupported")})
{town.GeometryJson=invalid;Check(MapValidation.Validate(doc) is not null,"Malformed boundary fields and unsafe appearance must fail.");}
town.GeometryJson=boundary;town.Type="House";Check(MapValidation.Validate(doc) is not null,"Buildings cannot disguise an arbitrary boundary as a settlement anchor.");
town.Type="Town";town.GeometryClass="Area";Check(MapValidation.Validate(doc) is not null,"Settlement areas must retain the Marker connection identity.");
town.GeometryClass="Marker";town.GeometryJson="{}";Check(MapValidation.Validate(doc) is null,"Legacy point-only settlements remain valid.");
town.GeometryJson=boundary;
var backup=new ProjectBackupExport{Project=new(){ProjectID=7},Data=new(){StoryMaps=[doc.Map],MapFeatures=doc.Features}};
var validate=typeof(ProjectRestoreService).GetMethod("ValidateBackup",BindingFlags.Static|BindingFlags.NonPublic)!;
var imported=JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(backup))!;
Check(validate.Invoke(null,[7,imported]) is null,"Backup export/import and restore validation accept settlement boundary records without a new format or field contract.");
Check(imported.Data.MapFeatures[0].FeatureID==town.FeatureID&&imported.Data.MapFeatures[0].GeometryJson==boundary&&imported.Data.MapFeatures[1].StartFeatureID==town.FeatureID,"Backup/import retain geometry, feature identities and route references.");
imported.Data.MapFeatures[0].GeometryJson=boundary.Replace("330","0");Check(validate.Invoke(null,[7,imported]) is string,"Backup import enforces the same boundary validation as Save.");
Console.WriteLine("PASS settlement Marker compatibility, nested geometry/style validation, stable route references and existing map/backup/import JSON contracts.");
}
}

View File

@ -15,6 +15,8 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--map-settlements-database")){await MapSettlementDatabaseTests.Run(args.Last());return;}
if(args.Contains("--map-settlements")){MapSettlementTests.Run();return;}
if(args.Contains("--geography-live-recovery")){await GeographyLiveRecovery.Run(args);return;}
if(args.Contains("--geography-database")){await GeographyDatabaseTests.Run();return;}
if(args.Contains("--geography")){await GeographyTests.Run();return;}
@ -154,6 +156,7 @@ if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console
var tests = new (string Name, Action Test)[]
{
("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run),
("Geographical roots, providers, queue outcomes and access", () => GeographyTests.Run().GetAwaiter().GetResult()),
("Intent evidence preserves provenance and author control", () => IntentAssessmentTests.Run().GetAwaiter().GetResult()),
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),

View File

@ -543,7 +543,9 @@ internal static class ToolbarBrowserHost
var map = new StoryMap { MapID = 1, ProjectID = 7, Name = "Working geography", Kind = "Region" };
surface = await Render("Maps/Index", context.Request.Query["story"] == "true" ? MapStoryTests.Workspace() : 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" }]
Locations = context.Request.Query["settlements"]=="true"
? [new(){LocationID=11,ProjectID=7,LocationName="Rubery"},new(){LocationID=12,ProjectID=7,LocationName="Maggie's flat",ParentLocationID=11},new(){LocationID=13,ProjectID=7,LocationName="Beth's flat",ParentLocationID=11}]
: [new LocationItem { LocationID = 11, ProjectID = 7, LocationName = "Harbour town" }, new LocationItem { LocationID = 12, ProjectID = 7, LocationName = "Hill village" }]
});
surface += "<script src='/js/application-dialogs.js'></script><script src='/js/workspace-surface.js'></script><script src='/js/maps-symbols.js'></script><script src='/js/workspace-bridge.js'></script><script src='/js/maps-engine.js'></script><script src='/js/maps-appearance-engine.js'></script><script src='/js/maps-geography-engine.js'></script><script src='/js/maps-workspace.js'></script><script src='/js/maps-appearance.js'></script><script src='/js/maps-story-engine.js'></script><script src='/js/maps-story.js'></script>";
}

View File

@ -0,0 +1,39 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using PlotLine.Models;
namespace PlotLine.Services;
// Geometry stays in the existing feature JSON; settlement features remain authoritative Marker anchors.
internal static class MapAreaGeometryValidation
{
internal static readonly string[] SettlementTypes=["Capital","City","Town","Village","Hamlet","Settlement"];
public static string? Validate(MapFeature feature,JsonElement geometry)
{
if(feature.GeometryClass=="Area" && geometry.TryGetProperty("appearance",out var areaStyle) && !ValidAppearance(areaStyle))return "Check area colours, opacity and border style.";
if(!geometry.TryGetProperty("boundary",out var boundary)||boundary.ValueKind==JsonValueKind.Null)return null;
if(feature.GeometryClass!="Marker"||!SettlementTypes.Contains(feature.Type))return "A settlement boundary must retain its settlement Marker anchor.";
if(boundary.ValueKind!=JsonValueKind.Object)return "Invalid settlement boundary.";
foreach(var field in new[]{"offsetX","offsetY","width","height","rotation"})
{
var limit=field.StartsWith("offset",StringComparison.Ordinal)?200000:100000;
if(!boundary.TryGetProperty(field,out var value)||value.ValueKind!=JsonValueKind.Number||!value.TryGetDouble(out var number)||!double.IsFinite(number)||Math.Abs(number)>limit||((field=="width"||field=="height")&&number<1))return "Check settlement boundary position, dimensions and rotation.";
}
if(!boundary.TryGetProperty("points",out var points)||points.ValueKind!=JsonValueKind.Array||points.GetArrayLength() is <3 or >64)return "A settlement boundary needs 3–64 control 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 settlement boundary control point.";
if(boundary.TryGetProperty("coast",out var coast)&&(coast.ValueKind!=JsonValueKind.String||!new[]{"Gentle","Natural","Rugged","Cliffs","Fjords","Marsh/Delta"}.Contains(coast.GetString())))return "Choose a supported boundary smoothing style.";
if(boundary.TryGetProperty("appearance",out var style)&&!ValidAppearance(style))return "Check boundary colours, opacity and border style.";
return null;
}
private static bool ValidAppearance(JsonElement style)
{
if(style.ValueKind==JsonValueKind.Null)return true;
if(style.ValueKind!=JsonValueKind.Object)return false;
foreach(var key in new[]{"fillColor","borderColor"})
if(style.TryGetProperty(key,out var colour)&&(colour.ValueKind!=JsonValueKind.String||!Regex.IsMatch(colour.GetString()??"","^#[0-9a-fA-F]{6}$")))return false;
foreach(var (key,max) in new[]{("fillOpacity",1d),("borderWidth",30d)})
if(style.TryGetProperty(key,out var value)&&(value.ValueKind!=JsonValueKind.Number||!value.TryGetDouble(out var n)||!double.IsFinite(n)||n<0||n>max))return false;
if(style.TryGetProperty("borderStyle",out var border)&&(border.ValueKind!=JsonValueKind.String||!new[]{"Solid","Dashed","Dotted"}.Contains(border.GetString())))return false;
return true;
}
}

View File

@ -31,11 +31,13 @@ public static class MapValidation
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.";
if (string.IsNullOrEmpty(f.GeometryJson) || 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.";
var areaError=MapAreaGeometryValidation.Validate(f,geometry.RootElement);
if(areaError is not null)return areaError;
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.";

View File

@ -45,3 +45,11 @@ html[data-standalone=true]:has(#mapsApp) .pd-ribbon-panel:not([hidden]){min-heig
#mapsGeographicSummary{max-height:160px;overflow:auto}
#mapsGeographicSummary p{margin:4px 0}
.maps-geographic-actions{display:flex;flex-wrap:wrap;gap:6px;position:sticky;bottom:0;background:var(--map-panel);padding:6px 0}
.maps-boundary{cursor:move}
.maps-boundary.is-selected .map-boundary-shape{stroke:var(--maps-selection,#136883)!important;stroke-width:3!important}
.maps-boundary.is-provisional .map-boundary-shape{stroke-dasharray:5 3}
.maps-boundary:focus-visible .map-boundary-shape{stroke:var(--maps-selection,#136883)!important;stroke-width:3!important}
.maps-details fieldset{border:0;padding:0;margin:0;min-width:0}
.maps-details fieldset:disabled{opacity:.65}
.maps-details [data-select-map-piece]{margin:2px;font-size:.82rem}

View File

@ -4,7 +4,7 @@
function appearance(map){let value;try{value=JSON.parse(map?.appearanceJson||'{}');}catch{}return {preset:'light',...presets.light,...value};}
function reference(map){let value;try{value=JSON.parse(map?.referenceJson||'{}');}catch{}return value?.imageID?{x:0,y:0,width:800,height:600,rotation:0,opacity:.35,isLocked:true,isVisible:true,...value}:null;}
const luminance=hex=>{const v=hex.slice(1).match(/../g).map(x=>parseInt(x,16)/255).map(x=>x<=.04045?x/12.92:((x+.055)/1.055)**2.4);return .2126*v[0]+.7152*v[1]+.0722*v[2];};
function palette(map){const a=appearance(map),base=presets[a.preset]||a,dark=luminance(base.backgroundColor)<.2;return {...base,dark,ink:dark?'#edf4ed':'#243f38',halo:dark?'#102128':'#fffef3',marker:dark?'#304a50':'#faf5df',selection:dark?'#ffe19a':'#136883',water:dark?'#85cbe3':'#4c92ae',route:dark?'#e2bc83':'#99764b',region:dark?'#d2b6fa':'#80699b',story:dark?['#80c9fa','#e2b0e4','#ffc977']:['#265e83','#7c4f83','#936027']};}
function palette(map){const a=appearance(map),base=presets[a.preset]||a,dark=luminance(base.backgroundColor)<.2;return {...base,dark,ink:dark?'#edf4ed':'#243f38',halo:dark?'#102128':'#fffef3',marker:dark?'#304a50':'#faf5df',selection:dark?'#ffe19a':'#136883',water:dark?'#85cbe3':'#4c92ae',route:dark?'#e2bc83':'#99764b',region:dark?'#d2b6fa':'#80699b',settlement:dark?'#aaa2d7':a.preset==='paper'?'#a77855':'#9670aa',settlementLine:dark?'#d2c2f1':a.preset==='paper'?'#82583c':'#62507c',story:dark?['#80c9fa','#e2b0e4','#ffc977']:['#265e83','#7c4f83','#936027']};}
function fit(image,view,rotation=0){const c=Math.abs(Math.cos(rotation*Math.PI/180)),s=Math.abs(Math.sin(rotation*Math.PI/180)),factor=Math.min(view.w*.8/(image.width*c+image.height*s),view.h*.8/(image.width*s+image.height*c));return {imageID:image.imageID,x:view.x+view.w/2,y:view.y+view.h/2,width:image.width*factor,height:image.height*factor,rotation,opacity:.35,isVisible:true,isLocked:true};}
const angle=n=>((n+180)%360+360)%360-180;
function transform(original,kind,start,point){const r=copy(original),dx=point[0]-start[0],dy=point[1]-start[1];if(kind==='move'){r.x+=dx;r.y+=dy;}if(kind==='scale'){const factor=Math.max(.02,Math.min(100,Math.hypot(point[0]-r.x,point[1]-r.y)/Math.hypot(start[0]-r.x,start[1]-r.y)));r.width=Math.max(10,Math.min(100000,r.width*factor));r.height=Math.max(10,Math.min(100000,r.height*factor));}if(kind==='rotate')r.rotation=angle(original.rotation+(Math.atan2(point[1]-r.y,point[0]-r.x)-Math.atan2(start[1]-r.y,start[0]-r.x))*180/Math.PI);return r;}

View File

@ -14,7 +14,7 @@
function finish(cancel=false){if(!adjusting)return;const tx=transaction;adjusting=false;transaction=null;drag=null;const active=document.activeElement,field=active?.dataset.referenceField,kind=active?.getAttribute('type'),colour=active?.dataset.mapColour,scale=active?.hasAttribute('data-reference-scale');if(cancel)W.cancelAdjustment(tx);else W.commitAdjustment(tx);if(colour)$('mapsDetailContent').querySelector(`[data-map-colour="${colour}"]`)?.focus({preventScroll:true});else if(scale)$('mapsDetailContent').querySelector('[data-reference-scale]')?.focus({preventScroll:true});else if(field)$('mapsDetailContent').querySelector(`[data-reference-field="${field}"][type="${kind}"]`)?.focus({preventScroll:true});}
function render(){
if(!W.document){layer.setAttribute('display','none');handles.replaceChildren();return;}
const p=E.palette(W.document.map),key=JSON.stringify(p);if(key!==paletteKey){paletteKey=key;const values={'canvas-bg':p.backgroundColor,land:p.landColor,'map-ink':p.ink,'label-halo':p.halo,'marker-bg':p.marker,selection:p.selection,'water-line':p.water,'route-line':p.route,'region-line':p.region,'terrain-line':p.dark?'#8da18c':'#91a087','forest-fill':p.dark?'#334c3b':'#c4d4af','mountains-fill':p.dark?'#53584c':'#d3cebd','marsh-fill':p.dark?'#3b5350':'#c2d3bc'};for(const[k,v]of Object.entries(values))svg.style.setProperty('--maps-'+k,v);window.dispatchEvent(new CustomEvent('pd-map-palette',{detail:p}));}
const p=E.palette(W.document.map),key=JSON.stringify(p);if(key!==paletteKey){paletteKey=key;const values={'canvas-bg':p.backgroundColor,land:p.landColor,'map-ink':p.ink,'label-halo':p.halo,'marker-bg':p.marker,selection:p.selection,'water-line':p.water,'route-line':p.route,'region-line':p.region,'settlement-fill':p.settlement,'settlement-line':p.settlementLine,'terrain-line':p.dark?'#8da18c':'#91a087','forest-fill':p.dark?'#334c3b':'#c4d4af','mountains-fill':p.dark?'#53584c':'#d3cebd','marsh-fill':p.dark?'#3b5350':'#c2d3bc'};for(const[k,v]of Object.entries(values))svg.style.setProperty('--maps-'+k,v);window.dispatchEvent(new CustomEvent('pd-map-palette',{detail:p}));}
const r=ref();attr(layer,'display',r?.isVisible?'inline':'none');handles.replaceChildren();if(!r)return;
const href=`/Maps/ReferenceImage?projectId=${boot.projectId}&imageId=${encodeURIComponent(r.imageID)}`;attr(image,'href',href);attr(image,'x',-r.width/2);attr(image,'y',-r.height/2);attr(image,'width',r.width);attr(image,'height',r.height);attr(layer,'transform',`translate(${r.x} ${r.y}) rotate(${r.rotation})`);attr(image,'opacity',r.opacity);attr(image,'class',r.isLocked?'maps-reference-image is-locked':'maps-reference-image');
attr(outline,'x',-r.width/2);attr(outline,'y',-r.height/2);attr(outline,'width',r.width);attr(outline,'height',r.height);attr(outline,'visibility',selected&&W.mode==='create'?'visible':'hidden');

View File

@ -21,6 +21,7 @@
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 settlements = ['Capital','City','Town','Village','Hamlet','Settlement'];
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]];
@ -30,7 +31,9 @@
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:'' };
const feature = { 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:'' };
if(settlements.includes(type))convertToArea(feature);
return feature;
}
function localToWorld(f,p) {
const a=f.rotation*Math.PI/180, x=p[0]*f.width,y=p[1]*f.height;
@ -57,13 +60,90 @@
}
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;
if(!['Land Mass','Island'].includes(f.type)&&!hasBoundary(f)&&!f.settlementBoundary) 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];});
});
}
const isSettlement=f=>f.geometryClass==='Marker'&&settlements.includes(f.type);
const hasBoundary=f=>isSettlement(f)&&!!geometry(f).boundary;
const isArea=f=>f.geometryClass==='Area'||hasBoundary(f);
function convertToArea(f){
if(!isSettlement(f)||hasBoundary(f)||f.isLocked)return false;
const g=geometry(f);
const size=({Capital:[560,360],City:[480,320],Town:[330,220],Village:[240,160],Hamlet:[180,120],Settlement:[300,200]})[f.type];
g.boundary={offsetX:0,offsetY:0,width:size[0],height:size[1],rotation:0,points:[[-.48,-.22],[-.20,-.5],[.17,-.43],[.48,-.18],[.4,.26],[.1,.48],[-.26,.35],[-.5,.1]],coast:'Natural'};
f.geometryJson=JSON.stringify(g);return true;
}
function areaGeometry(f){return hasBoundary(f)?geometry(f).boundary:geometry(f);}
function updateArea(f,change){const g=geometry(f);change(hasBoundary(f)?g.boundary:g);f.geometryJson=JSON.stringify(g);}
function areaFrame(f){
if(!hasBoundary(f))return f;
const b=areaGeometry(f);
return {x:f.x+b.offsetX,y:f.y+b.offsetY,width:b.width,height:b.height,rotation:b.rotation,geometryClass:'Area',type:f.type,settlementBoundary:true,geometryJson:JSON.stringify(b)};
}
function worldToLocal(f,p){const a=-f.rotation*Math.PI/180,dx=p[0]-f.x,dy=p[1]-f.y;return [(dx*Math.cos(a)-dy*Math.sin(a))/f.width,(dx*Math.sin(a)+dy*Math.cos(a))/f.height];}
function translate(f,dx,dy){f.x+=dx;f.y+=dy;}
function moveAnchor(f,x,y){if(f.isLocked)return false;const dx=x-f.x,dy=y-f.y;if(hasBoundary(f))updateArea(f,b=>{b.offsetX-=dx;b.offsetY-=dy;});f.x=x;f.y=y;return true;}
function featureBounds(f,features=[]){
const frame=areaFrame(f),pts=isArea(f)?coastline(frame).map(p=>localToWorld(frame,p)):f.geometryClass==='Path'?pathPoints(f,features):[[f.x-f.width/2,f.y-f.height/2],[f.x+f.width/2,f.y+f.height/2]];
if(!pts.length)pts.push(localToWorld(frame,[-.5,-.5]),localToWorld(frame,[.5,.5]));
if(hasBoundary(f))pts.push([f.x,f.y]);
return {left:Math.min(...pts.map(p=>p[0])),right:Math.max(...pts.map(p=>p[0])),top:Math.min(...pts.map(p=>p[1])),bottom:Math.max(...pts.map(p=>p[1]))};
}
// Sample the same cubic segments used by curve(); containment follows the rendered, smoothed outline.
function outline(f){
const frame=areaFrame(f),p=coastline(frame).map(p=>localToWorld(frame,p)),result=[],n=p.length;
for(let i=0;i<n;i++){
const a=p[(i-1+n)%n],b=p[i],c=p[(i+1)%n],d=p[(i+2)%n];
const c1=[b[0]+(c[0]-a[0])/6,b[1]+(c[1]-a[1])/6],c2=[c[0]-(d[0]-b[0])/6,c[1]-(d[1]-b[1])/6];
for(let j=0;j<8;j++){const t=j/8,u=1-t;result.push([u*u*u*b[0]+3*u*u*t*c1[0]+3*u*t*t*c2[0]+t*t*t*c[0],u*u*u*b[1]+3*u*u*t*c1[1]+3*u*t*t*c2[1]+t*t*t*c[1]]);}
}
return result;
}
function pointInPolygon(point,polygon){
let winding=0;const [x,y]=point;
for(let i=0,j=polygon.length-1;i<polygon.length;j=i++){
const [ax,ay]=polygon[j],[bx,by]=polygon[i],dx=bx-ax,dy=by-ay,cross=(x-ax)*dy-(y-ay)*dx;
if(Math.abs(cross)<1e-7*Math.max(1,Math.hypot(dx,dy))&&x>=Math.min(ax,bx)-1e-7&&x<=Math.max(ax,bx)+1e-7&&y>=Math.min(ay,by)-1e-7&&y<=Math.max(ay,by)+1e-7)return true;
if(ay<=y&&by>y&&cross<0)winding++;else if(ay>y&&by<=y&&cross>0)winding--;
}
return winding!==0;
}
function containment(features){
const cell=300,buckets=new Map(),placed=features.filter(f=>f.isPlaced),byID=new Map(placed.map(f=>[f.featureID,f]));
const areas=new Map(placed.filter(isArea).map(area=>[area.featureID,{area,bounds:null,polygon:null}]));
for(const f of placed){const key=Math.floor(f.x/cell)+','+Math.floor(f.y/cell);if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(f);}
function bounds(record){
if(!record.bounds){const b=featureBounds(record.area),dx=(b.right-b.left)/6+1e-7,dy=(b.bottom-b.top)/6+1e-7;record.bounds={left:b.left-dx,right:b.right+dx,top:b.top-dy,bottom:b.bottom+dy};}
return record.bounds;
}
function contains(record,f){
if(record.area===f)return false;
const b=bounds(record);if(f.x<b.left||f.x>b.right||f.y<b.top||f.y>b.bottom)return false;
record.polygon||=outline(record.area);
return record.polygon.length>=3&&pointInPolygon([f.x,f.y],record.polygon);
}
// Lazy lists avoid materialising an O(n²) containment graph for heavily overlapping maps.
function lists(ids,compute){const map=new Map(ids.map(id=>[id,undefined]));map.get=function(id){let value=Map.prototype.get.call(this,id);if(value===undefined&&this.has(id)){value=compute(id);this.set(id,value);}return value;};return map;}
const inside=lists(features.map(f=>f.featureID),id=>{const f=byID.get(id);return f?[...areas.values()].filter(a=>contains(a,f)).map(a=>a.area.featureID):[];});
const contents=lists([...areas.keys()],id=>{
const record=areas.get(id),b=bounds(record),x1=Math.floor(b.left/cell),x2=Math.floor(b.right/cell),y1=Math.floor(b.top/cell),y2=Math.floor(b.bottom/cell),candidates=[];
if((x2-x1+1)*(y2-y1+1)>placed.length*2)candidates.push(...placed);
else for(let x=x1;x<=x2;x++)for(let y=y1;y<=y2;y++)candidates.push(...(buckets.get(x+','+y)||[]));
return candidates.filter(f=>contains(record,f)).map(f=>f.featureID);
});
return {inside,contents};
}
function fitBoundary(f,items,features){
if(f.isLocked||!hasBoundary(f)||!items.length)return false;
const boxes=items.map(p=>featureBounds(p,features)),left=Math.min(...boxes.map(b=>b.left)),right=Math.max(...boxes.map(b=>b.right)),top=Math.min(...boxes.map(b=>b.top)),bottom=Math.max(...boxes.map(b=>b.bottom));
const margin=Math.max(35,(right-left)*.1,(bottom-top)*.1),width=Math.max(100,right-left+margin*2),height=Math.max(100,bottom-top+margin*2),offsetX=(left+right)/2-f.x,offsetY=(top+bottom)/2-f.y;
if(width>100000||height>100000||Math.abs(offsetX)>200000||Math.abs(offsetY)>200000)return false;
updateArea(f,b=>Object.assign(b,{offsetX,offsetY,width,height,rotation:0,points:[[-.5,-.5],[0,-.5],[.5,-.5],[.5,0],[.5,.5],[0,.5],[-.5,.5],[-.5,0]]}));return true;
}
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];
@ -129,5 +209,5 @@
f.width*=ratio;f.height*=ratio;f.rotation=normalAngle(f.rotation+angle*180/Math.PI);return f;
}
const normalAngle=value=>((value+180)%360+360)%360-180;
return {transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange};
return {settlements,isSettlement,hasBoundary,isArea,convertToArea,areaGeometry,updateArea,areaFrame,worldToLocal,translate,moveAnchor,featureBounds,outline,pointInPolygon,containment,fitBoundary,transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange};
});

View File

@ -5,14 +5,17 @@
const ns='http://www.w3.org/2000/svg',esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const guid=()=>crypto.randomUUID(), clone=E.copy;const windowParams=new URLSearchParams(location.search),detachedQuery=windowParams.get('detached')==='true'?'&detached=true'+(windowParams.get('workspace')?'&workspace='+encodeURIComponent(windowParams.get('workspace')):''):'';
let savedDocument=clone(boot.document),leavePending=null,rotationEdit=null;
let doc=boot.document,mode='create',selected=new Set(),pending=null,dirty=false,busy=false,history=[],future=[],preview=null,shapeEdit=false,parentFeature=null;
let doc=boot.document,mode='create',selected=new Set(),pending=null,dirty=false,busy=false,history=[],future=[],preview=null,shapeEdit=false,parentFeature=null,settlementMode='whole';
let view={x:-600,y:-400,w:1200,h:800},drag=null,clipboard=null;
const hiddenLayers=new Set(),nodes=new Map();
const hiddenLayers=new Set(),nodes=new Map(),boundaryNodes=new Map();
let containmentDirty=true,containmentCache=null;
function containment(){if(containmentDirty||!containmentCache){containmentCache=E.containment(doc?.features||[]);containmentDirty=false;}return containmentCache;}
const targetID=node=>node?.dataset.featureId||node?.dataset.boundaryFeatureId;
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 changed(message='Unsaved changes'){containmentDirty=true;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||!!window.PlotDirectorMapAppearance?.adjusting; $('mapsRedo').disabled=!future.length||!!preview||!!window.PlotDirectorMapAppearance?.adjusting; $('mapsSave').disabled=!doc||busy||!!preview||!!window.PlotDirectorMapAppearance?.adjusting||mode!=='create'; }
async function request(action,data,json=false){
@ -29,7 +32,7 @@
const saved=await request('Save',JSON.parse(sent),true);
if(saved?.map?.mapID!==doc.map.mapID||saved.map.projectID!==boot.projectId||!Number.isSafeInteger(saved.map.revision)||!Array.isArray(saved.features)||!Array.isArray(saved.relationships))throw new Error('The saved map could not be verified. Your edits remain here. Please try again.');
// Editing is disabled while saving; server-created Location links become canonical before further edits.
doc=saved;savedDocument=clone(saved);dirty=false;window.dispatchEvent(new CustomEvent('pd-map-saved'));window.PlotDirectorWorkspaceBridge?.send('map-saved',{mapID:saved.map.mapID,revision:saved.map.revision});
doc=saved;containmentDirty=true;savedDocument=clone(saved);dirty=false;window.dispatchEvent(new CustomEvent('pd-map-saved'));window.PlotDirectorWorkspaceBridge?.send('map-saved',{mapID:saved.map.mapID,revision:saved.map.revision});
const reconcile=entry=>{const prior=JSON.parse(entry);prior.map.revision=saved.map.revision;for(const f of prior.features){const canonical=saved.features.find(x=>x.featureID===f.featureID);if(canonical?.locationID&&f.createLocation){f.locationID=canonical.locationID;f.createLocation=false;}}return JSON.stringify(prior);};
history=history.map(reconcile);future=future.map(reconcile);boot.document=doc;
const known=boot.maps.find(m=>m.mapID===doc.map.mapID);if(known)Object.assign(known,doc.map);
@ -50,7 +53,7 @@
{label:'Discard changes',value:'discard',className:'btn-outline-danger'},
{label:'Keep editing',value:'keep'}]});
if(!['save','discard'].includes(answer?.value))return false;
if(answer.value==='discard'){doc=clone(savedDocument);dirty=false;history=[];future=[];preview=null;pending=null;selected=new Set([...selected].filter(id=>doc?.features.some(f=>f.featureID===id)));render();details();locations();updateButtons();}
if(answer.value==='discard'){doc=clone(savedDocument);containmentDirty=true;dirty=false;history=[];future=[];preview=null;pending=null;selected=new Set([...selected].filter(id=>doc?.features.some(f=>f.featureID===id)));render();details();locations();updateButtons();}
await action();return true;
}finally{leavePending=null;}
}
@ -73,15 +76,28 @@
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||[]){const reference=arguments.length===0?window.PlotDirectorMapAppearanceEngine?.reference(doc?.map):null;if(reference?.isVisible)items=[...items,{...reference,geometryClass:'Area',geometryJson:JSON.stringify({points:[[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]]})}];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.geometryClass==='Area'?(E.geometry(f).points||[[-.5,-.5],[.5,.5]]).map(p=>E.localToWorld(f,p)):[[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]);}}
for(const f of items){const b=E.featureBounds(f,doc.features);left=Math.min(left,b.left);right=Math.max(right,b.right);top=Math.min(top,b.top);bottom=Math.max(bottom,b.bottom);}
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<ratio)w=h*ratio;else h=w/ratio;
view={x:(left+right-w)/2,y:(top+bottom-h)/2,w,h};applyView();}
function zoom(factor,point){const center=point||[view.x+view.w/2,view.y+view.h/2],w=Math.min(12000,Math.max(180,view.w*factor)),ratio=w/view.w;view={x:center[0]-(center[0]-view.x)*ratio,y:center[1]-(center[1]-view.y)*ratio,w,h:view.h*ratio};applyView();}
function areaMarkup(f,boundary=false){
const frame=E.areaFrame(f),geometry=E.areaGeometry(f),a=geometry.appearance||{},overlay=f.layer==='Regions';
const colour=(value,fallback)=>/^#[0-9a-f]{6}$/i.test(value||'')?value:fallback;
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 fill=colour(a.fillColor,boundary?'var(--maps-settlement-fill,#9670aa)':overlay?'#ac9cc6':fills[f.type]||'var(--maps-land,#e9e4c5)');
const stroke=colour(a.borderColor,boundary?'var(--maps-settlement-line,#62507c)':overlay?'var(--maps-region-line,#80699b)':'var(--maps-terrain-line,#91a087)');
const opacity=Number.isFinite(a.fillOpacity)?Math.max(0,Math.min(1,a.fillOpacity)):boundary?.22:overlay?.25:1;
const width=Number.isFinite(a.borderWidth)?Math.max(0,Math.min(30,a.borderWidth)):2;
const dash=({'Solid':'','Dashed':'8 5','Dotted':'2 5'})[a.borderStyle]??(overlay?'8 5':'');
const points=E.coastline(frame).map(p=>[p[0]*frame.width,p[1]*frame.height]);
return `<path class="map-shape${boundary?' map-boundary-shape':''}" d="${E.curve(points,true)}" transform="translate(${frame.x} ${frame.y}) rotate(${frame.rotation})" fill="${fill}" fill-opacity="${opacity}" stroke="${stroke}" stroke-width="${width}" ${dash?`stroke-dasharray="${dash}"`:''}/>`;
}
function render(affected=null){
if(!doc)return;window.PlotDirectorMapAppearance?.render();
const visible=(preview?.features||doc.features).filter(f=>!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);}
for(const[id,node]of boundaryNodes)if(!alive.has(id)||!E.hasBoundary(visible.find(f=>f.featureID===id))){node.remove();boundaryNodes.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){
@ -90,6 +106,13 @@
const isSelected=selected.has(f.featureID);g.setAttribute('class',`maps-feature${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}${f.isLocked?' is-locked':''}`);g.setAttribute('aria-label',`${f.name}, ${f.type}${f.isProvisional?', planning':''}${childIDs.has(f.featureID)?', detailed map available':''}`);g.setAttribute('aria-pressed',String(isSelected));
// Reconcile individual keyed pieces; the shell, canvas, focus and sidebars remain stable.
let markup='';
if(E.hasBoundary(f)){
let boundary=boundaryNodes.get(f.featureID);
if(!boundary){boundary=svgNode('g',{'data-boundary-feature-id':f.featureID,tabindex:'0',role:'button'});boundaryNodes.set(f.featureID,boundary);scene.append(boundary);}
boundary.setAttribute('class',`maps-boundary${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}`);
boundary.setAttribute('aria-label',f.name+' boundary');boundary.setAttribute('aria-pressed',String(isSelected));
const outline=areaMarkup(f,true);if(boundary.innerHTML!==outline)boundary.innerHTML=outline;
}
if(f.geometryClass==='Marker'){
const symbol=E.library.find(a=>a.type===f.type)?.symbol||'◆',size=Math.min(46,Math.max(26,f.width/Math.max(.7,scale)))*scale;
markup=`<g transform="translate(${f.x} ${f.y})"><circle class="map-shape" r="${size/2}" fill="var(--maps-marker-bg,#faf5df)" stroke="var(--maps-map-ink,#667d65)" stroke-width="${1.5*scale}" vector-effect="non-scaling-stroke"/><g class="map-symbol" transform="translate(${-size*.39} ${-size*.39}) scale(${size*.78/24})" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">${window.PlotDirectorMapSymbols.content(f.type)}</g></g>`;
@ -101,9 +124,11 @@
if(rail)markup+=`<path d="${d}" fill="none" stroke="var(--maps-map-ink,#5b635d)" stroke-width="10" stroke-dasharray="2 12" pointer-events="none"/>`;
markup+=`<path d="${d}" fill="none" stroke="transparent" stroke-width="${Math.max(18*scale,width)}"/>`;
}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=`<path class="map-shape" d="${E.curve(points,true)}" transform="translate(${f.x} ${f.y}) rotate(${f.rotation})" fill="${overlay?'#ac9cc6':fills[f.type]||'var(--maps-land,#e9e4c5)'}" fill-opacity="${overlay?.25:1}" stroke="${overlay?'var(--maps-region-line,#80699b)':'var(--maps-terrain-line,#91a087)'}" stroke-width="2" ${overlay?'stroke-dasharray="8 5"':''}/>`;
markup=areaMarkup(f);
}
if(isSelected&&E.isSettlement(f)){
const r=27*scale,gap=18*scale;
markup+=`<path class="maps-anchor-crosshair" d="M${f.x-r} ${f.y}h${r-gap} M${f.x+gap} ${f.y}h${r-gap} M${f.x} ${f.y-r}v${r-gap} M${f.x} ${f.y+gap}v${r-gap}" fill="none" stroke="var(--maps-selection,#136883)" stroke-width="${2*scale}" pointer-events="none"/>`;
}
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;
@ -113,21 +138,33 @@
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);});
if(!affected){
const layers=[],outlines=ordered.filter(E.hasBoundary).map(f=>boundaryNodes.get(f.featureID));let inserted=false;
for(const f of ordered){if(!inserted&&f.zOrder>=30){layers.push(...outlines);inserted=true;}layers.push(nodes.get(f.featureID));}
if(!inserted)layers.push(...outlines);
layers.forEach((node,i)=>{if(scene.children[i]!==node)scene.insertBefore(node,scene.children[i]||null);});
}
renderHandles(scale);
window.PlotDirectorStoryOverlay?.redraw();
}
function renderHandles(scale){handles.replaceChildren();if(mode!=='create'||preview||selected.size!==1)return;const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked)return;
const add=(p,type,index)=>handles.append(svgNode('circle',{cx:p[0],cy:p[1],r:9*scale,class:'maps-handle','data-handle':type,'data-index':index??'',tabindex:'0',role:'button','aria-label':type==='endpoint'?'Turn and extend path endpoint':type==='point'?'Move shape point':'Resize selected feature'}));
const pts=E.geometry(f).points||[];
if(f.geometryClass==='Path'){
function renderHandles(scale){
const active=handles.contains(document.activeElement)?{type:document.activeElement.dataset.handle,index:document.activeElement.dataset.index}:null;
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:9*scale,class:'maps-handle','data-handle':type,'data-index':index??'','data-handle-feature-id':f.featureID,tabindex:'0',role:'button','aria-label':type==='anchor'?'Move anchor; keep boundary fixed':type==='endpoint'?'Turn and extend path endpoint':type==='point'?'Move shape point':'Resize boundary or area'}));
const frame=E.areaFrame(f),pts=E.isArea(f)?E.areaGeometry(f).points||[]:E.geometry(f).points||[];
if(E.hasBoundary(f)&&settlementMode==='anchor')add([f.x,f.y],'anchor');
else if(f.geometryClass==='Path'){
const actual=E.pathPoints(f,doc.features);if(!f.startFeatureID)add(actual[0],'endpoint',0);if(!f.endFeatureID)add(actual.at(-1),'endpoint',pts.length-1);
if(shapeEdit)pts.forEach((p,i)=>{if(i>0&&i<pts.length-1)add(E.localToWorld(f,p),'point',i);});
}else if(shapeEdit&&f.geometryClass!=='Marker')pts.forEach((p,i)=>add(E.localToWorld(f,p),'point',i));
else if(f.geometryClass!=='Marker')add(E.localToWorld(f,[.5,.5]),'resize');
}else if(E.isArea(f)){
if(shapeEdit)pts.forEach((p,i)=>add(E.localToWorld(frame,p),'point',i));
add(E.localToWorld(frame,[.5,.5]),'resize');
}
if(active)handles.querySelector(`[data-handle="${active.type}"][data-index="${active.index}"]`)?.focus({preventScroll:true});
}
function select(id,extend=false){window.PlotDirectorMapAppearance?.clearSelection();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;window.PlotDirectorMapAppearance?.clearSelection();safeEdit(()=>{const f=E.makeFeature(type,point[0],point[1],guid());if(locationID){const l=boot.locations.find(l=>l.locationID===locationID);f.locationID=locationID;f.name=l.locationName;f.isProvisional=false;}doc.features.push(f);selected=new Set([f.featureID]);shapeEdit=false;});pending=null;svg.classList.remove('placing');$('mapName')?.focus();}
function select(id,extend=false){window.PlotDirectorMapAppearance?.clearSelection();if(!extend)selected.clear();if(extend&&selected.has(id))selected.delete(id);else selected.add(id);shapeEdit=false;settlementMode='whole';render();details();}
function place(type,point,locationID=null){if(!doc||busy||mode!=='create')return;window.PlotDirectorMapAppearance?.clearSelection();safeEdit(()=>{const f=E.makeFeature(type,point[0],point[1],guid());settlementMode='whole';if(locationID){const l=boot.locations.find(l=>l.locationID===locationID);f.locationID=locationID;f.name=l.locationName;f.isProvisional=false;}doc.features.push(f);selected=new Set([f.featureID]);shapeEdit=false;});pending=null;svg.classList.remove('placing');$('mapName')?.focus();}
function library(){const categories=[...new Set(E.library.map(a=>a.category))];$('mapsCategory').innerHTML='<option value="">All categories</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');
for(const layer of ['Terrain','Water','Vegetation','Places','Routes','Regions','Labels']){const label=document.createElement('label');label.innerHTML=`<input type="checkbox" checked data-layer="${layer}" /> ${layer}`;$('mapsLayers').append(label);}assets();}
function assets(){const q=$('mapsAssetSearch').value.toLowerCase(),category=$('mapsCategory').value;$('mapsAssets').innerHTML=E.library.filter(a=>(!q||a.type.toLowerCase().includes(q))&&(!category||a.category===category)).map(a=>`<button type="button" draggable="true" data-asset="${esc(a.type)}" title="Place ${esc(a.type)}">${window.PlotDirectorMapSymbols.svg(a.type)}${esc(a.type)}</button>`).join('');}
@ -136,6 +173,23 @@
function option(value,label,selectedValue){return `<option value="${esc(value)}" ${String(value??'')===String(selectedValue??'')?'selected':''}>${esc(label)}</option>`;}
function field(label,key,value,type='text',attrs=''){if(['width','height','labelX','labelY'].includes(key)){value=Math.round(value);attrs+=' data-initial-display="'+value+'"';}return `<label>${label}<input data-field="${key}" type="${type}" value="${esc(value)}" ${attrs}/></label>`;}
function check(label,key,value){return `<label><input data-field="${key}" type="checkbox" ${value?'checked':''}/> ${label}</label>`;}
function areaField(label,key,value,attrs=''){return `<label>${label}<input data-area-frame="${key}" type="number" value="${Math.round(value*100)/100}" ${attrs}/></label>`;}
function fitContents(f){
const inside=new Set(containment().contents.get(f.featureID)||[]),locations=new Map(boot.locations.map(l=>[l.locationID,l]));
return doc.features.filter(other=>{
if(other===f||!other.isPlaced||other.geometryClass==='Path')return false;
if(inside.has(other.featureID))return true;
if(!f.locationID||!other.locationID)return false;
let current=locations.get(other.locationID),seen=new Set();
while(current&&!seen.has(current.locationID)){seen.add(current.locationID);if(current.parentLocationID===f.locationID)return true;current=locations.get(current.parentLocationID);}
return false;
});
}
function containmentDetails(f){
const c=containment(),areas=c.inside.get(f.featureID)||[],children=c.contents.get(f.featureID)||[];
const links=ids=>ids.map(id=>{const item=doc.features.find(x=>x.featureID===id);return `<button type="button" data-select-map-piece="${id}">${esc(item?.name)}</button>`;}).join(' ');
return `<details><summary>Geographical containment</summary><p>Anchor inside: ${areas.length?links(areas):'No mapped area'}</p>${E.isArea(f)?`<p>Anchors within this area: ${children.length?links(children):'None'}</p>`:''}<p class="maps-hint">Derived from the drawn boundaries. Pieces keep their own positions and story Location relationships; overlapping areas are all retained.</p></details>`;
}
function details(){
const content=$('mapsDetailContent');
if(!doc){content.textContent='Create or open a map to begin.';return;}
@ -151,16 +205,24 @@
if(readonly){html+=f.notes?`<p>${esc(f.notes)}</p>`:'';if(linked)html+=`<a href="/Locations/Details/${f.locationID}">Open story Location: ${esc(linked.locationName)}</a>`;}
else{
html+=`<div class="maps-edit-only">${field('Name','name',f.name,'text','id="mapName" maxlength="200"')}`;
if(f.geometryClass==='Marker')html+=`<label>Appear as <select data-field="type">${E.library.filter(a=>a.geometryClass==='Marker').map(a=>option(a.type,a.type,f.type)).join('')}</select></label>`;
if(f.geometryClass==='Marker')html+=`<label>Appear as <select data-field="type">${E.library.filter(a=>a.geometryClass==='Marker'&&(!E.hasBoundary(f)||E.settlements.includes(a.type))).map(a=>option(a.type,a.type,f.type)).join('')}</select></label>`;
html+=check('Planning / provisional','isProvisional',f.isProvisional)+check('Lock position','isLocked',f.isLocked)+check('Show label','showLabel',f.showLabel);
html+=`<details><summary>Story Location</summary><p>A map feature can exist without a story Location.</p><label>Link existing <select data-field="locationID">${option('','None',f.locationID)}${boot.locations.filter(l=>!l.isArchived).map(l=>option(l.locationID,l.locationName,f.locationID)).join('')}</select></label>`;
if(!f.locationID)html+=check('Create a story Location when saved (establishes this place)','createLocation',f.createLocation);
if(linked)html+=`<a href="/Locations/Details/${f.locationID}">Open ${esc(linked.locationName)}</a>`;
html+='</details>';
if(f.geometryClass!=='Marker'){
html+=`<details open><summary>Shape</summary>${field('Width','width',f.width,'number','min="10" max="10000"')}${field('Height','height',f.height,'number','min="10" max="10000"')}<label>Rotate <span class="maps-rotation"><input aria-label="Rotate" data-rotate type="range" min="-180" max="180" value="${Math.round(E.normalAngle(f.rotation))}" ${f.startFeatureID||f.endFeatureID?'disabled':''}/><input aria-label="Rotation degrees" data-rotate type="number" step="0.1" min="-180" max="180" value="${Math.round(E.normalAngle(f.rotation)*10)/10}" ${f.startFeatureID||f.endFeatureID?'disabled':''}/><span>°</span><button type="button" data-reset-rotation ${f.startFeatureID||f.endFeatureID?'disabled':''}>Reset</button></span></label>`;
if(['Land Mass','Island'].includes(f.type))html+=`<label>Coastline <select data-geometry="coast">${['Gentle','Natural','Rugged','Cliffs','Fjords','Marsh/Delta'].map(c=>option(c,c,E.geometry(f).coast)).join('')}</select></label>`;
html+=`<div class="maps-inline"><button type="button" data-action="shape">${shapeEdit?'Finish shape':'Edit shape'}</button><button type="button" data-action="bend">Add ${f.geometryClass==='Path'?'bend':'shape point'}</button></div><p class="maps-hint">${f.geometryClass==='Path'?'Drag a free endpoint to turn and extend; edit bends to reshape. Attached endpoints stay connected.':'Drag the corner to resize, or edit a few shape points.'}</p></details>`;
if(E.isSettlement(f)&&!E.hasBoundary(f))html+=`<button type="button" data-action="convert-area" ${f.isLocked?'disabled':''}>Convert to area</button><p class="maps-hint">Adds a boundary without moving this anchor or changing connections.</p>`;
if(E.hasBoundary(f))html+=`<fieldset ${f.isLocked?'disabled':''}><legend class="maps-hint">Settlement editing</legend><div class="maps-inline">${[['whole','Move settlement'],['boundary','Edit boundary'],['anchor','Move anchor']].map(([value,label])=>`<button type="button" data-settlement-mode="${value}" aria-pressed="${settlementMode===value}">${label}</button>`).join('')}</div><p class="maps-hint">${settlementMode==='anchor'?'Drag the anchor handle; the boundary stays fixed and roads follow the anchor.':settlementMode==='boundary'?'Drag the outline to move only the boundary, or drag control points to reshape. The anchor and buildings stay fixed.':'Drag the settlement to translate its anchor and boundary together. Contained pieces remain independent.'}</p><button type="button" data-action="fit-boundary" ${fitContents(f).length?'':'disabled'}>Fit boundary to contents</button><p class="maps-hint">Uses enclosed pieces and story-linked descendants with a margin; never moves them.</p></fieldset>`;
if(f.geometryClass!=='Marker'||E.hasBoundary(f)){
const frame=E.areaFrame(f),g=E.isArea(f)?E.areaGeometry(f):E.geometry(f);
html+=`<details open><summary>${E.hasBoundary(f)?'Boundary':'Shape'}</summary><fieldset ${f.isLocked?'disabled':''}>${E.hasBoundary(f)?areaField('Boundary width','width',frame.width,'min="10" max="100000"')+areaField('Boundary height','height',frame.height,'min="10" max="100000"'):field('Width','width',f.width,'number','min="10" max="10000"')+field('Height','height',f.height,'number','min="10" max="10000"')}<label>Rotate <span class="maps-rotation"><input aria-label="Rotate" data-rotate type="range" min="-180" max="180" value="${Math.round(E.normalAngle(frame.rotation))}" ${f.startFeatureID||f.endFeatureID?'disabled':''}/><input aria-label="Rotation degrees" data-rotate type="number" step="0.1" min="-180" max="180" value="${Math.round(E.normalAngle(frame.rotation)*10)/10}" ${f.startFeatureID||f.endFeatureID?'disabled':''}/><span>°</span><button type="button" data-reset-rotation ${f.startFeatureID||f.endFeatureID?'disabled':''}>Reset</button></span></label>`;
if(['Land Mass','Island'].includes(f.type)||E.hasBoundary(f))html+=`<label>${E.hasBoundary(f)?'Boundary smoothing':'Coastline'} <select data-geometry="coast">${['Gentle','Natural','Rugged','Cliffs','Fjords','Marsh/Delta'].map(c=>option(c,c,g.coast)).join('')}</select></label>`;
html+=`<div class="maps-inline"><button type="button" data-action="shape">${shapeEdit?'Finish shape':'Edit shape'}</button><button type="button" data-action="bend">Add ${f.geometryClass==='Path'?'bend':'shape point'}</button></div><p class="maps-hint">Drag the corner to resize. Edit points to reshape; right-click a point or press Delete to remove it.</p>`;
if(E.isArea(f)){
const a=g.appearance||{},palette=window.PlotDirectorMapAppearanceEngine.palette(doc.map),fill=a.fillColor||(E.hasBoundary(f)?palette.settlement:palette.landColor),border=a.borderColor||(E.hasBoundary(f)?palette.settlementLine:f.layer==='Regions'?palette.region:palette.dark?'#8da18c':'#91a087');
html+=`<label>${E.hasBoundary(f)?'Fill colour':'Fill colour override'} <input type="color" data-area-style="fillColor" value="${esc(fill)}" /></label><label>Fill opacity <input type="number" data-area-style="fillOpacity" min="0" max="1" step="0.05" value="${a.fillOpacity??(E.hasBoundary(f)?.22:f.layer==='Regions'?.25:1)}" /></label><label>Border colour <input type="color" data-area-style="borderColor" value="${esc(border)}" /></label><label>Border width <input type="number" data-area-style="borderWidth" min="0" max="30" step="0.5" value="${a.borderWidth??2}" /></label><label>Border style <select data-area-style="borderStyle">${['Solid','Dashed','Dotted'].map(v=>option(v,v,a.borderStyle||'Solid')).join('')}</select></label><button type="button" data-action="area-style-reset">Use theme defaults</button>`;
}
html+='</fieldset></details>';
}
if(f.geometryClass==='Path')html+=`<details open><summary>Connections</summary><p>Endpoints stay attached as places move.</p>${['startFeatureID','endFeatureID'].map((key,i)=>`<label>${i?'End':'Start'} <select data-field="${key}">${option('','Unattached',f[key])}${doc.features.filter(x=>x.geometryClass==='Marker').map(x=>option(x.featureID,x.name,f[key])).join('')}</select></label>`).join('')}</details>`;
html+=`<details><summary>Labels & notes</summary>${field('Label across','labelX',f.labelX,'number')}${field('Label down','labelY',f.labelY,'number')}<label>Notes <textarea data-field="notes" maxlength="4000">${esc(f.notes)}</textarea></label></details>`;
@ -170,6 +232,7 @@
if(child)html+=`<p><a href="${url(child.mapID)}">Open detailed map: ${esc(child.name)} ↳</a></p>`;
else if(!readonly)html+='<p><button type="button" data-action="child">Create detailed map</button></p>';
if(f.floorPlanID)html+=`<p><a href="/FloorPlans/Edit/${f.floorPlanID}">Open Floor Plan</a></p>`;
html+=containmentDetails(f);
html+=`<details open><summary>Spatial relationships</summary><p class="maps-hint">Directions and distances describe intent; placement remains yours.</p>`;
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);
@ -182,12 +245,22 @@
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=`<form><h2>Spatial relationship</h2><label>Place <select name="sourceID">${doc.features.map(x=>option(x.featureID,x.name,r.sourceID)).join('')}</select></label><label>Direction from the other place <select name="direction">${option('','Unspecified',r.direction)}${E.directions.map(x=>option(x,x,r.direction)).join('')}</select></label><label>Other place <select name="targetID">${doc.features.map(x=>option(x.featureID,x.name,r.targetID)).join('')}</select></label><label>Relative distance <select name="relativeDistance">${option('','Unspecified',r.relativeDistance)}${E.distances.map(x=>option(x,x,r.relativeDistance)).join('')}</select></label><details><summary>Known distance / typical travel time</summary><label>Measured distance (optional)<input name="measuredDistance" type="number" min="0" step="0.001" value="${esc(r.measuredDistance??'')}" /></label><label>Unit <input name="unit" maxlength="30" placeholder="e.g. kilometres, miles" value="${esc(r.unit)}" /></label><label>Typical travel time <input name="typicalTravelTime" maxlength="120" placeholder="e.g. 2 hours on foot" value="${esc(r.typicalTravelTime)}" /></label></details><button type="button" data-cancel>Cancel</button><button type="submit">Keep relationship</button></form>`;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 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));settlementMode='whole';shapeEdit=false;});}
function removePoint(f,index){
const points=E.isArea(f)?E.areaGeometry(f).points:E.geometry(f).points;
if(f.isLocked||!points||!Number.isInteger(index)||index<0||index>=points.length||points.length<=(f.geometryClass==='Path'?2:3))return;
if(f.geometryClass==='Path'&&(index===0||index===points.length-1))return;
safeEdit(()=>{if(E.isArea(f))E.updateArea(f,g=>g.points.splice(index,1));else{const g=E.geometry(f);g.points.splice(index,1);f.geometryJson=JSON.stringify(g);}});
}
function action(name){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f)return;
if(f.isLocked&&['convert-area','fit-boundary','shape','bend','area-style-reset','unplace'].includes(name))return;
if(name==='convert-area'&&E.isSettlement(f)&&!E.hasBoundary(f)){safeEdit(()=>E.convertToArea(f));shapeEdit=true;settlementMode='boundary';render();details();return;}
if(name==='fit-boundary'){const items=fitContents(f);if(!items.length){status('No enclosed or story-linked pieces to fit.');return;}safeEdit(()=>E.fitBoundary(f,items,doc.features));return;}
if(name==='area-style-reset')safeEdit(()=>E.updateArea(f,g=>delete g.appearance));
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==='relationship')relationEditor();if(name==='child')newMap(f);if(name==='shape'){shapeEdit=!shapeEdit;if(E.hasBoundary(f))settlementMode=shapeEdit?'boundary':'whole';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;i<pts.length-(f.geometryClass==='Path'?1:0);i++){const next=pts[(i+1)%pts.length],len=Math.hypot(next[0]-pts[i][0],next[1]-pts[i][1]);if(len>longest){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;});
if(name==='bend')safeEdit(()=>{const g=E.isArea(f)?E.areaGeometry(f):E.geometry(f),pts=g.points||[];if(pts.length>=64)return;let index=0,longest=0;for(let i=0;i<pts.length-(f.geometryClass==='Path'?1:0);i++){const next=pts[(i+1)%pts.length],len=Math.hypot(next[0]-pts[i][0],next[1]-pts[i][1]);if(len>longest){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;if(E.isArea(f))E.updateArea(f,target=>target.points=pts);else f.geometryJson=JSON.stringify(g);shapeEdit=true;if(E.hasBoundary(f))settlementMode='boundary';});
}
function definePlace(){
if(!doc||busy||mode!=='create')return;
@ -197,7 +270,7 @@
const f=E.makeFeature(v.type,view.x+view.w/2,view.y+view.h/2,guid());f.name=v.name.trim();if(!f.name)return;
if(v.targetID){const target=doc.features.find(x=>x.featureID===v.targetID);f.x=target.x;f.y=target.y;f.isPlaced=false;const r={relationshipID:guid(),sourceID:f.featureID,targetID:v.targetID,direction:v.direction,relativeDistance:v.relativeDistance,measuredDistance:null,unit:null,typicalTravelTime:null,notes:null};doc.relationships.push(r);
const arranged=E.arrange([...doc.features.map(x=>({...x,isPlaced:true})),f],doc.relationships,true).features.find(x=>x.featureID===f.featureID);Object.assign(f,{x:arranged.x,y:arranged.y,isPlaced:true});}
doc.features.push(f);selected=new Set([f.featureID]);
doc.features.push(f);selected=new Set([f.featureID]);settlementMode='whole';shapeEdit=false;
});dialog.close();};
}
async function newMap(feature=null){const intent=feature?{featureID:feature.featureID,name:feature.name}:null;return requestLeave(()=>openNewMap(intent));}
@ -216,6 +289,8 @@
// 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;window.PlotDirectorMapAppearance?.completeAdjustment();if(modeButton.dataset.mode==='story'&&dirty){requestLeave(()=>modeButton.click());return;}mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange','mapsGeographic'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();updateButtons();window.dispatchEvent(new CustomEvent('pd-map-mode',{detail:mode}));return;}
const choose=e.target.closest('[data-select-map-piece]');if(choose){select(choose.dataset.selectMapPiece);return;}
const editMode=e.target.closest('[data-settlement-mode]');if(editMode){const f=doc?.features.find(f=>selected.has(f.featureID));if(f&&!f.isLocked&&mode==='create'&&!busy&&!preview){settlementMode=editMode.dataset.settlementMode;shapeEdit=settlementMode==='boundary';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);
@ -223,8 +298,14 @@
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();}
});
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;if(e.target.dataset.initialDisplay===e.target.value)return;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;safeEdit(()=>{f[key]=value;if(key==='createLocation'&&value)f.isProvisional=false;if(key==='isProvisional'&&value)f.createLocation=false;if(key==='locationID')f.createLocation=false;});}
if(e.target.matches('[data-geometry]')){const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{const g=E.geometry(f);g[e.target.dataset.geometry]=e.target.value;f.geometryJson=JSON.stringify(g);});}
if(e.target.matches('[data-field]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||busy)return;const key=e.target.dataset.field;if(f.isLocked&&['width','height','rotation','type'].includes(key))return;if(e.target.dataset.initialDisplay===e.target.value)return;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;if(key==='type'&&E.hasBoundary(f)&&!E.settlements.includes(value))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));if(f&&!f.isLocked)safeEdit(()=>E.updateArea(f,g=>g[e.target.dataset.geometry]=e.target.value));}
if(e.target.matches('[data-area-frame],[data-area-style]')){
const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||!E.isArea(f))return;
const key=e.target.dataset.areaFrame||e.target.dataset.areaStyle,value=e.target.type==='number'?Number(e.target.value):e.target.value;
if(typeof value==='number'&&(!Number.isFinite(value)||(['width','height'].includes(key)&&value<10)||(['fillOpacity'].includes(key)&&(value<0||value>1))||(key==='borderWidth'&&(value<0||value>30))))return;
safeEdit(()=>{if(e.target.dataset.areaFrame)E.updateArea(f,b=>b[key]=value);else E.updateArea(f,g=>{g.appearance||={};g.appearance[key]=value;});});
}
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=>`<button type="button" data-search-feature="${f.featureID}">${esc(f.name)} · ${esc(f.type)}</button>`).join(''):'';}});
@ -232,28 +313,32 @@
app.addEventListener('dragstart',e=>{const target=e.target.closest('[data-asset],[data-location]');if(!target)return;e.dataTransfer.setData('application/plotdirector-map',JSON.stringify({type:target.dataset.asset||'Settlement',locationID:Number(target.dataset.location)||null}));e.dataTransfer.effectAllowed='copy';});
svg.addEventListener('dragover',e=>e.preventDefault());svg.addEventListener('drop',e=>{e.preventDefault();try{const data=JSON.parse(e.dataTransfer.getData('application/plotdirector-map'));place(data.type,world(e),data.locationID);}catch{status('Choose a map piece from the library.');}});
svg.addEventListener('pointerdown',e=>{
if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;const p=world(e),target=e.target.closest('[data-feature-id]'),handle=e.target.closest('[data-handle]');
if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;const p=world(e),target=e.target.closest('[data-feature-id],[data-boundary-feature-id]'),handle=e.target.closest('[data-handle]');
e.preventDefault();window.getSelection()?.removeAllRanges();
if(pending){place(pending.type,p,pending.locationID);return;}
if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||mode!=='create')return;const redo=future.slice();checkpoint();drag={redo,kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};}
else if(target){const id=target.dataset.featureId;if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){const redo=future.slice();checkpoint();drag={redo,kind:'move',start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}else drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};}
if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||mode!=='create')return;const redo=future.slice();checkpoint();drag={redo,kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};}
else if(target){const id=targetID(target);if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){const redo=future.slice();checkpoint();drag={redo,kind:E.hasBoundary(f)&&selected.size===1&&settlementMode==='anchor'?'anchor':E.hasBoundary(f)&&selected.size===1&&settlementMode==='boundary'?'boundary':'move',id:f.featureID,original:clone(f),start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}else drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};}
else{if(!e.shiftKey){selected.clear();shapeEdit=false;render();details();}drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};}
if(drag){svg.classList.add('manipulating');svg.setPointerCapture(e.pointerId);}
});
svg.addEventListener('pointermove',e=>{if(!drag)return;const p=world(e),dx=p[0]-drag.start[0],dy=p[1]-drag.start[1];if(Math.abs(dx)+Math.abs(dy)>1)drag.moved=true;
if(drag.kind==='pan'){view.x=drag.original.x-(e.clientX-drag.client[0])*drag.matrix.a;view.y=drag.original.y-(e.clientY-drag.client[1])*drag.matrix.d;svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);return;}
if(drag.kind==='move'){for(const o of drag.originals){const f=doc.features.find(f=>f.featureID===o.featureID);f.x=o.x+dx;f.y=o.y+dy;f.isPlaced=true;}}
else{const f=doc.features.find(f=>f.featureID===drag.id),o=drag.original,a=-o.rotation*Math.PI/180,lx=(p[0]-o.x)*Math.cos(a)-(p[1]-o.y)*Math.sin(a),ly=(p[0]-o.x)*Math.sin(a)+(p[1]-o.y)*Math.cos(a);if(drag.kind==='endpoint'){Object.assign(f,E.transformEndpoint(o,drag.index,p,doc.features));}else if(drag.kind==='resize'){f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}else{const g=E.geometry(f);g.points[drag.index]=[Math.max(-5,Math.min(5,lx/o.width)),Math.max(-5,Math.min(5,ly/o.height))];f.geometryJson=JSON.stringify(g);}}
if(drag.kind==='anchor'){const f=doc.features.find(f=>f.featureID===drag.id);Object.assign(f,clone(drag.original));E.moveAnchor(f,drag.original.x+dx,drag.original.y+dy);}
else if(drag.kind==='boundary'){const f=doc.features.find(f=>f.featureID===drag.id);Object.assign(f,clone(drag.original));E.updateArea(f,b=>{b.offsetX+=dx;b.offsetY+=dy;});}
else 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,frame=E.areaFrame(o),a=-frame.rotation*Math.PI/180,lx=(p[0]-frame.x)*Math.cos(a)-(p[1]-frame.y)*Math.sin(a),ly=(p[0]-frame.x)*Math.sin(a)+(p[1]-frame.y)*Math.cos(a);if(drag.kind==='endpoint'){Object.assign(f,E.transformEndpoint(o,drag.index,p,doc.features));}else if(drag.kind==='resize'){if(E.hasBoundary(f))E.updateArea(f,b=>{b.width=Math.max(20,Math.abs(lx)*2);b.height=Math.max(20,Math.abs(ly)*2);});else{f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}}else{const point=[Math.max(-5,Math.min(5,lx/frame.width)),Math.max(-5,Math.min(5,ly/frame.height))];if(E.isArea(f))E.updateArea(f,g=>g.points[drag.index]=point);else{const g=E.geometry(f);g.points[drag.index]=point;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;svg.classList.remove('manipulating');if(d.frame)cancelAnimationFrame(d.frame);if(svg.hasPointerCapture(e.pointerId))svg.releasePointerCapture(e.pointerId);if(d.kind!=='pan'){if(d.moved){changed();render();details();}else{history.pop();future=d.redo;}updateButtons();}});
function cancelDrag(){svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'&&history.length){doc=JSON.parse(history.pop());future=drag.redo;render();details();}drag=null;}
svg.addEventListener('pointercancel',cancelDrag);svg.addEventListener('lostpointercapture',cancelDrag);
svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID){const destination=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;requestLeave(()=>{location.href=destination;});}}});
svg.addEventListener('dblclick',e=>{const id=targetID(e.target.closest('[data-feature-id],[data-boundary-feature-id]'));if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID){const destination=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;requestLeave(()=>{location.href=destination;});}}});
svg.addEventListener('wheel',e=>{e.preventDefault();zoom(e.deltaY>0?1.12:1/1.12,world(e));},{passive:false});
(window.PlotDirectorContextMenus?.register||((selector,provider)=>{(window.PlotDirectorContextProviders||=[]).push({selector,provider});}))('#mapsCanvas',target=>{
const point=target.closest('[data-handle="point"]');
if(point){const f=doc.features.find(f=>f.featureID===point.dataset.handleFeatureId);if(f)return {invoker:point,commands:[{label:'Remove control point',icon:'remove',disabled:f.isLocked||(E.isArea(f)?E.areaGeometry(f):E.geometry(f)).points.length<=(f.geometryClass==='Path'?2:3),run:()=>removePoint(f,Number(point.dataset.index))}]};}
const referenceMenu=window.PlotDirectorMapAppearance?.context(target);if(referenceMenu)return referenceMenu;
const id=target.closest('[data-feature-id]')?.dataset.featureId;
const id=targetID(target.closest('[data-feature-id],[data-boundary-feature-id]'));
if(id&&!selected.has(id))select(id);
const f=doc?.features.find(f=>f.featureID===id),items=doc?.features.filter(f=>selected.has(f.featureID))||[],commands=[];
const add=(label,icon,run,disabled=false)=>commands.push({label,icon,run,disabled});
@ -265,7 +350,7 @@
else if(mode==='create')add('Create detailed map','add',()=>newMap(f));
if(f.locationID)add('Open Location','locations',()=>requestLeave(()=>{location.href='/Locations/Details/'+f.locationID;}));
if(f.floorPlanID)add('Open Floor Plan','floorplans',()=>requestLeave(()=>{location.href=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;}));
if(mode==='create'){add('Add relationship','relationships',()=>action('relationship'));if(f.geometryClass!=='Marker')add('Edit shape / bends','writer',()=>action('shape'),f.isLocked);}
if(mode==='create'){if(E.isSettlement(f)&&!E.hasBoundary(f))add('Convert to area','auto-arrange',()=>action('convert-area'),f.isLocked);if(E.hasBoundary(f))add('Fit boundary to contents','auto-arrange',()=>action('fit-boundary'),f.isLocked||!fitContents(f).length);add('Add relationship','relationships',()=>action('relationship'));if(f.geometryClass!=='Marker'||E.hasBoundary(f))add('Edit shape / bends','writer',()=>action('shape'),f.isLocked);}
}
if(mode==='create'){
add('Copy','copy',()=>{clipboard=clone(items);});add('Duplicate','copy',()=>duplicate(items));
@ -291,13 +376,14 @@
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);}
const point=e.target.closest('[data-handle=point]');if(point&&(e.key==='Delete'||e.key==='Backspace')){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));if(f)removePoint(f,Number(point.dataset.index));return;}
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==='endpoint'){const i=Number(handle.dataset.index),p=E.pathPoints(f,doc.features)[i],step=e.shiftKey?20:5;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;Object.assign(f,E.transformEndpoint(f,i,p,doc.features));}else if(handle.dataset.handle==='point'){const g=E.geometry(f),p=g.points[Number(handle.dataset.index)],step=e.shiftKey?.05:.01;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;f.geometryJson=JSON.stringify(g);}else{f.width=Math.max(20,f.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));f.height=Math.max(20,f.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));}});return;}
const focused=e.target.closest('[data-feature-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(focused.dataset.featureId,e.shiftKey);}
if(selected.size&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const step=e.shiftKey?20:5;safeEdit(()=>doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked).forEach(f=>{f.x+=(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0);f.y+=(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0);}));}
const handle=e.target.closest('[data-handle]');if(handle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{if(handle.dataset.handle==='endpoint'){const i=Number(handle.dataset.index),p=E.pathPoints(f,doc.features)[i],step=e.shiftKey?20:5;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;Object.assign(f,E.transformEndpoint(f,i,p,doc.features));}else if(handle.dataset.handle==='point'){const g=E.isArea(f)?E.areaGeometry(f):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;if(E.isArea(f))E.updateArea(f,target=>target.points=g.points);else f.geometryJson=JSON.stringify(g);}else if(handle.dataset.handle==='anchor'){const step=e.shiftKey?20:5;E.moveAnchor(f,f.x+(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0),f.y+(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0));}else{if(E.hasBoundary(f))E.updateArea(f,b=>{b.width=Math.max(20,b.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));b.height=Math.max(20,b.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));});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],[data-boundary-feature-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(targetID(focused),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=>{const dx=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0,dy=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;if(E.hasBoundary(f)&&settlementMode==='anchor')E.moveAnchor(f,f.x+dx,f.y+dy);else if(E.hasBoundary(f)&&settlementMode==='boundary')E.updateArea(f,b=>{b.offsetX+=dx;b.offsetY+=dy;});else E.translate(f,dx,dy);}));}
});
function rotate(value,commit=false){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||busy||mode!=='create'||f.startFeatureID||f.endFeatureID)return;if(!Number.isFinite(value))return;
if(!rotationEdit&&f.rotation===E.normalAngle(value))return;if(!rotationEdit){checkpoint();rotationEdit=f.featureID;}f.rotation=E.normalAngle(value);changed();render();document.querySelectorAll('[data-rotate]').forEach(n=>n.value=String(n.type==='range'?Math.round(f.rotation):Math.round(f.rotation*10)/10));if(commit){const active=document.activeElement,focus=active?.matches('[data-rotate]')?'input[data-rotate][type="'+active.type+'"]':active?.matches('[data-reset-rotation]')?'[data-reset-rotation]':null;rotationEdit=null;details();if(focus)document.querySelector(focus)?.focus({preventScroll:true});}}
if(!rotationEdit&&E.areaFrame(f).rotation===E.normalAngle(value))return;if(!rotationEdit){checkpoint();rotationEdit=f.featureID;}if(E.hasBoundary(f))E.updateArea(f,b=>b.rotation=E.normalAngle(value));else f.rotation=E.normalAngle(value);changed();render();document.querySelectorAll('[data-rotate]').forEach(n=>n.value=String(n.type==='range'?Math.round(E.areaFrame(f).rotation):Math.round(E.areaFrame(f).rotation*10)/10));if(commit){const active=document.activeElement,focus=active?.matches('[data-rotate]')?'input[data-rotate][type="'+active.type+'"]':active?.matches('[data-reset-rotation]')?'[data-reset-rotation]':null;rotationEdit=null;details();if(focus)document.querySelector(focus)?.focus({preventScroll:true});}}
document.addEventListener('input',e=>{if(e.target.matches('[data-rotate]'))rotate(Number(e.target.value));});
document.addEventListener('change',e=>{if(e.target.matches('[data-rotate]'))rotate(Number(e.target.value),true);});
document.addEventListener('click',e=>{if(e.target.closest('[data-reset-rotation]'))rotate(0,true);});
@ -328,7 +414,7 @@
const drawing=svg.cloneNode(true),ids=new Map();
for(const node of [drawing,...drawing.querySelectorAll('[id]')])if(node.id){ids.set(node.id,'geographic-preview-'+node.id);node.id='geographic-preview-'+node.id;}
for(const node of [drawing,...drawing.querySelectorAll('*')]){
node.removeAttribute('tabindex');node.removeAttribute('data-feature-id');
node.removeAttribute('tabindex');node.removeAttribute('data-feature-id');node.removeAttribute('data-boundary-feature-id');
for(const attribute of [...node.attributes]){
let value=attribute.value;
for(const [id,replacement]of ids){value=value.replaceAll('url(#'+id+')','url(#'+replacement+')');if(value==='#'+id)value='#'+replacement;}