diff --git a/Docs/Maps_Stage1.md b/Docs/Maps_Stage1.md index 23d1a404..68e26e9c 100644 --- a/Docs/Maps_Stage1.md +++ b/Docs/Maps_Stage1.md @@ -9,6 +9,7 @@ Maps is a project-scoped spatial writing workspace. The direct `/Maps` address o - Terrain includes mountain ranges, hills, forests, marsh, desert, plains and farmland. Water includes lakes, rivers, streams and canals. Routes include roads, tracks, trails, railway, sea routes and walls. Region overlays have their own layer. - Resize areas/paths by dragging their corner or changing dimensions. Rotate in Details. Edit Shape exposes simple points; Add Bend/Shape Point subdivides the longest segment. Coastline presets are deterministic. Rendering never changes saved control points. - Existing unplaced story Locations have a separate searchable tray. Their placement links the existing ID. Appearance can be changed afterwards. A new feature offers explicit Location creation; checking it establishes the place. Provisional features do not silently create canonical Locations. Geographic features can remain unlinked. +- **Define a place first** supports the relationship-first workflow: name a new piece, choose another place and direction/distance, and position only the new piece. Existing author positions stay unchanged. - Define any pair of features as one north/east/etc. of another, with optional friendly relative distance, measured distance/unit and typical travel time. The visual geometry suggests the initial direction. Measured distance and travel time are independent data. - Arrange from relationships is explicit and previewed. Cancel preserves the document. Apply is undoable. Locked pieces and established component anchors stay put; manual positions have a restoring weight. The unplaced-only option moves only pieces marked unplaced. Contradictions produce observations, not save failures. Measured distances never determine canvas spacing. - Paths can attach each endpoint to a marker. Attached endpoints follow marker movement; the intervening author-controlled bends remain editable. Detach by choosing Unattached. diff --git a/PlotLine.Tests/Browser/maps-dev-smoke.cjs b/PlotLine.Tests/Browser/maps-dev-smoke.cjs index 9866ac67..8c763f48 100644 --- a/PlotLine.Tests/Browser/maps-dev-smoke.cjs +++ b/PlotLine.Tests/Browser/maps-dev-smoke.cjs @@ -38,6 +38,9 @@ const base='https://dev.plotdirector.com'; // Save from a focused name field must commit the edit and reuse the same canonical Location ID. await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID);await page.locator('[data-field=name]').fill('Harbour town revised');await page.keyboard.press('Control+s');await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved'); assert(await page.evaluate(({id,locationID})=>{const f=window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===id);return f.name==='Harbour town revised'&&f.locationID===locationID;},{id:towns[0].featureID,locationID})); + const established=await page.evaluate(()=>window.PlotDirectorMapWorkspace.document.features.map(f=>({id:f.featureID,x:f.x,y:f.y}))); + await page.locator('#mapsDefine').click();const definition=page.locator('dialog[open]');await definition.locator('[name=name]').fill('Northern planning village');await definition.locator('[name=type]').selectOption('Village');await definition.locator('[name=targetID]').selectOption(towns[0].featureID);await definition.locator('[name=direction]').selectOption('N');await definition.getByRole('button',{name:'Add place',exact:true}).click(); + assert(await page.evaluate(previous=>previous.every(p=>{const f=window.PlotDirectorMapWorkspace.document.features.find(f=>f.featureID===p.id);return f.x===p.x&&f.y===p.y;}),established),'relationship-first placement preserves established positions');await page.locator('#mapsSave').click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved'); await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),towns[0].featureID);await page.locator('[data-action=child]').click();await page.locator('#mapsNewForm [name=Name]').fill('Harbour detail'); const rootID=new URL(rootURL).searchParams.get('id');await page.locator('#mapsNewForm button[type=submit]').click();await page.waitForURL(url=>url.searchParams.get('id')!==rootID&&url.pathname==='/Maps');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace); assert.equal(await page.locator('#mapsBreadcrumbs a').count(),3,'hierarchy breadcrumbs');const childURL=page.url(); diff --git a/PlotLine.Tests/Browser/maps-engine.cjs b/PlotLine.Tests/Browser/maps-engine.cjs index 0bca8b1d..e1ec7713 100644 --- a/PlotLine.Tests/Browser/maps-engine.cjs +++ b/PlotLine.Tests/Browser/maps-engine.cjs @@ -8,10 +8,10 @@ assert.equal(E.suggestedDirection(first.features[1],first.features[0]),'NW'); assert.equal(E.suggestedDirection(first.features[2],first.features[1]),'E'); assert.deepEqual(first,E.arrange([a,b,c],rel.map(r=>({...r,measuredDistance:999999999}))), 'physical distance never drives canvas spacing'); assert.equal(a.x,0,'preview never mutates author data'); -b.isPlaced=false;const partial=E.arrange([a,b,c],rel,true);assert.equal(partial.features[0].x,a.x);assert.equal(partial.features[2].x,c.x); -b.isLocked=true;assert.equal(E.arrange([a,b],rel).features[1].x,b.x);b.isLocked=false; +a.x=.123456;a.y=-.987654;b.isPlaced=false;const partial=E.arrange([a,b,c],rel,true);assert.equal(partial.features[0].x,a.x);assert.equal(partial.features[2].x,c.x); +b.x=10.123456;b.isLocked=true;assert.equal(E.arrange([a,b],rel).features[1].x,b.x,'locked positions retain full precision');b.isLocked=false; const conflicts=E.arrange([a,b],[{relationshipID:'1',sourceID:'a',targetID:'b',direction:'N'},{relationshipID:'2',sourceID:'b',targetID:'a',direction:'N'}]);assert(conflicts.warnings.length,'contradictions are observations'); -const route=E.makeFeature('Road',0,0,'road');route.startFeatureID='a';route.endFeatureID='b';a.x=150;b.x=700; +const route=E.makeFeature('Road',0,0,'road');route.startFeatureID='a';route.endFeatureID='b';a.x=150;a.y=0;b.x=700; const points=E.pathPoints(route,[a,b]);assert.deepEqual(points[0],[150,0]);assert.deepEqual(points.at(-1),[700,10]); const island=E.makeFeature('Island',0,0,'island');assert.equal(E.curve(E.coastline(island),true),E.curve(E.coastline(island),true)); assert(E.library.length>70);assert(E.library.some(x=>x.type==='Forest'&&x.geometryClass==='Area'));assert(E.library.some(x=>x.type==='River'&&x.geometryClass==='Path')); diff --git a/PlotLine.Tests/Browser/maps-workspace.cjs b/PlotLine.Tests/Browser/maps-workspace.cjs index 06422ef4..12444357 100644 --- a/PlotLine.Tests/Browser/maps-workspace.cjs +++ b/PlotLine.Tests/Browser/maps-workspace.cjs @@ -66,6 +66,9 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5246'; const same=await page.evaluate(()=>{window.__mapCanvas=document.getElementById('mapsCanvas');return true;}); await sourceClick('mapsZoomIn');await sourceClick('mapsZoomOut');assert(await page.evaluate(()=>window.__mapCanvas===document.getElementById('mapsCanvas'))); await page.screenshot({path:`/tmp/maps-${pwa?'pwa':'web'}.png`}); + const 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'); const scale=await page.evaluate(()=>{const w=window.PlotDirectorMapWorkspace;for(let i=0;i<500;i++)w.document.features.push(window.PlotDirectorMaps.makeFeature('Village',(i%25)*110,Math.floor(i/25)*100,crypto.randomUUID()));const start=performance.now();w.fit();return {ms:performance.now()-start,count:document.querySelectorAll('.maps-feature').length};}); assert(scale.count>500&&scale.ms<3000,'substantial maps render practically'); assert.deepEqual(errors,[]);console.log(`PASS Maps ${pwa?'PWA':'web'}: 7-piece author workflow, Location tray, relationships, arrangement preview/cancel/apply/undo, attached roads, Explore search, Story boundary, stable canvas and maximise`); diff --git a/PlotLine/Views/Maps/Index.cshtml b/PlotLine/Views/Maps/Index.cshtml index cea4d93e..93c52cc2 100644 --- a/PlotLine/Views/Maps/Index.cshtml +++ b/PlotLine/Views/Maps/Index.cshtml @@ -25,7 +25,7 @@ diff --git a/PlotLine/wwwroot/js/maps-engine.js b/PlotLine/wwwroot/js/maps-engine.js index 6d943b4a..4672a620 100644 --- a/PlotLine/wwwroot/js/maps-engine.js +++ b/PlotLine/wwwroot/js/maps-engine.js @@ -116,7 +116,7 @@ const a=byId.get(r.sourceID),b=byId.get(r.targetID); if(!r.connection&&((r.direction&&suggestedDirection(a,b)!==r.direction)||(r.relativeDistance&&Math.abs(Math.hypot(a.x-b.x,a.y-b.y)-spacing(a,b,r))>spacing(a,b,r)*.5)))warnings.push(`${a.name} ${r.direction} of ${b.name}`); } - result.forEach(f=>{if(movable(f))f.isPlaced=true;f.x=Math.round(f.x*100)/100;f.y=Math.round(f.y*100)/100;}); + result.forEach(f=>{if(movable(f)){f.isPlaced=true;if(!anchored.has(f.featureID)){f.x=Math.round(f.x*100)/100;f.y=Math.round(f.y*100)/100;}}}); return {features:result,warnings}; } return {library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange}; diff --git a/PlotLine/wwwroot/js/maps-workspace.js b/PlotLine/wwwroot/js/maps-workspace.js index fe7345dc..ca55871d 100644 --- a/PlotLine/wwwroot/js/maps-workspace.js +++ b/PlotLine/wwwroot/js/maps-workspace.js @@ -153,6 +153,17 @@ if(name==='unplace')safeEdit(()=>{f.isPlaced=false;}); if(name==='bend')safeEdit(()=>{const g=E.geometry(f),pts=g.points||[];if(pts.length>=64)return;let index=0,longest=0;for(let i=0;ilongest){longest=len;index=i;}}const next=pts[(index+1)%pts.length];pts.splice(index+1,0,[(pts[index][0]+next[0])/2,(pts[index][1]+next[1])/2]);g.points=pts;f.geometryJson=JSON.stringify(g);shapeEdit=true;}); } + function definePlace(){ + if(!doc||busy||mode!=='create')return; + const dialog=document.createElement('dialog');dialog.innerHTML=`

Define a place

Only this new piece will be positioned. You can move it afterwards and decide later whether to create a story Location.

`; + app.append(dialog);dialog.showModal();dialog.onclose=()=>dialog.remove();dialog.querySelector('[data-cancel]').onclick=()=>dialog.close(); + dialog.querySelector('form').onsubmit=e=>{e.preventDefault();const v=Object.fromEntries(new FormData(e.target));safeEdit(()=>{ + 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]); + });dialog.close();}; + } async function newMap(feature=null){if(busy)return;if(feature&&dirty&&!(await save()))return;parentFeature=feature?.featureID||null;const form=$('mapsNewForm');form.reset();form.elements.Name.value=feature?feature.name+' detail':'';form.elements.ParentMapID.value=feature?doc.map.mapID:'';$('mapsNewDialog').showModal();} async function createMap(e){e.preventDefault();const values=Object.fromEntries(new FormData(e.target));if(dirty&&!parentFeature&&!confirm('Leave this map and discard unsaved changes?'))return; const data={ProjectID:boot.projectId,Name:values.Name,Kind:values.Kind};if(values.ParentMapID)data.ParentMapID=values.ParentMapID;if(parentFeature)data.ParentFeatureID=parentFeature; @@ -220,7 +231,7 @@ function undo(redo=false){if(busy||preview)return;const from=redo?future:history,to=redo?history:future;if(!from.length)return;to.push(snapshot());doc=JSON.parse(from.pop());selected.clear();changed();render();details();locations();} $('mapsSelectorForm').onsubmit=e=>e.preventDefault();$('mapsSearchForm').onsubmit=e=>e.preventDefault(); $('mapsSave').onclick=save;$('mapsUndo').onclick=()=>undo();$('mapsRedo').onclick=()=>undo(true);$('mapsSelect').onchange=e=>navigate(Number(e.target.value)); - $('mapsNew').onclick=()=>newMap();$('mapsWelcomeNew').onclick=()=>newMap();$('mapsNewCancel').onclick=()=>$('mapsNewDialog').close();$('mapsNewForm').onsubmit=createMap; + $('mapsDefine').onclick=definePlace;$('mapsNew').onclick=()=>newMap();$('mapsWelcomeNew').onclick=()=>newMap();$('mapsNewCancel').onclick=()=>$('mapsNewDialog').close();$('mapsNewForm').onsubmit=createMap; $('mapsRename').onclick=()=>{if(!doc)return;const name=prompt('Map name',doc.map.name);if(name?.trim())safeEdit(()=>{doc.map.name=name.trim().slice(0,200);crumbs();});}; $('mapsDuplicate').onclick=async()=>{if(!doc||busy||preview)return;if(dirty&&!(await save()))return;try{const result=await request('Create',{ProjectID:boot.projectId,Name:doc.map.name+' copy',Kind:doc.map.kind,...(doc.map.parentMapID?{ParentMapID:doc.map.parentMapID}:{})});const d=clone(doc);d.map.mapID=result.id;d.map.name+=' copy';d.map.revision=0;d.features.forEach(f=>f.createLocation=false);await request('Save',d,true);dirty=false;location.href=url(result.id);}catch(error){status(error.message,true);}}; $('mapsDelete').onclick=async()=>{if(!doc||busy||preview)return;if(!confirm(`Delete “${doc.map.name}”? Detailed child maps will become top-level maps. Story Locations and Floor Plans are kept.`))return;try{await request('Delete',{projectId:boot.projectId,id:doc.map.mapID,revision:doc.map.revision});dirty=false;location.href=url();}catch(error){status(error.message,true);}};