Move geographical hierarchies and anchored curves in one map proposal

This commit is contained in:
Nick Beckley 2026-11-14 16:17:11 +00:00
parent 84256767da
commit 04d8c43718
13 changed files with 276 additions and 25 deletions

View File

@ -0,0 +1,38 @@
# Hierarchy-aware geographical repositioning
## Cause and scope
The former operation projected only resolved Marker features. It neither followed canonical Location parents nor changed road frames/control points. Road rendering substitutes the current anchor coordinates for the first/last normalized point, so moving settlements alone pulled endpoints away from bends left in the original frame.
The geographical projection, provider, queue, cache and confirmation rules are unchanged. This enhancement extends the pure proposed-map calculation. No database migration or new parent/road relationship is introduced.
## Canonical hierarchy
`Geography/State?includeHierarchy=true` returns current resolutions plus the project's Location IDs, names and ParentLocationIDs through the existing repositories and access checks. Default callers still receive the original state array. Each preview loads this hierarchy rather than depending on an old Maps-page snapshot.
Resolved unlocked pieces with valid coordinates participate directly, including explicitly associated areas and unanchored paths. Endpoint-anchored paths use their existing anchors instead of acquiring independent geographical references. Non-authoritative descendants walk their existing Location parent chain to the nearest participating geographical ancestor and inherit that ancestor's canvas displacement. Unmapped intermediate parents are supported. Each piece is moved once, so mapped intermediate descendants do not compound the displacement. A child with its own authoritative coordinates is positioned independently.
Cycles, missing hierarchy entries and several map anchors for one ancestor with conflicting displacements are reported; those descendants stay unchanged. Locked pieces remain locked and stationary. A nearer locked geographical ancestor is not bypassed to inherit a more distant participant. Unassociated decoration is unchanged. No proximity or derived geometric-containment relationship is used as a substitute for story parents.
## Curves and areas
Path controls are normalized to the feature's X/Y, width/height and rotation; rendering replaces endpoint controls with anchor coordinates. The shared `connectionTransform` implements the similarity transform already used for free endpoint turn/extension. Geographical positioning uses it to map the entire rendered control polygon from the old to the new endpoint pair. Along-line proportions and perpendicular offsets scale/rotate together. Equal endpoint displacements produce a translation; one moving endpoint leaves the other fixed.
The transformed polygon is stored back in the existing frame/points representation. The label reference point follows the same transform, with its offsets adjusted for the normalised frame. Coincident or near-zero endpoint separation has no unique orientation; the fallback blends endpoint displacements along control-point order while retaining bends. Non-finite/out-of-range geometry or a locked path whose endpoints would move blocks the entire Apply operation. Existing paths are individual segments with at most a start/end anchor; adjoining segments transform through their shared anchors. There is no new per-control-point anchoring model.
Settlement boundaries remain offsets relative to their authoritative anchor, so moving the whole settlement translates its boundary without changing controls, smoothing or styling. Associated forests/lakes/buildings inherit only displacement. Their shapes and local canvas offsets are not geographically scaled. Manual map movement keeps its previous independent-object behaviour.
## Preview and persistence
One pure calculation returns the entire proposed feature array, direct and inherited movements, transformed paths, unchanged counts and attention items. The preview renders that array through the normal scene, including drawing-order overrides and overlays. Apply assigns that same array with one existing Undo checkpoint; it does not recalculate. Cancel leaves the live document unchanged. Redo and the normal revision-protected Save preserve the complete operation. Existing GeometryJson storage and project export/import/backup/restore carry transformed curves and boundaries.
## Verification
- Build and executable regression harness use the repository's normal gates.
- `node PlotLine.Tests/Browser/maps-geography-hierarchy-engine.cjs`: hierarchy depth/nearest authority, independent children, mapped/unmapped intermediates, areas/decorations, duplicates/cycles/missing links, equal/different/single-moving endpoints, degenerate/reversed/rotated connections and atomic safety refusal.
- `node PlotLine.Tests/Browser/maps-geography-hierarchy.cjs`: normal/PWA and light/dark layouts; isolated Rubery/Frankley/Redditch/Barmouth scenario, exact preview/Apply geometry, Cancel, one-step Undo/Redo, Save contract/reopen and unchanged manual behaviour.
- Existing geography, Maps engine, settlement and drawing-order regressions cover compatibility.
- `--map-geography-hierarchy-database /tmp/pd-dev-browser-<fixture>/identity.json`: verifies the effective Development database and disposable account, creates only its own unique project, tests complete transformed-map Save/reload and project backup/export/import/restore, then leaves that owned map at its original positions for browser acceptance.
- `node PlotLine.Tests/Browser/maps-geography-hierarchy-development.cjs /tmp/pd-dev-browser-<fixture>/identity.json`: authenticated Development verification using the real hierarchy API and real Map Save/reload. Coordinates are explicit fixture responses; the test makes no external geocoder requests and does not modify provider/cache/resolution data. Standard disposable identity cleanup removes the fixtures.
Tests never open the author's actual Birmingham map. Adding a distant place legitimately changes the projection scale; dependent objects preserve their requested local offsets rather than inventing physical distances or a new regional-map system.

View File

@ -10,8 +10,8 @@ assert(r.features[1].y<r.features[0].y,'north is up');assert(r.features[2].x>r.f
const north=r.features[0].y-r.features[1].y,east=r.features[2].x-r.features[0].x;
assert(Math.abs(east/north-Math.cos(52*Math.PI/180))<.002,'geographical distance ratio and a single aspect scale');
for(const p of r.features.slice(0,3)){assert(p.x>=80&&p.x<=1120);assert(p.y>=80&&p.y<=720);}
assert.deepEqual(r.features.slice(3),fs.slice(3),'locks, paths and unrelated drawings remain byte-equivalent');
assert.equal(r.skipped.length,2);
assert.deepEqual(r.features[3],fs[3],'locks remain byte-equivalent');assert.deepEqual(r.features[5],fs[5],'unassociated decorations remain byte-equivalent');assert.notDeepEqual(r.features[4],fs[4],'an explicitly located unanchored path can use its own geographical coordinates');
assert.equal(r.skipped.length,1);
for(const coords of [[[52,0]],[[52,0],[52,0]],[[52,0],[52,1]],[[0,179.9],[0,-179.9]],[[89,0],[89,1]]]){
const result=position(coords.map((_,i)=>marker(i+1)),coords.map((p,i)=>state(i+1,...p)),box);
assert(result.features.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y)),'single/two/coincident/antimeridian/polar points finite');

View File

@ -0,0 +1,23 @@
// Explicit authenticated Development acceptance; requires the disposable database fixture from --map-geography-hierarchy-database.
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');
const identityPath=process.argv[2];if(!identityPath?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated Development identity required.');
const identity=JSON.parse(fs.readFileSync(identityPath,'utf8')),fixture=JSON.parse(fs.readFileSync(path.join(path.dirname(identityPath),'hierarchy-fixture.json'),'utf8'));
if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('pwa-browser-'))throw Error('Wrong account scope.');
const base='https://dev.plotdirector.com';
(async()=>{const browser=await chromium.launch();try{
const context=await browser.newContext({viewport:{width:1700,height:1150}}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
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()]);
const response=await context.request.get(base+'/Geography/State?projectId='+fixture.projectId+'&includeHierarchy=true');assert.equal(response.status(),200);const live=await response.json();assert(Array.isArray(live.states)&&Array.isArray(live.locations),'deployed API supplies fresh hierarchy');
const maggie=live.locations.find(l=>l.locationName==="Maggie's flat"),middle=live.locations.find(l=>l.locationName==='The Doweries'),rubery=live.locations.find(l=>l.locationName==='Rubery');assert.equal(maggie.parentLocationID,middle.locationID);assert.equal(middle.parentLocationID,rubery.locationID);
// Use bounded, explicit fixture coordinates without calling or modifying the provider/cache/resolution database.
await page.route('**/Geography/State?*',r=>r.fulfill({json:{states:fixture.states,locations:live.locations}}));
await page.goto(base+'/Maps?projectId='+fixture.projectId+'&id='+fixture.mapId);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
const read=()=>page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),before=await read();
const expected=await page.evaluate(({states,locations})=>window.PlotDirectorGeography.position(window.PlotDirectorMapWorkspace.document.features,states,window.PlotDirectorMapWorkspace.view,locations),{states:fixture.states,locations:live.locations});assert(expected.canApply);assert.equal(expected.counts.paths,2);assert(expected.inherited.some(f=>f.name==="Maggie's flat"&&f.ancestor==='Rubery'&&f.via[0]==='The Doweries'));
const command=id=>page.evaluate(id=>document.getElementById(id).click(),id);
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});assert.equal(await read(),before);await command('mapsGeographicCancel');assert.equal(await read(),before);
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});const preview=await page.locator('#mapsScene').innerHTML();await command('mapsGeographicApply');assert.equal(await page.locator('#mapsScene').innerHTML(),preview);assert.deepEqual(JSON.parse(await read()),expected.features);
const applied=await read();await command('mapsUndo');assert.equal(await read(),before);await command('mapsRedo');assert.equal(await read(),applied);
await command('mapsSave');await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert.equal(await read(),applied,'actual server Save and reload retain all positions, curves, boundaries and drawing order');
assert.deepEqual(errors,[]);console.log('PASS authenticated Development hierarchy geography: real hierarchy endpoint, Barmouth proposal, descendants through unmapped parent, complete road/boundary preview, Cancel, one-step Undo/Redo, server Save/reload and preserved identities. Isolated project '+fixture.projectId);await context.close();
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -0,0 +1,30 @@
const assert=require('node:assert/strict'),E=require('../../PlotLine/wwwroot/js/maps-engine.js'),G=require('../../PlotLine/wwwroot/js/maps-geography-engine.js');
const box={x:-600,y:-400,w:1200,h:800},make=(type,id,locationID,x,y)=>Object.assign(E.makeFeature(type,x,y,id),{locationID,name:id,isProvisional:false}),state=(id,lat,lon)=>({locationID:id,status:'Resolved',matchJson:JSON.stringify({Latitude:lat,Longitude:lon})});
const places=[{locationID:1,locationName:'Rubery'},{locationID:2,locationName:'The Doweries',parentLocationID:1},{locationID:3,locationName:"Maggie's flat",parentLocationID:2},{locationID:4,locationName:'Frankley'},{locationID:5,locationName:'Barmouth'},{locationID:6,locationName:'Forest',parentLocationID:1},{locationID:7,locationName:'Lake',parentLocationID:1},{locationID:8,locationName:'Own coordinates',parentLocationID:1}];
const features=[make('Town','Rubery',1,100,80),make('Town','Frankley',4,600,200),make('Town','Barmouth',5,-300,-200),make('House','Maggie',3,120,90),make('Forest','forest',6,60,40),make('Lake','lake',7,105,95),make('House','own',8,99,99),make('House','decoration',null,500,500)];
const road=make('Road','road',null,350,130);road.startFeatureID='Rubery';road.endFeatureID='Frankley';road.geometryJson=JSON.stringify({points:[[-.5,0],[-.1,.4],[.2,-.3],[.5,0]],drawingOrder:345678});features.push(road);
const states=[state(1,52.39,-2.016),state(4,52.41,-2.022),state(5,52.72,-4.05),state(8,52.4,-2.0)],before=JSON.stringify(features),r=G.position(features,states,box,places),find=(result,id)=>result.features.find(f=>f.featureID===id);
assert(r.canApply);assert.equal(places.find(l=>l.locationID===3).parentLocationID,2);assert.equal(places.find(l=>l.locationID===2).parentLocationID,1);assert.equal(JSON.stringify(features),before);const delta=[find(r,'Rubery').x-features[0].x,find(r,'Rubery').y-features[0].y];
for(const id of ['Maggie','forest','lake']){const old=features.find(f=>f.featureID===id),next=find(r,id);assert(Math.abs(next.x-old.x-delta[0])<1e-8);assert(Math.abs(next.y-old.y-delta[1])<1e-8);assert.equal(next.geometryJson,old.geometryJson);}
assert.deepEqual(r.inherited.find(p=>p.name==='Maggie').via,['The Doweries']);assert.equal(find(r,'Rubery').geometryJson,features[0].geometryJson,'boundary/style/order remain relative to translated anchor');assert.deepEqual(find(r,'decoration'),features[7]);assert.notEqual(find(r,'own').x-features[6].x,delta[0]);assert.equal(r.counts.paths,1);
const oldPoints=E.pathPoints(road,features),nextPoints=E.pathPoints(find(r,'road'),r.features),transform=E.connectionTransform(oldPoints[0],oldPoints.at(-1),nextPoints[0],nextPoints.at(-1));for(let i=0;i<oldPoints.length;i++){const p=transform.point(oldPoints[i]);assert(Math.hypot(p[0]-nextPoints[i][0],p[1]-nextPoints[i][1])<1e-7);}
assert.equal(E.geometry(find(r,'road')).drawingOrder,345678);
const middle=make('House','middle',2,115,85),withMiddle=G.position([...features,middle],states,box,places);assert(Math.abs(find(withMiddle,'Maggie').x-features[3].x-delta[0])<1e-7);assert(Math.abs(find(withMiddle,'middle').x-middle.x-delta[0])<1e-7);
const loosePath=make('Trail','loose',3,120,100),withLoose=G.position([...features,loosePath],states,box,places);assert(Math.abs(find(withLoose,'loose').x-loosePath.x-delta[0])<1e-7);assert.equal(withLoose.counts.paths,2);
// Several geographically positioned ancestors: the closest takes precedence, never twice.
const child=make('House','grandchild',9,110,120),nested=[...places,{locationID:9,locationName:'Child',parentLocationID:8}];const rr=G.position([...features,child],states,box,nested);assert(Math.abs(find(rr,'grandchild').x-child.x-(find(rr,'own').x-features[6].x))<1e-7);
for(const bad of [[{locationID:3,parentLocationID:999}],[{locationID:3,parentLocationID:2},{locationID:2,parentLocationID:3}]]){const result=G.position(features,states,box,bad);assert.deepEqual(find(result,'Maggie'),features[3]);assert(result.attention.some(a=>a.name==='Maggie'));}
const deep=Array.from({length:180},(_,i)=>({locationID:20+i,locationName:'Level '+i,parentLocationID:i?19+i:1})),deepPiece=make('House','deep',199,10,15),deepResult=G.position([...features,deepPiece],states,box,[...places,...deep]);assert(Math.abs(find(deepResult,'deep').x-deepPiece.x-delta[0])<1e-7,'hierarchy inheritance has no shallow depth limit');
const locked=E.copy(features);locked.find(f=>f.featureID==='road').isLocked=true;const blocked=G.position(locked,states,box,places);assert.equal(blocked.canApply,false);assert.deepEqual(blocked.features,locked,'unsafe locked connections prevent partial application');
const duplicate=E.copy(features[0]);duplicate.featureID='second Rubery';duplicate.x+=20;const ambiguous=G.position([...features,duplicate],states,box,places);assert(ambiguous.attention.some(a=>a.name==='Maggie'&&a.reason.includes('several')));assert.deepEqual(find(ambiguous,'Maggie'),features[3]);
// Exact path cases, independent of geographical projection; frame and local coordinates are implementation details.
function pathCase(a,b,c,d){const start=make('Town','a',null,...a),end=make('Town','b',null,...b),p=make('Road','p',null,0,0);p.startFeatureID='a';p.endFeatureID='b';p.geometryJson=JSON.stringify({points:[[-.5,0],[-.1,.3],[.2,-.2],[.5,0]]});const old=[start,end,p],next=[{...start,x:c[0],y:c[1]},{...end,x:d[0],y:d[1]},p],q=E.transformAnchoredPath(p,old,next),points=E.pathPoints(q,next);assert.deepEqual(points[0],c);assert.deepEqual(points.at(-1),d);assert(points.flat().every(Number.isFinite));return {old:E.pathPoints(p,old),points,label:[q.x+q.labelX,q.y+q.labelY]};}
const translated=pathCase([0,0],[100,0],[30,-10],[130,-10]);assert(Math.hypot(translated.label[0]-30,translated.label[1]+10)<1e-7,'the road label translates with the curve despite frame normalization');translated.old.forEach((p,i)=>assert(Math.hypot(translated.points[i][0]-p[0]-30,translated.points[i][1]-p[1]+10)<1e-7));
for(const args of [[[0,0],[100,0],[0,0],[200,100]],[[0,0],[100,0],[100,0],[0,0]],[[0,0],[100,0],[0,0],[0,100]],[[0,0],[0,0],[0,0],[100,0]],[[0,0],[.00001,0],[30,40],[30,40]],[[0,0],[100,0],[10,10],[10,10]]])pathCase(...args);
assert.throws(()=>pathCase([0,0],[.02,0],[0,0],[1000,0]),/safe|large/,'extreme separation changes cannot explode curve offsets');
const short=make('Road','short',null,0,0);short.startFeatureID='Rubery';short.endFeatureID='Frankley';short.geometryJson=JSON.stringify({points:[[-.5,0],[.5,0]]});assert.equal(E.geometry(E.transformAnchoredPath(short,features,r.features)).points.length,2);
// Single anchored endpoint, stationary free end; no proximity-based attachment.
const single=E.copy(road);single.endFeatureID=null;const oldEnd=E.pathPoints(single,features).at(-1),singleNext=E.transformAnchoredPath(single,features,r.features);assert.deepEqual(E.pathPoints(singleNext,r.features).at(-1),oldEnd);
const invalid=E.copy(features);invalid.at(-1).endFeatureID='missing';const invalidResult=G.position(invalid,states,box,places);assert.equal(invalidResult.canApply,false);assert.deepEqual(invalidResult.features,invalid);
assert.throws(()=>E.transformAnchoredPath(road,features,[{...features[0],x:1e8},...features.slice(1)]),/safe|large/);
console.log('PASS hierarchy inheritance, unmapped intermediate, nearest authority, independent child, malformed/cyclic/duplicate hierarchy, boundary/area/decor preservation, complete atomic proposal, anchored similarities, single/multiple segments, degenerate/reversed/rotated paths and bounds.');

View File

@ -0,0 +1,11 @@
// Isolated persistence/deployment fixture; all Location IDs are supplied by a disposable account's project.
const fs=require('node:fs'),{randomUUID}=require('node:crypto'),E=require('../../PlotLine/wwwroot/js/maps-engine.js'),G=require('../../PlotLine/wwwroot/js/maps-geography-engine.js');
const input=JSON.parse(fs.readFileSync(process.argv[2],'utf8')),places=new Map(input.locations.map(l=>[l.locationName,l.locationID]));
const make=(type,name,x,y)=>Object.assign(E.makeFeature(type,x,y,randomUUID()),{name,locationID:places.get(name)||null,isProvisional:false});
const rubery=make('Town','Rubery',0,0),frankley=make('Town','Frankley',300,-40),redditch=make('Town','Redditch',100,300),barmouth=make('Town','Barmouth',-350,-200),house=make('House',"Maggie's flat",25,20),forest=make('Forest','Forest',-50,-40),lake=make('Lake','Reservoir',320,-30),own=make('House','Own place',80,90),child=make('House','Own child',95,100),decor=make('Landmark','Decoration',600,450);
const road=make('Road','A38',150,0);road.startFeatureID=rubery.featureID;road.endFeatureID=frankley.featureID;E.updateArea(road,g=>g.points=[[-.5,0],[-.1,.35],[.2,-.3],[.5,0]]);
const trail=make('Trail','Trail',200,100);trail.startFeatureID=frankley.featureID;trail.endFeatureID=redditch.featureID;
const before=[rubery,frankley,redditch,barmouth,house,forest,lake,own,child,decor,road,trail];E.reorder(before,[lake.featureID],'front');
const states=[['Rubery',52.391,-2.016],['Frankley',52.412,-2.023],['Redditch',52.306,-1.942],['Barmouth',52.72,-4.05],['Own place',52.4,-2.01]].map(([name,Latitude,Longitude])=>({locationID:places.get(name),status:'Resolved',matchJson:JSON.stringify({Latitude,Longitude,Attribution:'Isolated acceptance coordinates; no live-provider requests'})}));
const result=G.position(before,states,{x:-600,y:-400,w:1200,h:800},input.locations);if(!result.canApply)throw Error(result.message);
fs.writeFileSync(process.argv[3],JSON.stringify({...input,before,after:result.features,states,counts:result.counts}),{mode:0o600});

View File

@ -0,0 +1,28 @@
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']){
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=[];page.on('pageerror',e=>errors.push(e.message));let saved;
const locations=[[11,'Rubery',null],[12,'Frankley',null],[13,'Redditch',null],[14,'Barmouth',null],[15,'The Doweries',11],[16,"Maggie's flat",15],[17,'Reservoir',12],[18,'Forest',11],[19,'Independent place',11],[20,'Independent child',19]].map(([locationID,locationName,parentLocationID])=>({locationID,locationName,parentLocationID}));
const states=[[11,52.391,-2.016],[12,52.412,-2.023],[13,52.306,-1.942],[14,52.72,-4.05],[19,52.4,-2.01]].map(([locationID,Latitude,Longitude])=>({locationID,status:'Resolved',matchJson:JSON.stringify({Latitude,Longitude,Attribution:'Isolated synthetic coordinates; no external provider calls'})}));
await page.route('**/Geography/State?*',r=>{assert.equal(new URL(r.request().url()).searchParams.get('includeHierarchy'),'true');return r.fulfill({json:{states,locations}});});
await page.route('**/Maps/Save',r=>{saved=r.request().postDataJSON();saved.map.revision++;return r.fulfill({json:saved});});
await page.goto(base+'/fixture?page=maps&theme='+theme);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
await page.evaluate(()=>{const W=window.PlotDirectorMapWorkspace,E=window.PlotDirectorMaps;W.edit(()=>{
const f=(type,id,locationID,x,y)=>Object.assign(E.makeFeature(type,x,y,id),{name:id,locationID,isProvisional:false});
const rubery=f('Town','Rubery',11,0,0),frankley=f('Town','Frankley',12,300,-40),redditch=f('Town','Redditch',13,100,300),barmouth=f('Town','Barmouth',14,-350,-200),house=f('House',"Maggie's flat",16,25,20),forest=f('Forest','Forest',18,-50,-40),lake=f('Lake','Reservoir',17,320,-30),own=f('House','Independent place',19,80,90),child=f('House','Independent child',20,95,100),decor=f('Landmark','Decoration',null,600,450);
const road=f('Road','A38',null,150,0);road.startFeatureID='Rubery';road.endFeatureID='Frankley';const g=E.geometry(road);g.points=[[-.5,0],[-.1,.35],[.2,-.3],[.5,0]];g.drawingOrder=310000;road.geometryJson=JSON.stringify(g);
const segment=f('Trail','Trail',null,200,100);segment.startFeatureID='Frankley';segment.endFeatureID='Redditch';W.document.features=[rubery,frankley,redditch,barmouth,house,forest,lake,own,child,decor,road,segment];});W.fit();});
const read=()=>page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features)),before=await read();
const expected=await page.evaluate(({states,locations})=>window.PlotDirectorGeography.position(window.PlotDirectorMapWorkspace.document.features,states,window.PlotDirectorMapWorkspace.view,locations),{states,locations});assert(expected.canApply);
const command=id=>page.evaluate(id=>document.getElementById(id).click(),id);
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});assert.equal(await read(),before);await page.locator('#mapsGeographicList').evaluate(n=>n.open=true);assert.match(await page.locator('#mapsGeographicSummary').innerText(),/Maggie's flat → Follows Rubery via The Doweries/);assert.match(await page.locator('#mapsGeographicSummary').innerText(),/2 roads\/paths/);assert(await page.locator('#mapsGeographicPreview svg').isVisible());
const scene=await page.locator('#mapsScene').innerHTML();await command('mapsGeographicCancel');assert.equal(await read(),before);
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});await command('mapsGeographicApply');assert(!await page.locator('#mapsGeographicDialog').isVisible());assert.deepEqual(JSON.parse(await read()),expected.features,'Apply takes the exact complete proposal');assert.equal(await page.locator('#mapsScene').innerHTML(),scene,'preview and applied renderer have identical roads/boundaries');
const applied=await read();await command('mapsUndo');assert.equal(await read(),before);await command('mapsRedo');assert.equal(await read(),applied);
await command('mapsSave');await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');assert.deepEqual(saved.features,expected.features);
// Reopen a document supplied by the Save contract, before workspace initialization.
await page.route('**/fixture?**',async route=>{const response=await route.fetch();let html=await response.text();html=html.replace(/(<script id="mapsBootstrap"[^>]*>)(.*?)(<\/script>)/s,(_,a,b,c)=>{const boot=JSON.parse(b);boot.document=saved;return a+JSON.stringify(boot)+c;});await route.fulfill({response,body:html});});
await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert.equal(await read(),applied,'Save/reopen preserves every transformed object');
// Ordinary manual movement retains its established independent-object behaviour.
await page.evaluate(()=>window.PlotDirectorMapWorkspace.select('Rubery'));await page.locator('[data-feature-id=Rubery]').focus();await page.keyboard.press('ArrowRight');const manual=JSON.parse(await read());assert.equal(manual[0].x,expected.features[0].x+5);assert.deepEqual(manual[4],expected.features[4],'manual movement does not start hierarchy inheritance');assert.deepEqual(await page.evaluate(()=>{const W=window.PlotDirectorMapWorkspace;return window.PlotDirectorMaps.pathPoints(W.document.features.find(f=>f.name==='A38'),W.document.features)[0];}),[manual[0].x,manual[0].y],'ordinary manual movement still updates the existing road anchor');
assert.deepEqual(errors,[]);console.log('PASS hierarchy geography '+(pwa?'PWA':'web')+' '+theme+': fresh hierarchy, Barmouth/Rubery/dependents, exact road/boundary preview, Cancel, Apply, atomic Undo/Redo, Save/reopen, independent manual editing.');await context.close();
}}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -0,0 +1,54 @@
// Explicit Development-only test. Creates/restores only a new project owned by a disposable 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;
using PlotLine.Services;
internal static class MapGeographicHierarchyDatabaseTests
{
static void Check(bool ok,string message){if(!ok)throw new InvalidOperationException(message);}
static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
public static async Task Run(string path)
{
Check(Path.GetFullPath(path).StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal),"Dedicated identity required.");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(path));var account=identity.RootElement;
Check(account.GetProperty("Database").GetString()=="PlotDirector_Development"&&account.GetProperty("Email").GetString()!.StartsWith("pwa-browser-"),"Wrong test account scope.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=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();Check(process.ExitCode==0,"Development configuration unavailable.");
var connectionString=environment.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
Check(new SqlConnectionStringBuilder(connectionString).InitialCatalog=="PlotDirector_Development","Wrong configured database.");
using var db=new SqlConnection(connectionString);await db.OpenAsync();Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Development","Wrong effective 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 user.");
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();var factory=new SqlConnectionFactory(config);
var title="Hierarchy geography 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 ids=new Dictionary<string,int>();
foreach(var (name,parent) in new (string,string?)[]{("Rubery",null),("Frankley",null),("Redditch",null),("Barmouth",null),("The Doweries","Rubery"),("Maggie's flat","The Doweries"),("Forest","Rubery"),("Reservoir","Frankley"),("Own place","Rubery"),("Own child","Own place")})
ids[name]=await locations.SaveAsync(new(){ProjectID=project,LocationName=name,ParentLocationID=parent is null?null:ids[parent]});
var maps=new MapRepository(factory);var map=await maps.CreateAsync(new(){ProjectID=project,Name="Isolated hierarchy geography",Kind="Region"},user);
var input=Path.Combine(Path.GetDirectoryName(path)!,"hierarchy-input.json");var output=Path.Combine(Path.GetDirectoryName(path)!,"hierarchy-fixture.json");
await File.WriteAllTextAsync(input,JsonSerializer.Serialize(new{projectId=project,mapId=map,locations=await locations.ListByProjectAsync(project)},Json));
var node=new ProcessStartInfo("node");node.ArgumentList.Add("PlotLine.Tests/Browser/maps-geography-hierarchy-fixture.cjs");node.ArgumentList.Add(input);node.ArgumentList.Add(output);using var generator=Process.Start(node)!;await generator.WaitForExitAsync();Check(generator.ExitCode==0,"Fixture projection failed.");
using var fixture=JsonDocument.Parse(await File.ReadAllTextAsync(output));var before=fixture.RootElement.GetProperty("before").Deserialize<List<MapFeature>>(Json)!;var after=fixture.RootElement.GetProperty("after").Deserialize<List<MapFeature>>(Json)!;
var document=(await maps.GetAsync(project,map,user))!;document.Features=before;Check(MapValidation.Validate(document) is null,"Original fixture validates.");await maps.SaveAsync(document,user);document=(await maps.GetAsync(project,map,user))!;
document.Features=after;Check(MapValidation.Validate(document) is null,"Complete transformed fixture validates.");await maps.SaveAsync(document,user);document=(await maps.GetAsync(project,map,user))!;Verify(document,after);
var backup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,user))!;var imported=JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(backup))!;
Check(imported.Data.MapFeatures.All(f=>after.Any(a=>a.FeatureID==f.FeatureID&&a.GeometryJson==f.GeometryJson)),"Export/import retains complete road and boundary geometry.");
document.Features=before;await maps.SaveAsync(document,user);
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@project AND ProjectName=@title",new{project,title})==1,"Verify unique owned restore target.");
await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=BookRecoveryRepository.Encode(imported,null)},commandType:CommandType.StoredProcedure,commandTimeout:180);
document=(await maps.GetAsync(project,map,user))!;Verify(document,after);
Check((await locations.GetAsync(ids["Maggie's flat"]))!.ParentLocationID==ids["The Doweries"]&&(await locations.GetAsync(ids["The Doweries"]))!.ParentLocationID==ids["Rubery"],"Canonical hierarchy remains intact.");
// Leave only this owned map at its original positions for authenticated acceptance; normal identity cleanup removes it.
document.Features=before;await maps.SaveAsync(document,user);
Console.WriteLine("PASS Development complete transformed map Save/reload, backup/export/import/full-project restore, road/settlement JSON, canonical hierarchy and identities. Owned fixture ready for browser acceptance.");
}
static void Verify(MapDocument document,List<MapFeature> expected)
{
Check(document.Features.Count==expected.Count,"All pieces preserved.");
foreach(var f in expected){var actual=document.Features.Single(a=>a.FeatureID==f.FeatureID);Check((actual.X,actual.Y,actual.Width,actual.Height,actual.Rotation,actual.LabelX,actual.LabelY,actual.GeometryJson,actual.LocationID,actual.StartFeatureID,actual.EndFeatureID)==(f.X,f.Y,f.Width,f.Height,f.Rotation,f.LabelX,f.LabelY,f.GeometryJson,f.LocationID,f.StartFeatureID,f.EndFeatureID),"Exact transformed geometry, order, identity and connections persist.");}
}
}

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--map-geography-hierarchy-database")){await MapGeographicHierarchyDatabaseTests.Run(args.Last());return;}
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;}

View File

@ -9,19 +9,20 @@ namespace PlotLine.Controllers;
public sealed class GeographyController(GeographyRepository repository,IProjectAccessService access,ICurrentUserService currentUser,GeographicRules rules,ILocationRepository locations) : Controller
{
[HttpGet]
public async Task<IActionResult> State(int projectId,int? locationId)
public async Task<IActionResult> State(int projectId,int? locationId,bool includeHierarchy=false)
{
if(!await access.CanAccessProjectAsync(projectId)) return NotFound();
Response.Headers.CacheControl="private, no-store";
var states=await repository.GetAsync(projectId,currentUser.UserId!.Value,locationId);
var projectLocations=includeHierarchy||states.Any(s=>s.Status=="Pending")
? (await locations.ListByProjectAsync(projectId)).ToDictionary(l=>l.LocationID) : null;
if(states.Any(s=>s.Status=="Pending"))
{
var projectLocations=(await locations.ListByProjectAsync(projectId)).ToDictionary(l=>l.LocationID);
foreach(var state in states.Where(s=>s.Status=="Pending"))
{
var chain=new List<PlotLine.Models.LocationItem>();
var visited=new HashSet<int>();var id=state.LocationID;
while(projectLocations.TryGetValue(id,out var place)&&visited.Add(id)&&chain.Count<=100)
while(projectLocations!.TryGetValue(id,out var place)&&visited.Add(id)&&chain.Count<=100)
{
chain.Add(place);
if(place.ParentLocationID is not int parent)break;
@ -34,6 +35,7 @@ public sealed class GeographyController(GeographyRepository repository,IProjectA
}
}
}
if(includeHierarchy)return Json(new {states,locations=projectLocations!.Values.Select(l=>new {l.LocationID,l.LocationName,l.ParentLocationID})});
return Json(states);
}
[HttpPost,ValidateAntiForgeryToken]

View File

@ -74,8 +74,8 @@
<h2 id="mapsGeographicTitle">Position geographically</h2>
<p id="mapsGeographicMessage" role="status"></p>
<div id="mapsGeographicPreview" aria-label="Proposed geographical arrangement"></div>
<p>Preview only · North ↑ · One geographical scale in both directions. Coincident places overlap.</p>
<details id="mapsGeographicList"><summary>Locations and lookup status</summary><div id="mapsGeographicSummary"></div></details>
<p>Preview only · North ↑ · One geographical scale in both directions. Coincident places overlap. Descendants retain their offsets; anchored curves follow their endpoints.</p>
<details id="mapsGeographicList"><summary>Movements, hierarchy and lookup status</summary><div id="mapsGeographicSummary"></div></details>
<p id="mapsGeographicRequestStatus" role="status"></p>
<div class="maps-geographic-actions"><button type="button" id="mapsGeographicRequest">Request missing lookups</button><button type="button" id="mapsGeographicRefresh">Refresh status</button><button type="button" id="mapsGeographicCancel">Cancel</button><button type="button" id="mapsGeographicApply">Apply positions</button></div>
<p>Apply closes this preview and adds one Undo step. Use Save to persist the map; you can drag markers afterwards.</p>

View File

@ -233,15 +233,35 @@
result.forEach(f=>{if(movable(f)){f.isPlaced=true;if(!anchored.has(f.featureID)){f.x=Math.round(f.x*100)/100;f.y=Math.round(f.y*100)/100;}}});
return {features:result,warnings};
}
// Shared endpoint similarity transform: proportional along-line and perpendicular offsets.
function connectionTransform(a,b,c,d){
const oldLength=Math.hypot(b[0]-a[0],b[1]-a[1]),nextLength=Math.hypot(d[0]-c[0],d[1]-c[1]);
if(oldLength<.01||nextLength<.01)return null;
const angle=Math.atan2(d[1]-c[1],d[0]-c[0])-Math.atan2(b[1]-a[1],b[0]-a[0]),ratio=nextLength/oldLength;
return {angle,ratio,point:p=>{const x=p[0]-a[0],y=p[1]-a[1];return [c[0]+(x*Math.cos(angle)-y*Math.sin(angle))*ratio,c[1]+(x*Math.sin(angle)+y*Math.cos(angle))*ratio];}};
}
function transformAnchoredPath(feature,before,after){
const points=pathPoints(feature,before),ends=pathPoints(feature,after),a=points[0],b=points.at(-1),c=ends[0],d=ends.at(-1);
const transform=connectionTransform(a,b,c,d);
// Degenerate connections have no unique direction; blend endpoint displacements, retaining bends.
const moved=points.map((p,i)=>{const t=i/(points.length-1);return transform?transform.point(p):[p[0]+(c[0]-a[0])*(1-t)+(d[0]-b[0])*t,p[1]+(c[1]-a[1])*(1-t)+(d[1]-b[1])*t];});
if(moved.some(p=>p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))throw Error('The proposed path exceeds safe canvas limits.');
const xs=moved.map(p=>p[0]),ys=moved.map(p=>p[1]),left=Math.min(...xs),right=Math.max(...xs),top=Math.min(...ys),bottom=Math.max(...ys);
const f=copy(feature),g=geometry(f);f.x=(left+right)/2;f.y=(top+bottom)/2;f.width=Math.max(1,right-left);f.height=Math.max(1,bottom-top);f.rotation=0;
if(f.width>100000||f.height>100000)throw Error('The proposed path is too large.');
const oldLabel=[feature.x+(feature.labelX||0),feature.y+(feature.labelY||0)],label=transform?transform.point(oldLabel):[oldLabel[0]+((c[0]-a[0])+(d[0]-b[0]))/2,oldLabel[1]+((c[1]-a[1])+(d[1]-b[1]))/2];
f.labelX=label[0]-f.x;f.labelY=label[1]-f.y;
if(![f.labelX,f.labelY].every(n=>Number.isFinite(n)&&Math.abs(n)<=100000))throw Error('The proposed path label exceeds safe canvas limits.');
g.points=moved.map(p=>[(p[0]-f.x)/f.width,(p[1]-f.y)/f.height]);f.geometryJson=JSON.stringify(g);return f;
}
function transformEndpoint(feature,index,point,features){
const f=copy(feature),points=pathPoints(f,features),last=points.length-1;
if(f.geometryClass!=='Path'||![0,last].includes(index)||(index===0?f.startFeatureID:f.endFeatureID))return f;
const fixed=points[index===0?last:0],moving=points[index],oldLength=Math.hypot(moving[0]-fixed[0],moving[1]-fixed[1]);
const nextLength=Math.hypot(point[0]-fixed[0],point[1]-fixed[1]);if(oldLength<.01||nextLength<10)return f;
const angle=Math.atan2(point[1]-fixed[1],point[0]-fixed[0])-Math.atan2(moving[1]-fixed[1],moving[0]-fixed[0]),ratio=nextLength/oldLength;
const x=f.x-fixed[0],y=f.y-fixed[1];f.x=fixed[0]+(x*Math.cos(angle)-y*Math.sin(angle))*ratio;f.y=fixed[1]+(x*Math.sin(angle)+y*Math.cos(angle))*ratio;
f.width*=ratio;f.height*=ratio;f.rotation=normalAngle(f.rotation+angle*180/Math.PI);return f;
const transform=connectionTransform(fixed,moving,fixed,point),center=transform.point([f.x,f.y]);f.x=center[0];f.y=center[1];
f.width*=transform.ratio;f.height*=transform.ratio;f.rotation=normalAngle(f.rotation+transform.angle*180/Math.PI);return f;
}
const normalAngle=value=>((value+180)%360+360)%360-180;
return {drawingPriority,drawingOrder,reorder,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};
return {connectionTransform,transformAnchoredPath,drawingPriority,drawingOrder,reorder,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

@ -2,18 +2,21 @@
Refuse large extents: no flat projection preserves all worldwide distances/directions. */
(function(root){
'use strict';
function position(features,states,bounds){
const E=typeof module!=='undefined'&&module.exports?require('./maps-engine.js'):root.PlotDirectorMaps;
function position(features,states,bounds,locations=[]){
const rad=Math.PI/180,R=6371008.8,wrap=a=>Math.atan2(Math.sin(a),Math.cos(a));
if(![bounds.x,bounds.y,bounds.w,bounds.h].every(Number.isFinite)||bounds.w<=0||bounds.h<=0)throw Error('Map area is unavailable.');
const skipped=[],points=[],output=JSON.parse(JSON.stringify(features));
const skipped=[],points=[],output=JSON.parse(JSON.stringify(features)),inherited=[],paths=[],attention=[],stateById=new Map(states.map(s=>[s.locationID,s])),original=new Map(features.map(f=>[f.featureID,f]));
const anchored=f=>f.geometryClass==='Path'&&!!(f.startFeatureID||f.endFeatureID);
const validMatch=s=>{let m;try{m=JSON.parse(s?.matchJson||'null');}catch{}return s?.status==='Resolved'&&m&&Number.isFinite(m.Latitude)&&Number.isFinite(m.Longitude)&&Math.abs(m.Latitude)<=90&&Math.abs(m.Longitude)<=180?m:null;};
for(const f of output){
if(!f.locationID)continue;
const state=states.find(s=>s.locationID===f.locationID);
if(!f.locationID||anchored(f))continue;
const state=stateById.get(f.locationID);
let match=null;try{match=JSON.parse(state?.matchJson||'null');}catch{}
const pendingLabel=state?.status==='Pending'?({'Awaiting hierarchy request':'Not requested','Queued':state.attempts?'Retry scheduled':'Queued','Processing':'Looking up','Waiting configuration':'Lookup disabled'}[state.jobState]||'Pending'):state?.status;
const reason=f.isLocked?'Locked':f.geometryClass!=='Marker'?'Only location markers can be positioned':state?.status!=='Resolved'?(pendingLabel||'Pending'):!match?'Unresolved':null;
if(reason){skipped.push({name:f.name,reason,locationID:f.locationID,message:state?.message,canRequest:reason==='Not requested'});continue;}
if(!Number.isFinite(match.Latitude)||!Number.isFinite(match.Longitude)||Math.abs(match.Latitude)>90||Math.abs(match.Longitude)>180){skipped.push({name:f.name,reason:'Invalid geographical coordinates'});continue;}
const reason=f.isLocked?'Locked':state?.status!=='Resolved'?(pendingLabel||'Pending'):!match?'Unresolved':null;
if(reason){skipped.push({featureID:f.featureID,name:f.name,reason,locationID:f.locationID,message:state?.message,canRequest:reason==='Not requested'});continue;}
if(!Number.isFinite(match.Latitude)||!Number.isFinite(match.Longitude)||Math.abs(match.Latitude)>90||Math.abs(match.Longitude)>180){skipped.push({featureID:f.featureID,name:f.name,locationID:f.locationID,reason:'Invalid geographical coordinates'});continue;}
points.push({feature:f,lat:match.Latitude*rad,lon:match.Longitude*rad,attribution:match.Attribution});
}
const positioned=points.map(p=>({name:p.feature.name,locationID:p.feature.locationID,featureID:p.feature.featureID,attribution:p.attribution}));
@ -32,8 +35,44 @@
const pad=Math.min(80,bounds.w*.12,bounds.h*.12),w=bounds.w-2*pad,h=bounds.h-2*pad;
const scale=Math.min(right-left>1e-6?w/(right-left):Infinity,bottom-top>1e-6?h/(bottom-top):Infinity);
for(const p of points){p.feature.x=bounds.x+bounds.w/2+(p.x-(left+right)/2)*(Number.isFinite(scale)?scale:0);p.feature.y=bounds.y+bounds.h/2+(p.y-(top+bottom)/2)*(Number.isFinite(scale)?scale:0);p.feature.isPlaced=true;}
const changes=points.filter(p=>{const before=features.find(f=>f.featureID===p.feature.featureID);return Math.abs(before.x-p.feature.x)>1e-6||Math.abs(before.y-p.feature.y)>1e-6||!before.isPlaced;}).length;
return {features:output,positioned,skipped,canApply:changes>0,message:changes?`${changes} location markers will move. Other map objects retain their positions.`:'These places are already in the proposed positions. No changes are needed.'};
const byLocation=new Map(),locationById=new Map(locations.map(l=>[l.locationID,l])),own=new Set(points.map(p=>p.feature.featureID));
for(const p of points){const before=original.get(p.feature.featureID),delta=[p.feature.x-before.x,p.feature.y-before.y];if(!byLocation.has(p.feature.locationID))byLocation.set(p.feature.locationID,[]);byLocation.get(p.feature.locationID).push({feature:p.feature,delta});}
for(const f of output){
if(!f.locationID||own.has(f.featureID)||anchored(f))continue;
if(f.isLocked){attention.push({featureID:f.featureID,name:f.name,reason:'Locked; stays in place',locationID:f.locationID});continue;}
// A resolved location is never silently replaced by an ancestor's displacement.
if(validMatch(stateById.get(f.locationID)))continue;
const chain=[],visited=new Set();let id=f.locationID,problem=null;
while(id!=null){if(visited.has(id)){problem='Cyclic Location hierarchy';break;}visited.add(id);const l=locationById.get(id);if(!l){problem='Missing Location hierarchy entry';break;}chain.push(l);id=l.parentLocationID;}
if(problem){attention.push({featureID:f.featureID,name:f.name,reason:problem,locationID:f.locationID});continue;}
const index=chain.findIndex((l,i)=>i>0&&byLocation.has(l.locationID));if(index<0)continue;
if(chain.slice(1,index).some(l=>features.some(p=>p.locationID===l.locationID&&p.isLocked)&&validMatch(stateById.get(l.locationID)))){attention.push({featureID:f.featureID,name:f.name,reason:'A nearer geographical ancestor is locked',locationID:f.locationID});continue;}
const references=byLocation.get(chain[index].locationID),reference=references[0];
if(references.some(r=>Math.hypot(r.delta[0]-reference.delta[0],r.delta[1]-reference.delta[1])>1e-6)){attention.push({featureID:f.featureID,name:f.name,reason:'Ancestor has several map anchors with different displacements',locationID:f.locationID});continue;}
f.x+=reference.delta[0];f.y+=reference.delta[1];f.isPlaced=true;
inherited.push({featureID:f.featureID,name:f.name,locationID:f.locationID,ancestor:chain[index].locationName||reference.feature.name,via:chain.slice(1,index).map(l=>l.locationName||'Unnamed location'),kind:f.geometryClass});
}
// Endpoints always win over a path's optional Location association. Each existing path is one segment.
let blocked=false;
const current=new Map(output.map(f=>[f.featureID,f]));
for(let i=0;i<output.length;i++){
const f=output[i];if(!anchored(f))continue;
const ids=[f.startFeatureID,f.endFeatureID].filter(Boolean),missing=ids.some(id=>!original.has(id)||original.get(id).geometryClass!=='Marker');
const moved=ids.some(id=>{const a=original.get(id),b=current.get(id);return a&&b&&(Math.abs(a.x-b.x)>1e-7||Math.abs(a.y-b.y)>1e-7);});
if(missing)attention.push({featureID:f.featureID,name:f.name,reason:'Missing or invalid endpoint anchor'});
if(!moved)continue;
if(missing||f.isLocked){blocked=true;if(f.isLocked)attention.push({featureID:f.featureID,name:f.name,reason:'Unlock this path before repositioning its endpoints'});continue;}
try{output[i]=E.transformAnchoredPath(original.get(f.featureID),features,output);paths.push({name:f.name,featureID:f.featureID});}
catch(error){blocked=true;attention.push({featureID:f.featureID,name:f.name,reason:error.message});}
}
for(const f of output)if(![f.x,f.y].every(n=>Number.isFinite(n)&&Math.abs(n)<=100000)){blocked=true;attention.push({featureID:f.featureID,name:f.name,reason:'Proposed position exceeds safe canvas limits'});}
for(const f of output)if(f.geometryClass==='Path'&&JSON.stringify(f)!==JSON.stringify(original.get(f.featureID))&&!paths.some(p=>p.featureID===f.featureID))paths.push({name:f.name,featureID:f.featureID});
// Inherited pieces are no longer reported as pending objects that will stay behind.
const following=new Set(inherited.map(p=>p.featureID));
const kept=skipped.filter(p=>!following.has(p.featureID));
const changed=output.filter(f=>JSON.stringify(f)!==JSON.stringify(original.get(f.featureID))).length;
const counts={positioned:new Set(positioned.map(p=>p.locationID)).size,descendants:new Set(inherited.map(p=>p.locationID)).size,paths:paths.length,otherPieces:inherited.filter(p=>p.kind!=='Marker').length,unchanged:blocked?output.length:output.length-changed,attention:new Set(attention.map(p=>p.featureID)).size};
return {features:blocked?E.copy(features):output,positioned,skipped:kept,inherited,paths,attention,counts,canApply:!blocked&&changed>0,message:blocked?'Some paths or positions cannot be transformed safely. Resolve the attention items before applying; no changes will be applied.':changed?`${positioned.length} geographical pieces, ${inherited.length} descendants and ${paths.length} paths are included in this proposal.`:'These places are already in the proposed positions. No changes are needed.'};
}
root.PlotDirectorGeography={position};
if(typeof module!=='undefined')module.exports={position};

View File

@ -414,15 +414,20 @@
if(!doc||busy||drag||mode!=='create'||window.PlotDirectorMapAppearance?.adjusting)return;
busy=true;updateButtons();const before=snapshot();
try{
const response=await fetch('/Geography/State?projectId='+boot.projectId,{cache:'no-store'});
const response=await fetch('/Geography/State?projectId='+boot.projectId+'&includeHierarchy=true',{cache:'no-store'});
if(!response.ok||response.redirected)throw Error('Could not load geographical resolutions. Your map is unchanged.');
const states=await response.json();
const payload=await response.json(),states=Array.isArray(payload)?payload:payload.states,hierarchy=Array.isArray(payload)?boot.locations:payload.locations;
if(!Array.isArray(states)||!Array.isArray(hierarchy))throw Error('Could not load the Location hierarchy. Your map is unchanged.');
if(snapshot()!==before)throw Error('The map changed while loading. Try positioning again.');
const result=window.PlotDirectorGeography.position(doc.features,states,view);
const result=window.PlotDirectorGeography.position(doc.features,states,view,hierarchy);
const summary=$('mapsGeographicSummary');summary.replaceChildren();
const add=(text,id)=>{const p=document.createElement('p');p.textContent=text;if(id){const link=document.createElement('a');link.href='/Locations/Details/'+id;link.target='_blank';link.rel='noopener';link.textContent=' Inspect location';p.append(link);}summary.append(p);};
$('mapsGeographicMessage').textContent=result.message+(result.skipped.length?' '+result.skipped.length+' linked locations will stay unchanged; see their status below.':'');
$('mapsGeographicMessage').textContent=result.message+(result.counts?` ${result.counts.otherPieces} other inherited pieces; ${result.counts.unchanged} objects unchanged; ${result.counts.attention} need attention.`:'')+(result.skipped.length?' '+result.skipped.length+' linked locations will stay unchanged; see their status below.':'');
for(const item of result.positioned)add((result.canApply?'Move: ':'Ready: ')+item.name);
if(result.counts)add(`${result.counts.positioned} geographical locations · ${result.counts.descendants} descendants · ${result.counts.paths} roads/paths · ${result.counts.otherPieces} other inherited pieces · ${result.counts.unchanged} unchanged · ${result.counts.attention} need attention`);
for(const item of result.inherited||[])add(item.name+' → Follows '+item.ancestor+(item.via.length?' via '+item.via.join(' → '):''));
for(const item of result.paths||[])add('Transform path: '+item.name);
for(const item of result.attention||[])add('Attention: '+item.name+' — '+item.reason,item.locationID);
for(const item of result.skipped)add('Keep: '+item.name+' — '+item.reason,item.locationID);
for(const attribution of new Set(result.positioned.map(p=>p.attribution).filter(Boolean)))add(attribution);
preview=result;render();
@ -441,7 +446,7 @@
$('mapsGeographicPreview').replaceChildren(drawing);
$('mapsGeographicApply').disabled=!result.canApply;
$('mapsGeographicRequest').hidden=!result.skipped.some(p=>p.canRequest);
$('mapsGeographicList').open=!result.canApply||result.skipped.length>0;
$('mapsGeographicList').open=!result.canApply||result.skipped.length>0||(result.attention?.length||0)>0;
if(!$('mapsGeographicDialog').open)$('mapsGeographicDialog').showModal();
}catch(error){preview=null;render();$('mapsGeographicApply').disabled=true;$('mapsGeographicPreview').replaceChildren();status(error.message,true);$('mapsGeographicRequestStatus').textContent=error.message;}finally{busy=false;updateButtons();}
}