PlotDirector/PlotLine/wwwroot/js/maps-workspace.js

515 lines
89 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(() => {
'use strict';
const E=window.PlotDirectorMaps,T=window.PlotDirectorTopology, boot=JSON.parse(document.getElementById('mapsBootstrap').textContent);
const $=id=>document.getElementById(id),app=$('mapsApp'),svg=$('mapsCanvas'),scene=$('mapsScene'),handles=$('mapsHandles');
const ns='http://www.w3.org/2000/svg',esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&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,settlementMode='whole';
let view={x:-600,y:-400,w:1200,h:800},drag=null,clipboard=null;
const hiddenLayers=new Set(),nodes=new Map(),boundaryNodes=new Map(),labelNodes=new Map(),sharedNodes=new Map();
let selectedEdge=null,joinEnds=[],snapVertex=true,snapEdge=true,snapHint=null,renderOrder=[];
const labels=svgNode('g',{id:'mapsLabels','pointer-events':'none'});scene.after(labels);
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||node?.dataset.sharedAreaId;
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'){containmentDirty=true;dirty=true;status(message);updateButtons();}
function edit(action){if(!doc||mode!=='create'||preview||busy)return;const before=snapshot(),redo=future.slice();checkpoint();try{action();changed();}catch(error){doc=JSON.parse(before);history.pop();future=redo;status(error.message,true);}render();details();locations();}
function updateButtons(){ const area=doc?.features.find(f=>selected.has(f.featureID));document.querySelectorAll('[data-topology][data-pwa-context]').forEach(b=>{b.hidden=mode!=='create';b.disabled=!area||!E.isArea(area)||selected.size!==1||area.isLocked||busy||!!preview||(b.dataset.topology==='unjoin'&&!T.linked(area));}); document.querySelectorAll('[data-map-order]').forEach(b=>{b.hidden=mode!=='create';b.disabled=!doc||busy||!!preview||!doc.features.some(f=>selected.has(f.featureID)&&!f.isLocked);}); $('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){
const response=await fetch('/Maps/'+action,{method:'POST',headers:{'RequestVerificationToken':token,...(json?{'Content-Type':'application/json'}:{})},body:json?JSON.stringify(data):new URLSearchParams(data)});
if(response.redirected)throw new Error('Your session or subscription needs attention. Open your account in another tab; your edits remain here.');
const content=await response.json().catch(()=>null);
if(!response.ok)throw new Error(content?.message||`Could not ${action.toLowerCase()} map (${response.status}). Your edits remain here.`);
return content;
}
async function save(options={}){
if(!doc||busy||preview||drag||window.PlotDirectorMapAppearance?.adjusting||(mode!=='create'&&!options.forNavigation))return false;
busy=true;updateButtons();const sent=snapshot();status('Saving…');
try{
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;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);
for(const f of doc.features)if(f.locationID&&!boot.locations.some(l=>l.locationID===f.locationID))boot.locations.push({locationID:f.locationID,locationName:f.name,projectID:boot.projectId});
$('mapsSelect').selectedOptions[0].textContent=doc.map.name;status('Saved');render();details();locations();return true;
}catch(error){status(error.message,true);return false;}finally{busy=false;updateButtons();}
}
function safeEdit(action){if(!busy)edit(action);}
function url(id){return '/Maps?projectId='+boot.projectId+(id?'&id='+id:'')+(mode==='story'&&id?'&mode=story'+(window.PlotDirectorStoryOverlay?.state.sceneID?'&sceneId='+window.PlotDirectorStoryOverlay.state.sceneID:'')+(window.PlotDirectorStoryOverlay?.data?.scenarioID?'&scenarioId='+window.PlotDirectorStoryOverlay.data.scenarioID:''):'')+detachedQuery;}
async function requestLeave(action){
window.PlotDirectorMapAppearance?.completeAdjustment();
if(leavePending||busy)return false;
if(!dirty){await action();return true;}
leavePending=action;
try{
const answer=await window.PlotDirectorDialogs.choose({title:'Unsaved map changes',message:"You have changes to this map that haven't been saved. What would you like to do?",actions:[
{label:'Save and continue',value:'save',className:'btn-primary',run:()=>save({forNavigation:true})},
{label:'Discard changes',value:'discard',className:'btn-outline-danger'},
{label:'Keep editing',value:'keep'}]});
if(!['save','discard'].includes(answer?.value))return false;
if(answer.value==='discard'){doc=clone(savedDocument);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;}
}
function navigate(id){return requestLeave(()=>{location.href=url(id);});}
document.addEventListener('click',e=>{
if(e.defaultPrevented||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;
const link=e.target.closest('a[href]');if(!link||link.hasAttribute('download')||(link.target&&link.target!=='_self'))return;
const destination=new URL(link.href,location.href);if(destination.origin!==location.origin||!/^https?:$/.test(destination.protocol)||link.getAttribute('href').startsWith('#'))return;
if(!dirty){return;}e.preventDefault();e.stopImmediatePropagation();requestLeave(()=>{location.href=destination.href;});
},true);
let continuingForm=null;
document.addEventListener('submit',e=>{
const form=e.target;if(!dirty||e.defaultPrevented||form===continuingForm||form.closest('#mapsApp')||form.matches('[data-appearance-form]')||!form.hasAttribute('action')||(form.target&&form.target!=='_self'))return;
const destination=new URL(e.submitter?.hasAttribute('formaction')?e.submitter.formAction:form.action,location.href);if(destination.origin!==location.origin)return;
e.preventDefault();e.stopImmediatePropagation();const submitter=e.submitter;
requestLeave(()=>{continuingForm=form;try{form.requestSubmit(submitter?.isConnected?submitter:undefined);}finally{continuingForm=null;}});
},true);
function svgNode(tag,attrs={}){const node=document.createElementNS(ns,tag);for(const[k,v]of Object.entries(attrs))node.setAttribute(k,v);return node;}
function applyView(){svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);$('mapsZoom').textContent=Math.round(1200/view.w*100)+'%';render();}
function scaleForSnap(){const m=svg.getScreenCTM();return 1/Math.hypot(m.a,m.b);}
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){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,topology=null){
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]);
if(topology&&(T.linked(f)||geometry.edgeShapes?.some(Boolean))){const edges=T.paths(f,topology),d=edges.map((q,i)=>T.path(q,i===0)).join(' ')+' Z';let result=`<path class="maps-area-fill" d="${d}" fill="${fill}" fill-opacity="${opacity}" stroke="none"/>`;edges.forEach((q,i)=>{if(geometry.edgeRefs?.[i])return;const style=geometry.edgeStyles?.[i];result+=`<path class="map-shape" d="${T.path(style?.reverseStroke?T.reverse(q):q)}" fill="none" ${style?borderStyle(style):`stroke="${stroke}" stroke-width="${width}" ${dash?`stroke-dasharray="${dash}"`:''}`}/>`;});return result;}
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 borderStyle(a){const colour=/^#[0-9a-f]{6}$/i.test(a.borderColor||'')?a.borderColor:a.theme==='settlement'?'var(--maps-settlement-line,#62507c)':a.theme==='region'?'var(--maps-region-line,#80699b)':'var(--maps-terrain-line,#91a087)',width=Number.isFinite(a.borderWidth)?Math.max(0,Math.min(30,a.borderWidth)):2,dash=({'Solid':'','Dashed':'8 5','Dotted':'2 5'})[a.borderStyle]??(a.theme==='region'?'8 5':'');return `stroke="${colour}" stroke-width="${width}" ${dash?`stroke-dasharray="${dash}"`:''} stroke-linejoin="round"`;}
function topologyEdit(operation){if(!doc||busy||preview||mode!=='create')return;try{const features=operation(doc.features);safeEdit(()=>doc.features=features);return true;}catch(error){status(error.message,true);return false;}}
function movementBlocked(f){if(E.isArea(f)&&T.linked(f)){status('This area has shared boundaries. Unjoin them before moving, resizing or rotating it independently; shared vertices remain editable.',true);return true;}return false;}
function boundaryTools(f){const g=E.areaGeometry(f),ids=[...new Set((g.edgeRefs||[]).filter(Boolean))],c=T.context(doc.features);if(selectedEdge&&!ids.includes(selectedEdge))selectedEdge=null;selectedEdge||=ids[0]||null;return `<div class="maps-topology-tools"><label><input type="checkbox" data-snap="vertex" ${snapVertex?'checked':''}/> Snap to vertex</label><label><input type="checkbox" data-snap="edge" ${snapEdge?'checked':''}/> Snap to edge</label><p class="maps-hint">10 pixel tolerance. Hold Alt while dragging a point to disable snapping; Alt + click still cycles overlapping pieces. Snapping does not join areas.</p><button type="button" data-topology="join">Join boundaries</button>${ids.length?`<label>Shared boundary <select data-shared-selection>${ids.map(id=>option(id,c.users(id).map(fid=>doc.features.find(x=>x.featureID===fid)?.name).join(' / ')+' · '+(ids.indexOf(id)+1),selectedEdge)).join('')}</select></label><label>Shared smoothing <select data-shared-smoothing>${['Natural','Gentle','Rugged','Cliffs','Fjords','Marsh/Delta'].map(v=>option(v,v,c.edges.get(selectedEdge)?.coast)).join('')}</select></label><button type="button" data-topology="insert">Insert shared vertex</button><button type="button" data-topology="unjoin">Unjoin boundary</button>${ids.length>1?'<button type="button" data-topology="unjoin-all">Unjoin all boundaries</button>':''}<p class="maps-hint">Shared curves use the retained area's border style. Edit their points from either area; locked neighbours must be unlocked first.</p>`:''}</div>`;}
function joinDialog(){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||!E.isArea(f)||f.isLocked)return;const others=doc.features.filter(x=>x.featureID!==f.featureID&&E.isArea(x)&&!x.isLocked);if(!others.length){status('Add another unlocked geographical area first.');return;}const points=T.controls(f,doc.features),dialog=document.createElement('dialog');dialog.innerHTML=`<form><h2>Join boundaries</h2><p>Snap two vertices to the neighbouring boundary first, then choose the sections to join. Existing shared sections are protected.</p><label>Neighbour <select name="neighborID">${others.map(x=>option(x.featureID,x.name,others[0].featureID)).join('')}</select></label>${[['start','First endpoint',joinEnds[0]??0],['end','Second endpoint',joinEnds[1]??1]].map(([key,label,current])=>`<label>${label}<select name="${key}">${points.map((_,i)=>option(i,'Vertex '+(i+1),current)).join('')}</select></label>`).join('')}${[['sourceDirection','Section on selected area'],['neighborDirection','Section on neighbour']].map(([key,label])=>`<label>${label}<select name="${key}">${[['shorter','Shorter section'],['forward','Forward around boundary'],['backward','Backward around boundary']].map(([v,t])=>option(v,t,'shorter')).join('')}</select></label>`).join('')}<label>Retain geometry <select name="retain"><option value="neighbor">Neighbour's boundary (default)</option><option value="selected">Selected area's boundary</option></select></label><p data-join-error role="alert"></p><button type="button" data-cancel>Cancel</button><button type="submit">Join boundaries</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 v=Object.fromEntries(new FormData(e.target));try{const features=T.join(doc.features,{...v,areaID:f.featureID,start:Number(v.start),end:Number(v.end)});safeEdit(()=>doc.features=features);shapeEdit=true;settlementMode='boundary';joinEnds=[];dialog.close();render();details();}catch(error){dialog.querySelector('[data-join-error]').textContent=error.message;}};}
function topologyAction(name){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||!E.isArea(f)||f.isLocked)return;if(name==='join'){joinDialog();return;}if(name==='unjoin'||name==='unjoin-all'){topologyEdit(features=>T.unjoin(features,f.featureID,name==='unjoin-all'?null:selectedEdge));selectedEdge=null;details();return;}if(name==='insert'){const c=T.context(doc.features),index=c.area(f.featureID).edgeRefs?.indexOf(selectedEdge);if(index>=0){const cs=T.edgeCurves(f,index,c),ci=Math.floor(cs.length/2);topologyEdit(features=>T.insert(features,f.featureID,index,ci,.5));shapeEdit=true;render();details();}}}
document.addEventListener('click',e=>{const b=e.target.closest('[data-topology]');if(b)topologyAction(b.dataset.topology);});
function render(affected=null){
if(!doc)return;window.PlotDirectorMapAppearance?.render();
const rendering=preview?.features||doc.features,topology=T.context(rendering);
const visible=rendering.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 visibleByID=new Map(visible.map(f=>[f.featureID,f])),ordered=affected&&renderOrder.length===visible.length?renderOrder.map(id=>visibleByID.get(id)):E.drawingOrder(visible);if(!affected)renderOrder=ordered.map(f=>f.featureID);
for(const[id,node]of labelNodes)if(!alive.has(id)){node.remove();labelNodes.delete(id);}
for(const f of ordered){
if(affected&&!affected.has(f.featureID))continue;
let g=nodes.get(f.featureID);if(!g){g=svgNode('g',{'data-feature-id':f.featureID,tabindex:'0',role:'button'});nodes.set(f.featureID,g);scene.append(g);}
const isSelected=selected.has(f.featureID);g.setAttribute('class',`maps-feature${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}${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,topology);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>`;
}else if(f.geometryClass==='Path'){
const water=['River','Stream','Canal'].includes(f.type),rail=f.type==='Railway',road=['Road','Major road'].includes(f.type);
const d=E.curve(E.pathPoints(f,preview?.features||doc.features)),color=water?'var(--maps-water-line,#4c92ae)':rail?'var(--maps-map-ink,#5b635d)':f.type==='Sea route'?'var(--maps-water-line,#557f94)':'var(--maps-route-line,#99764b)';
const width=f.type==='Major road'?8:road?5:f.type==='Stream'?3:water?7:3;
markup=`<path class="map-shape" d="${d}" fill="none" stroke="${color}" stroke-width="${width}" ${['Trail','Track','Sea route','Railway'].includes(f.type)?'stroke-dasharray="8 6"':''}/>`;
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{
markup=areaMarkup(f,false,topology);
}
let overlay=isSelected&&E.isArea(f)?`<path d="${T.paths(f,topology).map((q,i)=>T.path(q,i===0)).join(' ')} Z" fill="none" stroke="var(--maps-selection,#136883)" stroke-width="2"/>`.replace(/fill="[^"]*"/,'fill="none"').replace(/stroke="[^"]*"/,'stroke="var(--maps-selection,#136883)"'):'';
if(isSelected&&E.isSettlement(f)){
const r=27*scale,gap=18*scale;
overlay+=`<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;
if(!f.labelX&&!f.labelY)for(let attempt=0;attempt<5;attempt++){if(!labelBoxes.some(b=>Math.abs(b.x-x)<(b.w+width)/2&&Math.abs(b.y-y)<18*scale))break;y+=19*scale;}
labelBoxes.push({x,y,w:width});overlay+=`<text class="map-label" x="${x}" y="${y}" text-anchor="middle" style="font-size:${13*scale}px;stroke-width:${4*scale}px" pointer-events="none">${esc(text)}</text>`;
}
if(g.innerHTML!==markup)g.innerHTML=markup;
let label=labelNodes.get(f.featureID);if(!label){label=svgNode('g',{'data-label-feature-id':f.featureID});labelNodes.set(f.featureID,label);labels.append(label);}if(label.innerHTML!==overlay)label.innerHTML=overlay;
// append only when ordering changes, preserving DOM focus on normal updates
}
const edgeAfter=new Map(),aliveEdges=new Set(),edgeMembers=new Map();for(const f of ordered)if(E.isArea(f))for(const id of new Set(topology.area(f.featureID).edgeRefs||[])){if(!id)continue;if(!edgeMembers.has(id))edgeMembers.set(id,[]);edgeMembers.get(id).push(f);}for(const[id,edge]of topology.edges){const members=edgeMembers.get(id)||[];if(!members.length)continue;aliveEdges.add(id);let node=sharedNodes.get(id);if(!node){node=svgNode('g',{'data-shared-edge-id':id,tabindex:'0',role:'button'});sharedNodes.set(id,node);scene.append(node);}const owner=members.find(f=>selected.has(f.featureID))||members[0];node.dataset.sharedAreaId=owner.featureID;node.setAttribute('aria-label','Shared boundary: '+members.map(f=>f.name).join(' / '));node.setAttribute('class',selectedEdge===id&&selected.has(owner.featureID)?'maps-shared-edge is-selected':'maps-shared-edge');const sharedMarkup=`<path d="${T.path(edge.style.reverseStroke?T.reverse(T.sharedCurves(id,topology)):T.sharedCurves(id,topology))}" fill="none" ${borderStyle(edge.style)}/><path class="maps-shared-hit" d="${T.path(T.sharedCurves(id,topology))}" fill="none" stroke="transparent" stroke-width="${18*scale}"/>`;if(node.__topologyMarkup!==sharedMarkup){node.innerHTML=sharedMarkup;node.__topologyMarkup=sharedMarkup;}const last=members.at(-1).featureID;if(!edgeAfter.has(last))edgeAfter.set(last,[]);edgeAfter.get(last).push(node);}
for(const[id,node]of sharedNodes)if(!aliveEdges.has(id)){node.remove();sharedNodes.delete(id);}
if(!affected){
const layers=ordered.flatMap(f=>[E.hasBoundary(f)?boundaryNodes.get(f.featureID):nodes.get(f.featureID),...(edgeAfter.get(f.featureID)||[])]);
// Settlement anchor symbols stay above ordinary content, independently of fill order.
layers.push(...ordered.filter(E.hasBoundary).map(f=>nodes.get(f.featureID)));
layers.forEach((node,i)=>{if(scene.children[i]!==node)scene.insertBefore(node,scene.children[i]||null);});
}
updateButtons();renderHandles(scale);
if(snapHint){handles.append(svgNode('circle',{cx:snapHint.point[0],cy:snapHint.point[1],r:10*scale,class:'maps-snap-indicator','pointer-events':'none'}));}
window.PlotDirectorStoryOverlay?.redraw();
}
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(E.isArea(f)){
if(shapeEdit)T.controls(f,doc.features).forEach((p,i)=>{add(p,'point',i);if(E.areaGeometry(f).vertexRefs?.[i])handles.lastElementChild.classList.add('maps-shared-vertex');if(joinEnds.includes(i))handles.lastElementChild.classList.add('maps-join-endpoint');});
if(!T.linked(f))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){if(!selected.has(id)){selectedEdge=null;joinEnds=[];}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('');}
function locations(){if(!doc){$('mapsLocations').textContent='Open a map to place story Locations.';return;}const q=$('mapsLocationSearch').value.toLowerCase(),placed=new Set(doc.features.map(f=>f.locationID));$('mapsLocations').innerHTML=boot.locations.filter(l=>!l.isArchived&&!placed.has(l.locationID)&&l.locationName.toLowerCase().includes(q)).map(l=>`<button type="button" draggable="true" data-location="${l.locationID}">${esc(l.locationName)}</button>`).join('')||'<p class="maps-hint">No unplaced Locations match.</p>';}
function crumbs(){const list=[];let current=doc?.map,seen=new Set();while(current&&!seen.has(current.mapID)){seen.add(current.mapID);list.unshift(current);current=boot.maps.find(m=>m.mapID===current.parentMapID);} $('mapsBreadcrumbs').innerHTML=`<a href="${url()}">All maps</a>`+list.map(m=>`<span aria-hidden="true">›</span><a href="${url(m.mapID)}">${esc(m.name)}</a>`).join('');}
function option(value,label,selectedValue){return `<option value="${esc(value)}" ${String(value??'')===String(selectedValue??'')?'selected':''}>${esc(label)}</option>`;}
function field(label,key,value,type='text',attrs=''){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;}
if(window.PlotDirectorMapAppearance?.details())return;
if(mode==='story'&&window.PlotDirectorStoryOverlay?.details([...selected][0]))return;
const search='';
const f=doc.features.find(f=>selected.has(f.featureID));
if(!f){content.innerHTML=search+`<p>${esc(doc.map.name)} · ${doc.features.length} pieces</p><p>Pick a piece on the left, then click to place it. Drag the map background to pan. Alt + click to cycle overlapping pieces, or use Find on map to select by name.</p><p>◇ Planning pieces have dashed outlines. They become story Locations only when you choose.</p>`;return;}
if(selected.size>1){content.innerHTML=search+`<p>${selected.size} pieces selected.</p><div class="maps-edit-only"><button type="button" data-action="duplicate">Duplicate</button><button type="button" data-action="remove">Delete selection</button></div>`;return;}
const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===f.featureID),linked=boot.locations.find(l=>l.locationID===f.locationID);
const readonly=mode!=='create';
let html=search+`<h3>${esc(f.name)}</h3><p>${esc(f.type)}${f.isProvisional?' · ◇ Planning':''}${f.isLocked?' · Locked':''}${!f.isPlaced?' · Unplaced':''}</p>`;
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'&&(!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(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">${T.linked(f)?'Shared boundaries: edit common vertices or unjoin before moving the boundary. The anchor can still move independently.':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">${T.linked(f)?'Shared boundaries: edit common vertices or unjoin before moving, resizing or rotating.':'Drag the corner to resize. Edit points to reshape; right-click a point or press Delete to remove it.'}</p>`;
if(E.isArea(f))html+=boundaryTools(f);
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>`;
html+=`<details><summary>Floor Plan</summary><label>Link an existing Floor Plan <select data-field="floorPlanID">${option('','None',f.floorPlanID)}${boot.floorPlans.map(p=>option(p.floorPlanID,p.name,f.floorPlanID)).join('')}</select></label></details>`;
html+=`<div class="maps-inline"><button type="button" data-action="duplicate">Duplicate</button><button type="button" data-action="remove">Delete</button><button type="button" data-action="unplace">Mark as unplaced</button></div></div>`;
}
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);
html+=`<div class="maps-rel">${esc(a?.name)} ${esc(r.direction||'relative to')} ${esc(b?.name)} · ${esc(r.relativeDistance||'distance unspecified')}${r.measuredDistance!=null?` · ${esc(r.measuredDistance)} ${esc(r.unit)}`:''}${r.typicalTravelTime?` · travel: ${esc(r.typicalTravelTime)}`:''}${!readonly?` <button type="button" data-edit-rel="${r.relationshipID}">Edit</button> <button type="button" data-remove-rel="${r.relationshipID}" aria-label="Remove relationship">×</button>`:''}</div>`;
}
if(!readonly)html+='<button type="button" data-action="relationship">Add relationship</button>';
html+='</details>';content.innerHTML=html;if(T.linked(f))content.querySelectorAll('[data-area-frame],[data-field=width],[data-field=height],[data-rotate],[data-reset-rotation],[data-action=fit-boundary]').forEach(n=>n.disabled=true);
}
function relationEditor(id){const f=doc.features.find(f=>selected.has(f.featureID));if(!f)return;const old=doc.relationships.find(r=>r.relationshipID===id),other=doc.features.find(x=>x.featureID!==f.featureID);if(!old&&!other){status('Place a second item to define a relationship.');return;}
const r=old||{relationshipID:guid(),sourceID:f.featureID,targetID:other.featureID,direction:E.suggestedDirection(f,other),relativeDistance:'Close',measuredDistance:null,unit:'',typicalTravelTime:'',notes:''};
const dialog=document.createElement('dialog');dialog.innerHTML=`<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=T.remove(doc.features,ids);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()]));let 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}));copies=T.detachCopies(doc.features,copies,mapping);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;
if(E.isArea(f)){topologyEdit(features=>T.removePoint(features,f.featureID,index));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'){if(movementBlocked(f))return;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;if(E.hasBoundary(f))settlementMode=shapeEdit?'boundary':'whole';render();details();}
if(name==='unplace')safeEdit(()=>{f.isPlaced=false;});
if(name==='bend'&&E.isArea(f)){const c=T.context(doc.features),g=c.area(f.featureID),i=selectedEdge&&g.edgeRefs?g.edgeRefs.indexOf(selectedEdge):-1,idx=i>=0?i:Math.max(0,joinEnds.at(-1)??0),curves=T.edgeCurves(f,idx,c);if(topologyEdit(features=>T.insert(features,f.featureID,idx,Math.floor(curves.length/2),.5))){shapeEdit=true;render();details();}return;}
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;
const dialog=document.createElement('dialog');dialog.innerHTML=`<form><h2>Define a place</h2><label>Name <input name="name" maxlength="200" required autofocus /></label><label>Map piece <select name="type">${E.library.map(a=>option(a.type,a.type,'Town')).join('')}</select></label><label>Relative to <select name="targetID">${option('','No relationship yet','')}${doc.features.map(f=>option(f.featureID,f.name,'')).join('')}</select></label><label>This place is <select name="direction">${E.directions.map(d=>option(d,d,'N')).join('')}</select></label><label>Relative distance <select name="relativeDistance">${E.distances.map(d=>option(d,d,'Close')).join('')}</select></label><p>Only this new piece will be positioned. You can move it afterwards and decide later whether to create a story Location.</p><button type="button" data-cancel>Cancel</button><button type="submit">Add place</button></form>`;
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]);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));}
function openNewMap(intent){if(busy)return;const feature=doc?.features.find(f=>f.featureID===intent?.featureID);parentFeature=feature?.featureID||null;const form=$('mapsNewForm');form.reset();form.elements.Name.value=intent?(feature?.name||intent.name)+' detail':'';form.elements.ParentMapID.value=intent?doc.map.mapID:'';
let note=form.querySelector('[data-map-new-context]');if(!note){note=document.createElement('p');note.dataset.mapNewContext='';note.className='maps-hint';note.setAttribute('role','status');form.querySelector('h2').after(note);}note.hidden=!intent||!!feature;note.textContent='The unsaved feature was discarded. You can still create this map under the current map, without a feature link.';$('mapsNewDialog').showModal();}
async function createMap(e){e.preventDefault();const values=Object.fromEntries(new FormData(e.target));
const data={ProjectID:boot.projectId,Name:values.Name,Kind:values.Kind};if(values.ParentMapID)data.ParentMapID=values.ParentMapID;if(parentFeature)data.ParentFeatureID=parentFeature;
const submit=e.target.querySelector('[type=submit]');submit.disabled=true;
try{const result=await request('Create',data);let features=[];const add=(type,x,y,w,h)=>{const f=E.makeFeature(type,x,y,guid());f.width=w;f.height=h;features.push(f);};
if(['land','island','inland','local'].includes(values.Starter))add(values.Starter==='island'?'Island':'Land Mass',0,0,values.Starter==='local'?1000:850,650);
if(values.Starter==='two'){add('Land Mass',-290,0,480,600);add('Land Mass',300,40,430,570);}
if(values.Starter==='islands'){add('Island',-240,-100,370,300);add('Island',200,90,300,380);add('Island',-70,230,200,170);}
if(features.length){const created={map:{mapID:result.id,projectID:boot.projectId,name:values.Name,kind:values.Kind,revision:0},features,relationships:[]};await request('Save',created,true);}dirty=false;location.href=url(result.id);
}catch(error){status(error.message,true);}finally{submit.disabled=false;}}
const orderCommands={front:'Bring to front',forward:'Bring forward',backward:'Send backward',back:'Send to back'};
function changeDrawingOrder(command){
if(!doc||!selected.size||busy||preview||mode!=='create')return;
const trial=clone(doc.features);if(!E.reorder(trial,[...selected],command))return;
safeEdit(()=>{doc.features=trial;});status(orderCommands[command]+'. Unsaved changes.');
}
document.addEventListener('click',e=>{const button=e.target.closest('[data-map-order]');if(button)changeDrawingOrder(button.dataset.mapOrder);});
function previewArrange(){if(!doc||mode!=='create')return false;try{preview=E.arrange(doc.features,doc.relationships,$('mapsOnlyNew').checked);$('mapsArrangeWarnings').textContent=preview.warnings.length?'Some intentions cannot all be represented exactly: '+preview.warnings.slice(0,5).join('; ')+'. You can still apply and adjust manually.':'Preview ready. Locked pieces and established anchors stay in place.';render();updateButtons();return true;}catch(error){preview=null;status(error.message,true);render();updateButtons();return false;}}
// 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);
const removeRel=e.target.closest('[data-remove-rel]');if(removeRel)safeEdit(()=>doc.relationships=doc.relationships.filter(r=>r.relationshipID!==removeRel.dataset.removeRel));
const result=e.target.closest('[data-search-feature]');if(result){const f=doc.features.find(f=>f.featureID===result.dataset.searchFeature);select(f.featureID);fit([f]);$('mapsSearchResults').replaceChildren();}
});
document.addEventListener('change',e=>{
if(e.target.matches('[data-snap]')){if(e.target.dataset.snap==='vertex')snapVertex=e.target.checked;else snapEdge=e.target.checked;return;}
if(e.target.matches('[data-shared-selection]')){selectedEdge=e.target.value;render();details();return;}
if(e.target.matches('[data-shared-smoothing]')){topologyEdit(features=>T.smooth(features,selectedEdge,e.target.value));return;}
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(['width','height','rotation','type'].includes(key)&&movementBlocked(f))return;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;
if(e.target.dataset.areaFrame&&movementBlocked(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(''):'';}});
$('mapsAssetSearch').oninput=assets;$('mapsCategory').onchange=assets;$('mapsLocationSearch').oninput=locations;
app.addEventListener('dragstart',e=>{const target=e.target.closest('[data-asset],[data-location]');if(!target)return;e.dataTransfer.setData('application/plotdirector-map',JSON.stringify({type:target.dataset.asset||'Settlement',locationID:Number(target.dataset.location)||null}));e.dataTransfer.effectAllowed='copy';});
svg.addEventListener('dragover',e=>e.preventDefault());svg.addEventListener('drop',e=>{e.preventDefault();try{const data=JSON.parse(e.dataTransfer.getData('application/plotdirector-map'));place(data.type,world(e),data.locationID);}catch{status('Choose a map piece from the library.');}});
svg.addEventListener('pointerdown',e=>{
if(e.button!==0||!doc||busy||preview||e.target.closest('[data-story-key]'))return;const p=world(e),target=e.target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]'),handle=e.target.closest('[data-handle]');
e.preventDefault();window.getSelection()?.removeAllRanges();
if(e.altKey&&!handle&&!pending){
const hits=[...new Set(document.elementsFromPoint(e.clientX,e.clientY).map(n=>targetID(n.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]'))).filter(Boolean))];
if(hits.length){const current=hits.findIndex(id=>selected.has(id));select(hits[(current+1)%hits.length]);status('Selected '+doc.features.find(f=>selected.has(f.featureID)).name+'. Alt + click again to cycle overlapping pieces.');}return;
}
const shared=e.target.closest('[data-shared-edge-id]');if(shared){select(shared.dataset.sharedAreaId);selectedEdge=shared.dataset.sharedEdgeId;shapeEdit=true;settlementMode='boundary';render();details();return;}
if(pending){place(pending.type,p,pending.locationID);return;}
if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked||mode!=='create')return;if(handle.dataset.handle==='resize'&&movementBlocked(f))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};if(handle.dataset.handle==='point'&&E.isArea(f)){const i=Number(handle.dataset.index);joinEnds=[...joinEnds.filter(x=>x!==i),i].slice(-2);drag.snapIndex=T.snapIndex(doc.features.filter(x=>!hiddenLayers.has(x.layer)),scaleForSnap());drag.vertexID=E.areaGeometry(f).vertexRefs?.[i];}}
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){if(!(E.hasBoundary(f)&&settlementMode==='anchor')&&doc.features.some(x=>selected.has(x.featureID)&&movementBlocked(x)))return;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==='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)){snapHint=T.snap(drag.snapIndex,p,10*scaleForSnap(),{areaID:f.featureID,vertexID:drag.vertexID,vertex:snapVertex,edge:snapEdge,disabled:e.altKey});try{doc.features=T.movePoint(doc.features,f.featureID,drag.index,snapHint?.point||p);drag.affected=drag.vertexID?T.context(doc.features).users(drag.vertexID,'vertex'):[f.featureID];}catch(error){status(error.message,true);}}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.affected||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);snapHint=null;if(d.kind!=='pan'){if(d.moved&&snapshot()!==history.at(-1)){changed();render();details();}else{history.pop();future=d.redo;}updateButtons();}});
function cancelDrag(){snapHint=null;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=>{if(e.altKey)return;const id=targetID(e.target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-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:[...(E.isArea(f)?[{label:'Use as join endpoint',icon:'point',run:()=>{const i=Number(point.dataset.index);joinEnds=[...joinEnds.filter(x=>x!==i),i].slice(-2);status('Join endpoint '+(i+1)+' selected.');render();details();}}]:[]),{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=targetID(target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]'));
if(id&&!selected.has(id))select(id);const sharedTarget=target.closest('[data-shared-edge-id]');if(sharedTarget)selectedEdge=sharedTarget.dataset.sharedEdgeId;
const f=doc?.features.find(f=>f.featureID===id),items=doc?.features.filter(f=>selected.has(f.featureID))||[],commands=[];
const add=(label,icon,run,disabled=false)=>commands.push({label,icon,run,disabled});
if(!f){add('Fit map','focus',()=>fit());if(mode==='create')add('Paste','paste',()=>duplicate(clipboard),!clipboard?.length);}
else{
add('Details','details',()=>{$('mapsDetails').scrollIntoView({block:'nearest'});$('mapsDetailContent').querySelector('input,button,a')?.focus();});
if(items.length===1){const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);
if(child)add('Open detailed map','map',()=>navigate(child.mapID));
else if(mode==='create')add('Create detailed map','add',()=>newMap(f));
if(f.locationID)add('Open Location','locations',()=>requestLeave(()=>{location.href='/Locations/Details/'+f.locationID;}));
if(f.floorPlanID)add('Open Floor Plan','floorplans',()=>requestLeave(()=>{location.href=window.PlotDirectorStoryOverlay?.floorPlanURL(f.floorPlanID)||'/FloorPlans/Edit/'+f.floorPlanID;}));
if(mode==='create'){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'){
if(items.length===1&&E.isArea(f)){add('Snap to vertex'+(snapVertex?' (on)':' (off)'),'point',()=>{snapVertex=!snapVertex;details();});add('Snap to edge'+(snapEdge?' (on)':' (off)'),'point',()=>{snapEdge=!snapEdge;details();});add('Join boundaries','auto-arrange',()=>topologyAction('join'),f.isLocked);add('Unjoin boundary','separate-window',()=>topologyAction('unjoin'),f.isLocked||!T.linked(f));}
for(const[key,label]of Object.entries(orderCommands))add(label,'auto-arrange',()=>changeDrawingOrder(key),items.every(f=>f.isLocked));
add('Copy','copy',()=>{clipboard=clone(items);});add('Duplicate','copy',()=>duplicate(items));
add(items.every(f=>f.isLocked)?'Unlock position':'Lock position',items.every(f=>f.isLocked)?'unlock':'lock',()=>safeEdit(()=>{const locked=items.every(f=>f.isLocked);items.forEach(f=>f.isLocked=!locked);}));
add('Mark as unplaced','hide-node',()=>safeEdit(()=>items.filter(f=>!f.isLocked).forEach(f=>f.isPlaced=false)),items.every(f=>f.isLocked));
add('Delete','remove',remove,items.every(f=>f.isLocked));
}
}
return {invoker:target.closest('[data-feature-id],[data-boundary-feature-id],[data-shared-area-id]')||svg,commands};
});
$('mapsDetach').hidden=!window.PlotDirectorWorkspaceBridge;
$('mapsDetach').onclick=()=>{const destination=new URL(url(doc?.map.mapID),location.href);destination.searchParams.set('mode',mode);if(!window.PlotDirectorWorkspaceBridge?.detach(destination.href))status('The separate window could not open. Allow pop-ups for PlotDirector and try again.',true);};
window.addEventListener('pd-workspace-message',e=>{if(e.detail.type==='map-saved'&&e.detail.payload.mapID===doc?.map.mapID&&e.detail.payload.revision>doc.map.revision)status('This map was saved in another window. Reload before editing further. Your current changes remain here.',true);});
document.addEventListener('keydown',e=>{
if(e.defaultPrevented||document.querySelector('.modal.show'))return;
if(e.key==='Escape'&&$('mapsGeographicDialog').open){e.preventDefault();cancelGeographic();return;}
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'&&!e.target.closest('dialog')){e.preventDefault();if(e.target.matches('[data-field]'))e.target.dispatchEvent(new Event('change',{bubbles:true}));save();return;}
if(e.target.closest('dialog')||e.target.matches('input,textarea,select')||e.target.isContentEditable)return;
if(e.key==='Escape'){if(!drag&&!pending&&app.classList.contains('maps-maximised'))return;e.preventDefault();svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'){doc=JSON.parse(history.pop());future=drag.redo;drag=null;}pending=null;selected.clear();shapeEdit=false;svg.classList.remove('placing');render();details();return;}
if(e.target.closest('dialog'))return;
if(mode!=='create'||busy||preview)return;
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();undo(e.shiftKey);}
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 areaHandle=e.target.closest('[data-handle=point]');if(areaHandle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){const f=doc.features.find(f=>selected.has(f.featureID));if(f&&E.isArea(f)){e.preventDefault();const index=Number(areaHandle.dataset.index),p=T.controls(f,doc.features)[index],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;topologyEdit(features=>T.movePoint(features,f.featureID,index,p));return;}}
const handle=e.target.closest('[data-handle]');if(handle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{if(handle.dataset.handle==='endpoint'){const i=Number(handle.dataset.index),p=E.pathPoints(f,doc.features)[i],step=e.shiftKey?20:5;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;Object.assign(f,E.transformEndpoint(f,i,p,doc.features));}else if(handle.dataset.handle==='point'){const g=E.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],[data-shared-area-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(targetID(focused),e.shiftKey);if(focused.dataset.sharedEdgeId){selectedEdge=focused.dataset.sharedEdgeId;shapeEdit=true;settlementMode='boundary';render();details();}}
if(selected.size&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();if(!(selected.size===1&&settlementMode==='anchor')&&doc.features.some(f=>selected.has(f.featureID)&&movementBlocked(f)))return;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)||movementBlocked(f))return;
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);});
function undo(redo=false){if(busy||preview||drag||window.PlotDirectorMapAppearance?.adjusting)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=>{const id=Number(e.target.value);e.target.value=doc?.map.mapID||'';navigate(id);};
$('mapsDefine').onclick=definePlace;$('mapsNew').onclick=()=>newMap();$('mapsWelcomeNew').onclick=()=>newMap();$('mapsNewCancel').onclick=()=>$('mapsNewDialog').close();$('mapsNewForm').onsubmit=createMap;
$('mapsRename').onclick=async()=>{if(!doc)return;const answer=await window.PlotDirectorDialogs.choose({title:'Rename map',message:'Choose a name for this map.',input:{label:'Map name',value:doc.map.name},actions:[{label:'Rename',value:'rename',className:'btn-primary'},{label:'Cancel',value:'cancel'}]});if(answer?.value==='rename'&&answer.input.trim())safeEdit(()=>{doc.map.name=answer.input.trim().slice(0,200);crumbs();});};
$('mapsDuplicate').onclick=async()=>{if(!doc||busy||preview)return;if(dirty){requestLeave(()=>$('mapsDuplicate').click());return;}try{const result=await request('Create',{ProjectID:boot.projectId,Name:doc.map.name+' copy',Kind:doc.map.kind,...(doc.map.parentMapID?{ParentMapID:doc.map.parentMapID}:{})});const d=clone(doc);d.map.mapID=result.id;d.map.name+=' copy';d.map.revision=0;d.features.forEach(f=>f.createLocation=false);await request('Save',d,true);dirty=false;location.href=url(result.id);}catch(error){status(error.message,true);}};
$('mapsDelete').onclick=async()=>{if(!doc||busy||preview)return;const answer=await window.PlotDirectorDialogs.choose({title:'Delete map?',message:`Delete “${doc.map.name}”? Detailed child maps will become top-level maps. Story Locations, Floor Plans and project reference images are kept.`,actions:[{label:'Delete map',value:'delete',className:'btn-danger'},{label:'Cancel',value:'cancel'}]});if(answer?.value!=='delete')return;try{await request('Delete',{projectId:boot.projectId,id:doc.map.mapID,revision:doc.map.revision});dirty=false;location.href=url();}catch(error){status(error.message,true);}};
async function geographicPreview(){
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+'&includeHierarchy=true',{cache:'no-store'});
if(!response.ok||response.redirected)throw Error('Could not load geographical resolutions. Your map is unchanged.');
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,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.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();
// Render the actual proposed canvas inside the dialog. It remains a visual clone, never editable state.
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('data-boundary-feature-id');node.removeAttribute('data-label-feature-id');node.removeAttribute('data-shared-edge-id');node.removeAttribute('data-shared-area-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;}
if(value!==attribute.value)node.setAttribute(attribute.name,value);
}
}
drawing.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);drawing.setAttribute('role','img');drawing.setAttribute('aria-label','Proposed positions, north up');
$('mapsGeographicPreview').replaceChildren(drawing);
$('mapsGeographicApply').disabled=!result.canApply;
$('mapsGeographicRequest').hidden=!result.skipped.some(p=>p.canRequest);
$('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();}
}
$('mapsGeographic').onclick=()=>{if(preview)return;$('mapsGeographicRequestStatus').textContent='';geographicPreview();};
$('mapsGeographicRefresh').onclick=geographicPreview;
$('mapsGeographicRequest').onclick=async()=>{
if(busy||!preview)return;
const ids=[...new Set(preview.skipped.filter(p=>p.canRequest).map(p=>p.locationID))];
if(!ids.length)return;
busy=true;$('mapsGeographicRequest').disabled=true;
try{
const data=new URLSearchParams({projectId:boot.projectId});ids.forEach(id=>data.append('locationIds',id));
const response=await fetch('/Geography/RequestLocations',{method:'POST',headers:{RequestVerificationToken:token},body:data});
const result=await response.json().catch(()=>null);if(!response.ok||response.redirected||!result)throw Error(result?.message||'Could not request these lookups.');
$('mapsGeographicRequestStatus').textContent=result.message;
}catch(error){$('mapsGeographicRequestStatus').textContent=error.message;}finally{busy=false;$('mapsGeographicRequest').disabled=false;await geographicPreview();}
};
function cancelGeographic(){if(busy)return;preview=null;$('mapsGeographicDialog').close();$('mapsGeographicPreview').replaceChildren();render();updateButtons();}
$('mapsGeographicCancel').onclick=cancelGeographic;
$('mapsGeographicDialog').oncancel=e=>{e.preventDefault();cancelGeographic();};
$('mapsGeographicApply').onclick=()=>{
if(!preview?.canApply||busy||mode!=='create')return;
const result=preview;preview=null;checkpoint();doc.features=result.features;
changed('Geographical positions applied. Save to persist; Undo restores previous positions.');
$('mapsGeographicDialog').close();$('mapsGeographicPreview').replaceChildren();render();details();updateButtons();
};
$('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;if(previewArrange())$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange;
function cancelArrange(){preview=null;$('mapsArrangeDialog').close();render();updateButtons();}
$('mapsArrangeCancel').onclick=cancelArrange;$('mapsArrangeDialog').oncancel=e=>{e.preventDefault();cancelArrange();};
$('mapsArrangeApply').onclick=()=>{const result=preview;preview=null;checkpoint();doc.features=result.features;changed(result.warnings.length?'Arrangement applied with observations; you can adjust manually.':'Arrangement applied. You can move any piece afterwards.');$('mapsArrangeDialog').close();render();details();updateButtons();};
$('mapsFit').onclick=()=>fit();$('mapsFitSelection').onclick=()=>fit(doc?.features.filter(f=>selected.has(f.featureID)));$('mapsZoomIn').onclick=()=>zoom(1/1.25);$('mapsZoomOut').onclick=()=>zoom(1.25);
window.PlotDirectorWorkspaceSurface.attach(app,$('mapsMaximise'),{className:'maps-maximised',allowPwa:true,hideChrome:true});
window.addEventListener('beforeunload',e=>{if(dirty||window.PlotDirectorMapAppearance?.adjusting){e.preventDefault();e.returnValue='';}});
const resizeWorkspace=()=>{const top=Math.max(0,app.getBoundingClientRect().top)+'px';if(!app.classList.contains('maps-maximised')&&app.style.getPropertyValue('--maps-shell-top')!==top)app.style.setProperty('--maps-shell-top',top);if(doc)render();};
const workspaceResize=new ResizeObserver(resizeWorkspace);workspaceResize.observe(svg);const chrome=document.querySelector('.pd-application-header');if(chrome)workspaceResize.observe(chrome);
app.dataset.mode=mode;library();locations();crumbs();details();updateButtons();
$('mapsWelcome').hidden=!!doc;svg.style.visibility=doc?'visible':'hidden';$('mapsList').innerHTML=boot.maps.map(m=>`<a href="${url(m.mapID)}">${esc(m.name)} · ${esc(m.kind)}${m.parentMapID?' · detail of '+esc(boot.maps.find(p=>p.mapID===m.parentMapID)?.name||'parent map'):''}</a>`).join('');
if(doc)fit();if(new URLSearchParams(location.search).get('mode')==='explore')document.querySelector('[data-mode=explore]').click();
// Expose semantic operations for browser regression fixtures, never credentials or a bypass.
window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},get mode(){return mode;},get dirty(){return dirty;},get selected(){return [...selected];},setMode(value){document.querySelector(`button[data-mode="${value}"]`)?.click();},refreshDetails:details,clearSelection(){selected.clear();render();details();},focus(id){const f=doc?.features.find(f=>f.featureID===id);if(f){view.x=f.x-view.w/2;view.y=f.y-view.h/2;applyView();}},select,fit,save,requestLeave,edit:safeEdit,render,status,get busy(){return busy;},beginAdjustment(){if(!doc||mode!=='create'||busy||preview)return null;const transaction={before:snapshot(),redo:future.slice(),wasDirty:dirty};checkpoint();updateButtons();return transaction;},commitAdjustment(transaction){if(snapshot()===transaction.before){history.pop();future=transaction.redo;}else changed();render();details();updateButtons();},markAdjustmentChanged(){if(!dirty)changed();},cancelAdjustment(transaction){doc=JSON.parse(transaction.before);dirty=transaction.wasDirty;status(dirty?'Unsaved changes':'Adjustment cancelled');history.pop();future=transaction.redo;render();details();updateButtons();}};
})();