(() => { 'use strict'; const E=window.PlotDirectorMaps, boot=JSON.parse(document.getElementById('mapsBootstrap').textContent); const $=id=>document.getElementById(id),app=$('mapsApp'),svg=$('mapsCanvas'),scene=$('mapsScene'),handles=$('mapsHandles'); const ns='http://www.w3.org/2000/svg',esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const guid=()=>crypto.randomUUID(), clone=E.copy; let doc=boot.document,mode='create',selected=new Set(),pending=null,dirty=false,busy=false,history=[],future=[],preview=null,shapeEdit=false,parentFeature=null; let view={x:-600,y:-400,w:1200,h:800},drag=null,clipboard=null,contextMenu=null; const hiddenLayers=new Set(),nodes=new Map(); const token=document.querySelector('input[name="__RequestVerificationToken"]').value; function status(message,error=false){$('mapsStatus').textContent=message;$('mapsStatus').dataset.error=String(error);} function snapshot(){return JSON.stringify(doc);} function checkpoint(){if(!doc)return;history.push(snapshot());if(history.length>70)history.shift();future=[];} function changed(message='Unsaved changes'){dirty=true;status(message);updateButtons();} function edit(action){if(!doc||mode!=='create'||preview||busy)return;checkpoint();action();changed();render();details();locations();} function updateButtons(){ $('mapsUndo').disabled=!history.length||!!preview; $('mapsRedo').disabled=!future.length||!!preview; $('mapsSave').disabled=!doc||busy||!!preview; } async function request(action,data,json=false){ const response=await fetch('/Maps/'+action,{method:'POST',headers:{'RequestVerificationToken':token,...(json?{'Content-Type':'application/json'}:{})},body:json?JSON.stringify(data):new URLSearchParams(data)}); if(response.redirected)throw new Error('Your session or subscription needs attention. Open your account in another tab; your edits remain here.'); const content=await response.json().catch(()=>null); if(!response.ok)throw new Error(content?.message||`Could not ${action.toLowerCase()} map (${response.status}). Your edits remain here.`); return content; } async function save(){ if(!doc||busy||preview)return false; busy=true;updateButtons();const sent=snapshot();status('Saving…'); try{ const saved=await request('Save',JSON.parse(sent),true); // Editing is disabled while saving; server-created Location links become canonical before further edits. doc=saved;dirty=false; const reconcile=entry=>{const prior=JSON.parse(entry);prior.map.revision=saved.map.revision;for(const f of prior.features){const canonical=saved.features.find(x=>x.featureID===f.featureID);if(canonical?.locationID&&f.createLocation){f.locationID=canonical.locationID;f.createLocation=false;}}return JSON.stringify(prior);}; history=history.map(reconcile);future=future.map(reconcile);boot.document=doc; const known=boot.maps.find(m=>m.mapID===doc.map.mapID);if(known)Object.assign(known,doc.map); for(const f of doc.features)if(f.locationID&&!boot.locations.some(l=>l.locationID===f.locationID))boot.locations.push({locationID:f.locationID,locationName:f.name,projectID:boot.projectId}); $('mapsSelect').selectedOptions[0].textContent=doc.map.name;status('Saved');render();details();locations();return true; }catch(error){status(error.message,true);return false;}finally{busy=false;updateButtons();} } function safeEdit(action){if(!busy)edit(action);} function url(id){return '/Maps?projectId='+boot.projectId+(id?'&id='+id:'');} function navigate(id){if(dirty&&!confirm('Leave this map and discard unsaved changes?'))return;location.href=url(id);} function svgNode(tag,attrs={}){const node=document.createElementNS(ns,tag);for(const[k,v]of Object.entries(attrs))node.setAttribute(k,v);return node;} function applyView(){svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);$('mapsZoom').textContent=Math.round(1200/view.w*100)+'%';render();} function world(event){const p=new DOMPoint(event.clientX,event.clientY).matrixTransform(svg.getScreenCTM().inverse());return [p.x,p.y];} function fit(items=doc?.features||[]){if(!items.length){view={x:-600,y:-400,w:1200,h:800};applyView();return;} let left=Infinity,top=Infinity,right=-Infinity,bottom=-Infinity; for(const f of items){let pts=f.geometryClass==='Path'?E.pathPoints(f,doc.features):f.geometryClass==='Area'?(E.geometry(f).points||[[-.5,-.5],[.5,.5]]).map(p=>E.localToWorld(f,p)):[[f.x-f.width/2,f.y-f.height/2],[f.x+f.width/2,f.y+f.height/2]];for(const p of pts){left=Math.min(left,p[0]);right=Math.max(right,p[0]);top=Math.min(top,p[1]);bottom=Math.max(bottom,p[1]);}} let w=Math.max(350,right-left+180),h=Math.max(250,bottom-top+180),ratio=svg.clientWidth/Math.max(1,svg.clientHeight);if(w/h!hiddenLayers.has(f.layer)); const alive=new Set(visible.map(f=>f.featureID)),scale=view.w/Math.max(svg.clientWidth,1),labelBoxes=[]; for(const[id,node]of nodes)if(!alive.has(id)){node.remove();nodes.delete(id);} const childIDs=new Set(boot.maps.filter(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID).map(m=>m.parentFeatureID)); const ordered=[...visible].sort((a,b)=>a.zOrder-b.zOrder||a.featureID.localeCompare(b.featureID)); for(const f of ordered){ if(affected&&!affected.has(f.featureID))continue; let g=nodes.get(f.featureID);if(!g){g=svgNode('g',{'data-feature-id':f.featureID,tabindex:'0',role:'button'});nodes.set(f.featureID,g);scene.append(g);} const isSelected=selected.has(f.featureID);g.setAttribute('class',`maps-feature${isSelected?' is-selected':''}${f.isProvisional?' is-provisional':''}`);g.setAttribute('aria-label',`${f.name}, ${f.type}${f.isProvisional?', planning':''}${childIDs.has(f.featureID)?', detailed map available':''}`);g.setAttribute('aria-pressed',String(isSelected)); // Reconcile individual keyed pieces; the shell, canvas, focus and sidebars remain stable. let markup=''; if(f.geometryClass==='Marker'){ const symbol=E.library.find(a=>a.type===f.type)?.symbol||'◆',size=Math.min(46,Math.max(26,f.width/Math.max(.7,scale)))*scale; markup=`${esc(symbol)}`; }else if(f.geometryClass==='Path'){ const water=['River','Stream','Canal'].includes(f.type),rail=f.type==='Railway',road=['Road','Major road'].includes(f.type); const d=E.curve(E.pathPoints(f,preview?.features||doc.features)),color=water?'#4c92ae':rail?'#5b635d':f.type==='Sea route'?'#557f94':'#99764b'; const width=f.type==='Major road'?8:road?5:f.type==='Stream'?3:water?7:3; markup=``; if(rail)markup+=``; markup+=``; }else{ const fills={'Forest':'url(#map-forest)','Mountain Range':'url(#map-mountains)','Hills':'url(#map-hills)','Marsh':'url(#map-marsh)','Farmland':'url(#map-farmland)','Lake':'#91c0d0','Desert':'#e9d499','Plains':'#d8dcb1'}; const overlay=f.layer==='Regions',points=E.coastline(f).map(p=>[p[0]*f.width,p[1]*f.height]); markup=``; } if(f.showLabel&&!hiddenLayers.has('Labels')&&(scale<4||isSelected||['Capital','City'].includes(f.type))){ let x=f.x+f.labelX,y=f.y+f.labelY+(f.geometryClass==='Marker'?34*scale:0),text=f.name+(f.isProvisional?' ◇':'')+(childIDs.has(f.featureID)?' ↳':''),width=text.length*7*scale; if(!f.labelX&&!f.labelY)for(let attempt=0;attempt<5;attempt++){if(!labelBoxes.some(b=>Math.abs(b.x-x)<(b.w+width)/2&&Math.abs(b.y-y)<18*scale))break;y+=19*scale;} labelBoxes.push({x,y,w:width});markup+=`${esc(text)}`; } if(g.innerHTML!==markup)g.innerHTML=markup; // append only when ordering changes, preserving DOM focus on normal updates } if(!affected)ordered.forEach((f,i)=>{const node=nodes.get(f.featureID);if(scene.children[i]!==node)scene.insertBefore(node,scene.children[i]||null);}); renderHandles(scale); } function renderHandles(scale){handles.replaceChildren();if(mode!=='create'||preview||selected.size!==1)return;const f=doc.features.find(f=>selected.has(f.featureID));if(!f||f.isLocked)return; const add=(p,type,index)=>handles.append(svgNode('circle',{cx:p[0],cy:p[1],r:6*scale,class:'maps-handle','data-handle':type,'data-index':index??'',tabindex:'0','aria-label':type==='point'?'Move shape point':'Resize selected feature'})); if(shapeEdit&&f.geometryClass!=='Marker'){ const pts=E.geometry(f).points||[];pts.forEach((p,i)=>add(E.localToWorld(f,p),'point',i)); }else if(f.geometryClass!=='Marker')add(E.localToWorld(f,[.5,.5]),'resize'); } function select(id,extend=false){if(!extend)selected.clear();if(extend&&selected.has(id))selected.delete(id);else selected.add(id);shapeEdit=false;render();details();} function place(type,point,locationID=null){if(!doc||busy||mode!=='create')return;safeEdit(()=>{const f=E.makeFeature(type,point[0],point[1],guid());if(locationID){const l=boot.locations.find(l=>l.locationID===locationID);f.locationID=locationID;f.name=l.locationName;f.isProvisional=false;}doc.features.push(f);selected=new Set([f.featureID]);});pending=null;svg.classList.remove('placing');$('mapName')?.focus();} function library(){const categories=[...new Set(E.library.map(a=>a.category))];$('mapsCategory').innerHTML=''+categories.map(c=>``).join(''); for(const layer of ['Terrain','Water','Vegetation','Places','Routes','Regions','Labels']){const label=document.createElement('label');label.innerHTML=` ${layer}`;$('mapsLayers').append(label);}assets();} function assets(){const q=$('mapsAssetSearch').value.toLowerCase(),category=$('mapsCategory').value;$('mapsAssets').innerHTML=E.library.filter(a=>(!q||a.type.toLowerCase().includes(q))&&(!category||a.category===category)).map(a=>``).join('');} function locations(){if(!doc){$('mapsLocations').textContent='Open a map to place story Locations.';return;}const q=$('mapsLocationSearch').value.toLowerCase(),placed=new Set(doc.features.map(f=>f.locationID));$('mapsLocations').innerHTML=boot.locations.filter(l=>!l.isArchived&&!placed.has(l.locationID)&&l.locationName.toLowerCase().includes(q)).map(l=>``).join('')||'

No unplaced Locations match.

';} function crumbs(){const list=[];let current=doc?.map,seen=new Set();while(current&&!seen.has(current.mapID)){seen.add(current.mapID);list.unshift(current);current=boot.maps.find(m=>m.mapID===current.parentMapID);} $('mapsBreadcrumbs').innerHTML=`All maps`+list.map(m=>`${esc(m.name)}`).join('');} function option(value,label,selectedValue){return ``;} function field(label,key,value,type='text',attrs=''){return ``;} function check(label,key,value){return ``;} function details(){ const content=$('mapsDetailContent'); if(!doc){content.textContent='Create or open a map to begin.';return;} const search=''; const f=doc.features.find(f=>selected.has(f.featureID)); if(!f){content.innerHTML=search+`

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

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

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

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

${selected.size} pieces selected.

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

${esc(f.name)}

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

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

${esc(f.notes)}

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

A map feature can exist without a story Location.

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

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

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

Endpoints stay attached as places move.

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

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

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

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

Open Floor Plan

`; html+=`
Spatial relationships

Directions and distances describe intent; placement remains yours.

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

Spatial relationship

Known distance / typical travel time
`;app.append(dialog);dialog.showModal();dialog.querySelector('[data-cancel]').onclick=()=>dialog.close();dialog.onclose=()=>dialog.remove();dialog.querySelector('form').onsubmit=e=>{e.preventDefault();const values=Object.fromEntries(new FormData(e.target));if(values.sourceID===values.targetID){status('Choose two different places.',true);return;}safeEdit(()=>{Object.assign(r,values,{direction:values.direction||null,relativeDistance:values.relativeDistance||null,measuredDistance:values.measuredDistance===''?null:Number(values.measuredDistance)});if(!old)doc.relationships.push(r);});dialog.close();};} function remove(){safeEdit(()=>{const ids=new Set([...selected].filter(id=>!doc.features.find(f=>f.featureID===id)?.isLocked));doc.features=doc.features.filter(f=>!ids.has(f.featureID));doc.relationships=doc.relationships.filter(r=>!ids.has(r.sourceID)&&!ids.has(r.targetID));for(const f of doc.features){if(ids.has(f.startFeatureID))f.startFeatureID=null;if(ids.has(f.endFeatureID))f.endFeatureID=null;}selected.clear();});} function duplicate(items){safeEdit(()=>{const mapping=new Map(items.map(f=>[f.featureID,guid()]));const copies=clone(items).map(f=>({...f,featureID:mapping.get(f.featureID),name:f.name+' copy',x:f.x+50,y:f.y+50,isLocked:false,createLocation:false,startFeatureID:mapping.get(f.startFeatureID)||f.startFeatureID,endFeatureID:mapping.get(f.endFeatureID)||f.endFeatureID}));doc.features.push(...copies);selected=new Set(copies.map(f=>f.featureID));});} function action(name){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f)return; if(name==='remove')remove();if(name==='duplicate')duplicate(doc.features.filter(f=>selected.has(f.featureID))); if(name==='relationship')relationEditor();if(name==='child')newMap(f);if(name==='shape'){shapeEdit=!shapeEdit;render();details();} if(name==='unplace')safeEdit(()=>{f.isPlaced=false;}); if(name==='bend')safeEdit(()=>{const g=E.geometry(f),pts=g.points||[];if(pts.length>=64)return;let index=0,longest=0;for(let i=0;ilongest){longest=len;index=i;}}const next=pts[(index+1)%pts.length];pts.splice(index+1,0,[(pts[index][0]+next[0])/2,(pts[index][1]+next[1])/2]);g.points=pts;f.geometryJson=JSON.stringify(g);shapeEdit=true;}); } 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; const submit=e.target.querySelector('[type=submit]');submit.disabled=true; try{const result=await request('Create',data);let features=[];const add=(type,x,y,w,h)=>{const f=E.makeFeature(type,x,y,guid());f.width=w;f.height=h;features.push(f);}; if(['land','island','inland','local'].includes(values.Starter))add(values.Starter==='island'?'Island':'Land Mass',0,0,values.Starter==='local'?1000:850,650); if(values.Starter==='two'){add('Land Mass',-290,0,480,600);add('Land Mass',300,40,430,570);} if(values.Starter==='islands'){add('Island',-240,-100,370,300);add('Island',200,90,300,380);add('Island',-70,230,200,170);} if(features.length){const created={map:{mapID:result.id,projectID:boot.projectId,name:values.Name,kind:values.Kind,revision:0},features,relationships:[]};await request('Save',created,true);}dirty=false;location.href=url(result.id); }catch(error){status(error.message,true);}finally{submit.disabled=false;}} function previewArrange(){if(!doc||mode!=='create')return;preview=E.arrange(doc.features,doc.relationships,$('mapsOnlyNew').checked);$('mapsArrangeWarnings').textContent=preview.warnings.length?'Some intentions cannot all be represented exactly: '+preview.warnings.slice(0,5).join('; ')+'. You can still apply and adjust manually.':'Preview ready. Locked pieces and established anchors stay in place.';render();updateButtons();} // Delegated interaction continues to work after the PWA shell moves controls into its ribbon. document.addEventListener('click',e=>{ const modeButton=e.target.closest('button[data-mode]');if(modeButton){if(preview)return;mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();return;} const asset=e.target.closest('[data-asset]'),loc=e.target.closest('[data-location]');if(asset||loc){pending={type:asset?.dataset.asset||'Settlement',locationID:loc?Number(loc.dataset.location):null};svg.classList.add('placing');status('Click the map to place '+(asset?.dataset.asset||'this Location')+'. Escape cancels.');return;} const actionButton=e.target.closest('[data-action]');if(actionButton)action(actionButton.dataset.action); const rel=e.target.closest('[data-edit-rel]');if(rel)relationEditor(rel.dataset.editRel); const removeRel=e.target.closest('[data-remove-rel]');if(removeRel)safeEdit(()=>doc.relationships=doc.relationships.filter(r=>r.relationshipID!==removeRel.dataset.removeRel)); const result=e.target.closest('[data-search-feature]');if(result){const f=doc.features.find(f=>f.featureID===result.dataset.searchFeature);select(f.featureID);fit([f]);$('mapsSearchResults').replaceChildren();} if(contextMenu&&!contextMenu.contains(e.target)){contextMenu.remove();contextMenu=null;} }); document.addEventListener('change',e=>{ if(e.target.matches('[data-field]')){const f=doc?.features.find(f=>selected.has(f.featureID));if(!f||busy)return;const key=e.target.dataset.field;let value=e.target.type==='checkbox'?e.target.checked:e.target.type==='number'?Number(e.target.value):e.target.value;if(['locationID','floorPlanID'].includes(key))value=value?Number(value):null;if(['startFeatureID','endFeatureID'].includes(key))value=value||null;if(['width','height'].includes(key)&&(!Number.isFinite(value)||value<1))return;safeEdit(()=>{f[key]=value;if(key==='createLocation'&&value)f.isProvisional=false;if(key==='isProvisional'&&value)f.createLocation=false;if(key==='locationID')f.createLocation=false;});} if(e.target.matches('[data-geometry]')){const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{const g=E.geometry(f);g[e.target.dataset.geometry]=e.target.value;f.geometryJson=JSON.stringify(g);});} if(e.target.matches('[data-layer]')){if(e.target.checked)hiddenLayers.delete(e.target.dataset.layer);else hiddenLayers.add(e.target.dataset.layer);render();} }); document.addEventListener('input',e=>{if(e.target.id==='mapsFind'&&doc){const q=e.target.value.toLowerCase();$('mapsSearchResults').innerHTML=q?doc.features.filter(f=>(f.name+' '+(boot.locations.find(l=>l.locationID===f.locationID)?.locationName||'')).toLowerCase().includes(q)).slice(0,60).map(f=>``).join(''):'';}}); $('mapsAssetSearch').oninput=assets;$('mapsCategory').onchange=assets;$('mapsLocationSearch').oninput=locations; app.addEventListener('dragstart',e=>{const target=e.target.closest('[data-asset],[data-location]');if(!target)return;e.dataTransfer.setData('application/plotdirector-map',JSON.stringify({type:target.dataset.asset||'Settlement',locationID:Number(target.dataset.location)||null}));e.dataTransfer.effectAllowed='copy';}); svg.addEventListener('dragover',e=>e.preventDefault());svg.addEventListener('drop',e=>{e.preventDefault();try{const data=JSON.parse(e.dataTransfer.getData('application/plotdirector-map'));place(data.type,world(e),data.locationID);}catch{status('Choose a map piece from the library.');}}); svg.addEventListener('pointerdown',e=>{ if(e.button!==0||!doc||busy||preview)return;contextMenu?.remove();const p=world(e),target=e.target.closest('[data-feature-id]'),handle=e.target.closest('[data-handle]'); if(pending){place(pending.type,p,pending.locationID);return;} if(handle){const f=doc.features.find(f=>selected.has(f.featureID));if(!f||mode!=='create')return;checkpoint();drag={kind:handle.dataset.handle,id:f.featureID,index:Number(handle.dataset.index),start:p,original:clone(f),moved:false};} else if(target){const id=target.dataset.featureId;if(!selected.has(id)||e.shiftKey)select(id,e.shiftKey);const f=doc.features.find(f=>f.featureID===id);if(mode==='create'&&!f.isLocked){checkpoint();drag={kind:'move',start:p,originals:clone(doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked)),moved:false};}} else{if(!e.shiftKey){selected.clear();shapeEdit=false;render();details();}drag={kind:'pan',start:p,original:{...view},client:[e.clientX,e.clientY],matrix:svg.getScreenCTM().inverse(),moved:false};} if(drag)svg.setPointerCapture(e.pointerId); }); svg.addEventListener('pointermove',e=>{if(!drag)return;const p=world(e),dx=p[0]-drag.start[0],dy=p[1]-drag.start[1];if(Math.abs(dx)+Math.abs(dy)>1)drag.moved=true; if(drag.kind==='pan'){view.x=drag.original.x-(e.clientX-drag.client[0])*drag.matrix.a;view.y=drag.original.y-(e.clientY-drag.client[1])*drag.matrix.d;svg.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);return;} if(drag.kind==='move'){for(const o of drag.originals){const f=doc.features.find(f=>f.featureID===o.featureID);f.x=o.x+dx;f.y=o.y+dy;f.isPlaced=true;}} else{const f=doc.features.find(f=>f.featureID===drag.id),o=drag.original,a=-o.rotation*Math.PI/180,lx=(p[0]-o.x)*Math.cos(a)-(p[1]-o.y)*Math.sin(a),ly=(p[0]-o.x)*Math.sin(a)+(p[1]-o.y)*Math.cos(a);if(drag.kind==='resize'){f.width=Math.max(20,Math.abs(lx)*2);f.height=Math.max(20,Math.abs(ly)*2);}else{const g=E.geometry(f);g.points[drag.index]=[Math.max(-5,Math.min(5,lx/o.width)),Math.max(-5,Math.min(5,ly/o.height))];f.geometryJson=JSON.stringify(g);}} if(!drag.frame)drag.frame=requestAnimationFrame(()=>{if(!drag)return;drag.frame=null;const moved=new Set(drag.originals?.map(f=>f.featureID)||[drag.id]);for(const f of doc.features)if(moved.has(f.startFeatureID)||moved.has(f.endFeatureID))moved.add(f.featureID);render(moved);}); }); svg.addEventListener('pointerup',e=>{if(!drag)return;const d=drag;drag=null;if(d.frame)cancelAnimationFrame(d.frame);if(svg.hasPointerCapture(e.pointerId))svg.releasePointerCapture(e.pointerId);if(d.kind!=='pan'){if(d.moved){changed();render();details();}else history.pop();updateButtons();}}); svg.addEventListener('pointercancel',()=>{if(drag&&drag.kind!=='pan'&&history.length){doc=JSON.parse(history.pop());render();details();}drag=null;}); svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(!id)return;const child=boot.maps.find(m=>m.parentMapID===doc.map.mapID&&m.parentFeatureID===id);if(child)navigate(child.mapID);else{const f=doc.features.find(f=>f.featureID===id);if(f.floorPlanID&&(!dirty||confirm('Leave and discard unsaved changes?')))location.href='/FloorPlans/Edit/'+f.floorPlanID;}}); svg.addEventListener('wheel',e=>{e.preventDefault();zoom(e.deltaY>0?1.12:1/1.12,world(e));},{passive:false}); svg.addEventListener('contextmenu',e=>{e.preventDefault();const id=e.target.closest('[data-feature-id]')?.dataset.featureId;if(!id||mode!=='create')return;select(id);contextMenu?.remove();contextMenu=document.createElement('div');contextMenu.className='maps-context-menu';contextMenu.style.left=Math.min(e.clientX,window.innerWidth-180)+'px';contextMenu.style.top=Math.min(e.clientY,window.innerHeight-170)+'px';contextMenu.innerHTML='';app.append(contextMenu);}); document.addEventListener('keydown',e=>{ if((e.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.matches('input,textarea,select')||e.target.isContentEditable)return; if(e.key==='Escape'){if(drag&&drag.kind!=='pan'){doc=JSON.parse(history.pop());drag=null;}pending=null;selected.clear();shapeEdit=false;contextMenu?.remove();svg.classList.remove('placing');render();details();return;} if(e.target.closest('dialog'))return; if(mode!=='create'||busy||preview)return; if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();undo(e.shiftKey);} if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='y'){e.preventDefault();undo(true);} if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='c'){clipboard=clone(doc.features.filter(f=>selected.has(f.featureID)));} if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='v'&&clipboard?.length){e.preventDefault();duplicate(clipboard);} if(e.key==='Delete'||e.key==='Backspace'){e.preventDefault();remove();} const handle=e.target.closest('[data-handle]');if(handle&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const f=doc.features.find(f=>selected.has(f.featureID));safeEdit(()=>{if(handle.dataset.handle==='point'){const g=E.geometry(f),p=g.points[Number(handle.dataset.index)],step=e.shiftKey?.05:.01;p[0]+=e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0;p[1]+=e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0;f.geometryJson=JSON.stringify(g);}else{f.width=Math.max(20,f.width+(e.key==='ArrowRight'?10:e.key==='ArrowLeft'?-10:0));f.height=Math.max(20,f.height+(e.key==='ArrowDown'?10:e.key==='ArrowUp'?-10:0));}});return;} const focused=e.target.closest('[data-feature-id]');if(focused&&(e.key==='Enter'||e.key===' ')){e.preventDefault();select(focused.dataset.featureId,e.shiftKey);} if(selected.size&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)){e.preventDefault();const step=e.shiftKey?20:5;safeEdit(()=>doc.features.filter(f=>selected.has(f.featureID)&&!f.isLocked).forEach(f=>{f.x+=(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0);f.y+=(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0);}));} }); function undo(redo=false){if(busy||preview)return;const from=redo?future:history,to=redo?history:future;if(!from.length)return;to.push(snapshot());doc=JSON.parse(from.pop());selected.clear();changed();render();details();locations();} $('mapsSelectorForm').onsubmit=e=>e.preventDefault();$('mapsSearchForm').onsubmit=e=>e.preventDefault(); $('mapsSave').onclick=save;$('mapsUndo').onclick=()=>undo();$('mapsRedo').onclick=()=>undo(true);$('mapsSelect').onchange=e=>navigate(Number(e.target.value)); $('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);}}; $('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;previewArrange();$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange; function cancelArrange(){preview=null;$('mapsArrangeDialog').close();render();updateButtons();} $('mapsArrangeCancel').onclick=cancelArrange;$('mapsArrangeDialog').oncancel=e=>{e.preventDefault();cancelArrange();}; $('mapsArrangeApply').onclick=()=>{const result=preview;preview=null;checkpoint();doc.features=result.features;changed(result.warnings.length?'Arrangement applied with observations; you can adjust manually.':'Arrangement applied. You can move any piece afterwards.');$('mapsArrangeDialog').close();render();details();updateButtons();}; $('mapsFit').onclick=()=>fit();$('mapsFitSelection').onclick=()=>fit(doc?.features.filter(f=>selected.has(f.featureID)));$('mapsZoomIn').onclick=()=>zoom(1/1.25);$('mapsZoomOut').onclick=()=>zoom(1.25); $('mapsMaximise').onclick=e=>{const active=app.classList.toggle('maps-maximised');e.currentTarget.setAttribute('aria-pressed',String(active));e.currentTarget.textContent=active?'Restore workspace':'Maximise workspace';}; window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}}); new ResizeObserver(()=>{const top=app.getBoundingClientRect().top;if(!app.classList.contains('maps-maximised'))app.style.setProperty('--maps-shell-top',Math.max(0,top)+'px');if(doc)render();}).observe(svg); const syncDisplayMode=()=>{$('mapsMaximise').hidden=!!window.PlotDirectorPwa?.standalone;};syncDisplayMode();window.matchMedia('(display-mode: standalone)').addEventListener('change',syncDisplayMode); app.dataset.mode=mode;library();locations();crumbs();details();updateButtons(); $('mapsWelcome').hidden=!!doc;svg.style.visibility=doc?'visible':'hidden';$('mapsList').innerHTML=boot.maps.map(m=>`${esc(m.name)} · ${esc(m.kind)}${m.parentMapID?' · detail of '+esc(boot.maps.find(p=>p.mapID===m.parentMapID)?.name||'parent map'):''}`).join(''); if(doc)fit(); // Expose semantic operations for browser regression fixtures, never credentials or a bypass. window.PlotDirectorMapWorkspace={get document(){return doc;},get view(){return view;},select,fit,save}; })();