(() => { 'use strict'; const W=window.PlotDirectorMapWorkspace,E=window.PlotDirectorMapAppearanceEngine,G=window.PlotDirectorMaps,$=id=>document.getElementById(id); if(!W||!E||!$('mapsAppearance'))return; const boot=JSON.parse($('mapsBootstrap').textContent),svg=$('mapsCanvas'),ns='http://www.w3.org/2000/svg',esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const images=boot.referenceImages||[],token=document.querySelector('input[name=__RequestVerificationToken]').value; let selected=false,inspecting=false,adjusting=false,transaction=null,drag=null,uploading=false,paletteKey='',savedID=E.reference(W.document?.map)?.imageID||null; let layer=$('mapsReferenceLayer');if(!layer){layer=document.createElementNS(ns,'g');layer.id='mapsReferenceLayer';svg.insertBefore(layer,$('mapsScene'));} const image=document.createElementNS(ns,'image'),outline=document.createElementNS(ns,'rect'),handles=document.createElementNS(ns,'g');image.id='mapsReferenceImage';image.dataset.referenceImage='true';image.setAttribute('tabindex','0');image.setAttribute('role','button');image.setAttribute('aria-label','Reference image. Select to inspect its placement.');outline.setAttribute('class','maps-reference-outline');outline.setAttribute('fill','none');outline.setAttribute('pointer-events','none');layer.append(image,outline);svg.append(handles); const ref=()=>E.reference(W.document?.map),metadata=id=>images.find(i=>i.imageID===id),world=e=>{const p=new DOMPoint(e.clientX,e.clientY).matrixTransform(svg.getScreenCTM().inverse());return [p.x,p.y];}; function attr(node,key,value){if(node.getAttribute(key)!==String(value))node.setAttribute(key,value);} function putReference(value){W.document.map.referenceJson=JSON.stringify(value||{});if(adjusting)W.markAdjustmentChanged();} function begin(){if(adjusting)return true;adjusting=true;transaction=W.beginAdjustment();if(!transaction){adjusting=false;return false;}return true;} function finish(cancel=false){if(!adjusting)return;const tx=transaction;adjusting=false;transaction=null;drag=null;const active=document.activeElement,field=active?.dataset.referenceField,kind=active?.getAttribute('type'),colour=active?.dataset.mapColour,scale=active?.hasAttribute('data-reference-scale');if(cancel)W.cancelAdjustment(tx);else W.commitAdjustment(tx);if(colour)$('mapsDetailContent').querySelector(`[data-map-colour="${colour}"]`)?.focus({preventScroll:true});else if(scale)$('mapsDetailContent').querySelector('[data-reference-scale]')?.focus({preventScroll:true});else if(field)$('mapsDetailContent').querySelector(`[data-reference-field="${field}"][type="${kind}"]`)?.focus({preventScroll:true});} function render(){ if(!W.document){layer.setAttribute('display','none');handles.replaceChildren();return;} const p=E.palette(W.document.map),key=JSON.stringify(p);if(key!==paletteKey){paletteKey=key;const values={'canvas-bg':p.backgroundColor,land:p.landColor,'map-ink':p.ink,'label-halo':p.halo,'marker-bg':p.marker,selection:p.selection,'water-line':p.water,'route-line':p.route,'region-line':p.region,'terrain-line':p.dark?'#8da18c':'#91a087','forest-fill':p.dark?'#334c3b':'#c4d4af','mountains-fill':p.dark?'#53584c':'#d3cebd','marsh-fill':p.dark?'#3b5350':'#c2d3bc'};for(const[k,v]of Object.entries(values))svg.style.setProperty('--maps-'+k,v);window.dispatchEvent(new CustomEvent('pd-map-palette',{detail:p}));} const r=ref();attr(layer,'display',r?.isVisible?'inline':'none');handles.replaceChildren();if(!r)return; const href=`/Maps/ReferenceImage?projectId=${boot.projectId}&imageId=${encodeURIComponent(r.imageID)}`;attr(image,'href',href);attr(image,'x',-r.width/2);attr(image,'y',-r.height/2);attr(image,'width',r.width);attr(image,'height',r.height);attr(layer,'transform',`translate(${r.x} ${r.y}) rotate(${r.rotation})`);attr(image,'opacity',r.opacity);attr(image,'class',r.isLocked?'maps-reference-image is-locked':'maps-reference-image'); attr(outline,'x',-r.width/2);attr(outline,'y',-r.height/2);attr(outline,'width',r.width);attr(outline,'height',r.height);attr(outline,'visibility',selected&&W.mode==='create'?'visible':'hidden'); if(!selected||r.isLocked||!r.isVisible||W.mode!=='create')return; const scale=W.view.w/Math.max(svg.clientWidth,1),add=(point,kind,label)=>{const node=document.createElementNS(ns,'circle');for(const[k,v]of Object.entries({cx:point[0],cy:point[1],r:12*scale,tabindex:0,role:'button','aria-label':label,'data-reference-handle':kind,class:'maps-handle maps-reference-handle'}))node.setAttribute(k,v);handles.append(node);}; add([r.x,r.y],'move','Move reference image');add(G.localToWorld(r,[.5,.5]),'scale','Resize reference image');add(G.localToWorld(r,[0,-.5-35*scale/r.height]),'rotate','Rotate reference image'); } function field(label,key,value,type='number',attrs=''){const display=type==='number'?Math.round(value*10)/10:value;return ``;} function showDetails(){ if(!W.document||(!selected&&!inspecting))return false;const a=E.appearance(W.document.map),r=ref(),current=r&&metadata(r.imageID),editable=W.mode==='create',disabled=editable?'':'disabled'; let html=`

Map appearance

The application theme surrounds your map. These choices belong to the map itself.

`; if(a.preset==='custom')html+=`
`; html+=`
Reference image

A visual reference to work over. Nothing in the image becomes structured geography or travel evidence.

`; if(editable)html+=`

PNG, JPEG or WebP · up to 10 MB and 16 megapixels. Uploaded images are kept in this project's reference library.

`; if(r){html+=`

${esc(current?.originalFileName||'Reference image')}

`; if(editable)html+=`
${field('Across','x',r.x,'number',r.isLocked?'disabled':'')}${field('Down','y',r.y,'number',r.isLocked?'disabled':'')}${field('Width','width',r.width,'number','min="10" '+(r.isLocked?'disabled':''))}${field('Height','height',r.height,'number','min="10" '+(r.isLocked?'disabled':''))}
`; }else html+='

No reference image on this map.

'; html+='
'; if(editable&&images.length)html+=`
Project reference images

One image per map. Project images can be reused without copying them. Removing an image from a map keeps it here.

`; $('mapsDetailContent').innerHTML=html;libraryControls();return true; } function libraryControls(){const select=$('mapReferenceLibrary');if(!select)return;const item=metadata(select.value),current=ref(),remove=$('mapsDetailContent').querySelector('[data-reference-action=delete]'),use=$('mapsDetailContent').querySelector('[data-reference-action=use]');if(remove)remove.disabled=!item||current?.imageID===item.imageID||item.useCount>0||W.busy;if(use)use.disabled=!item||current?.imageID===item.imageID||W.busy;} function inspect(reference=false){selected=reference;inspecting=!reference;W.clearSelection();render();showDetails();if(reference)image.focus({preventScroll:true});} async function upload(file){if(!file||uploading||W.mode!=='create')return;uploading=true;if($('mapReferenceUpload'))$('mapReferenceUpload').disabled=true;W.status('Uploading reference image…');const body=new FormData();body.set('projectId',boot.projectId);body.set('referenceImage',file);try{const response=await fetch('/Maps/UploadReference',{method:'POST',headers:{RequestVerificationToken:token},body}),result=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(result?.message||'The image could not be uploaded. Check access and storage, then try again.');if(!result?.imageID||!Number.isFinite(result.width)||!Number.isFinite(result.height)||result.width<1||result.height<1)throw Error('The upload could not be verified. Your previous reference and map edits remain here.');if(!images.some(i=>i.imageID===result.imageID))images.push(result);let attached=false;if(W.mode==='create'&&(selected||inspecting)){const previous=ref();W.edit(()=>putReference(previous?{...previous,imageID:result.imageID}:E.fit(result,W.view)));selected=true;inspecting=false;attached=true;render();image.focus({preventScroll:true});}W.status(attached?'Image added to project references. Save the map to keep its placement.':'Image added to project references. Choose it from Map appearance to place it.');}catch(error){W.status(error.message,true);}finally{uploading=false;showDetails();}} async function action(kind){if(kind==='select'){inspect(true);return;}if(kind==='close'){selected=false;inspecting=false;W.refreshDetails();return;}const r=ref(),item=metadata($('mapReferenceLibrary')?.value);if(W.mode!=='create'||W.busy)return; if(kind==='delete'&&item){if(r?.imageID===item.imageID){W.status('Remove this image from the map and save before deleting it from the project.',true);return;}const answer=await window.PlotDirectorDialogs.choose({title:'Delete unused reference image?',message:'Permanently remove this unused image from project references? Deleted images cannot be restored with Undo. Saved maps using it prevent deletion.',actions:[{label:'Delete image',value:'delete',className:'btn-danger',run:async()=>{try{const response=await fetch('/Maps/DeleteUnusedReference',{method:'POST',headers:{RequestVerificationToken:token,'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({projectId:boot.projectId,imageId:item.imageID})});const result=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(result?.message||'The reference image could not be deleted.');images.splice(images.indexOf(item),1);return true;}catch(error){W.status(error.message,true);throw error;}}},{label:'Cancel',value:'cancel'}]});if(answer?.value==='delete')showDetails();return;} if(kind==='use'&&item){W.edit(()=>putReference(r?{...r,imageID:item.imageID}:E.fit(item,W.view)));selected=true;inspecting=false;render();showDetails();return;} if(!r)return;if(r.isLocked&&['fit','reset'].includes(kind))return;W.edit(()=>{if(kind==='remove')putReference(null);else if(kind==='fit')putReference({...E.fit(metadata(r.imageID)||{...r},W.view,r.rotation),imageID:r.imageID,opacity:r.opacity,isVisible:r.isVisible,isLocked:r.isLocked});else if(kind==='reset')putReference({...r,...E.fit(metadata(r.imageID)||{...r},W.view),imageID:r.imageID,opacity:r.opacity,isVisible:r.isVisible,isLocked:r.isLocked});else if(kind==='lock')putReference({...r,isLocked:!r.isLocked});}); } function updateField(input){const r=ref();if(!r||W.mode!=='create'||W.busy)return;if(r.isLocked&&!['opacity','isVisible','isLocked'].includes(input.dataset.referenceField))return;if(input.type==='number'&&input.value===input.dataset.initialDisplay&&!adjusting)return;const value=Number(input.value);if(!Number.isFinite(value)||Math.abs(value)>100000)return;if(!begin())return;const key=input.dataset.referenceField;let next={...r,[key]:key==='rotation'?E.angle(value):['width','height'].includes(key)?Math.max(10,value):key==='opacity'?Math.max(0,Math.min(1,value)):value};putReference(next);W.render();if($('mapReferenceOpacityValue'))$('mapReferenceOpacityValue').textContent=Math.round(next.opacity*100)+'%';} image.addEventListener('keydown',e=>{if(['Enter',' '].includes(e.key)){e.preventDefault();e.stopPropagation();inspect(true);}}); $('mapsAppearance').disabled=!W.document; $('mapsAppearance').onclick=()=>inspect();image.onerror=()=>W.status('The reference image is unavailable. Your structured map and local edits remain here.',true); document.addEventListener('click',e=>{const button=e.target.closest('[data-reference-action]');if(button)action(button.dataset.referenceAction);}); document.addEventListener('input',e=>{if(e.target.matches('[data-reference-field]'))updateField(e.target);if(e.target.matches('[data-reference-scale]')){const r=ref(),m=r&&metadata(r.imageID);if(r&&!r.isLocked&&m&&begin()){putReference({...r,width:m.width*Number(e.target.value)/100,height:m.height*Number(e.target.value)/100});W.render();}}if(e.target.matches('[data-map-colour]')&&W.mode==='create'&&begin()){const a=E.appearance(W.document.map);a[e.target.dataset.mapColour]=e.target.value;W.document.map.appearanceJson=JSON.stringify(a);W.markAdjustmentChanged();W.render();}}); document.addEventListener('change',e=>{const input=e.target;if(input.id==='mapReferenceLibrary')libraryControls();if(input.id==='mapReferenceUpload')upload(input.files?.[0]);if(input.id==='mapCanvasPreset'&&W.mode==='create')W.edit(()=>{const preset=input.value,base=preset==='custom'?E.palette(W.document.map):E.presets[preset];W.document.map.appearanceJson=JSON.stringify({preset,backgroundColor:base.backgroundColor,landColor:base.landColor});});if(input.id==='mapCanvasPreset')$('mapCanvasPreset')?.focus({preventScroll:true});if(input.matches('[data-reference-check]')){const r=ref();if(r)W.edit(()=>putReference({...r,[input.dataset.referenceCheck]:input.checked}));$('mapsDetailContent').querySelector(`[data-reference-check="${input.dataset.referenceCheck}"]`)?.focus({preventScroll:true});}if(input.matches('[data-reference-field]')){updateField(input);finish();}if(input.matches('[data-reference-scale],[data-map-colour]'))finish();}); svg.addEventListener('pointerdown',e=>{if(svg.classList.contains('placing'))return;const handle=e.target.closest('[data-reference-handle]'),onImage=e.target.closest('[data-reference-image]');if(!handle&&!onImage){if(e.target===svg||e.target.closest('#mapsScene')){selected=false;inspecting=false;}return;}if(e.button!==0||W.busy)return;const r=ref();if(!r)return;if(W.mode!=='create')return;if(onImage)inspect(true);else image.focus({preventScroll:true});if(r.isLocked)return;e.preventDefault();e.stopImmediatePropagation();window.getSelection()?.removeAllRanges();if(!begin())return;drag={kind:handle?.dataset.referenceHandle||'move',start:world(e),original:{...r},pointerId:e.pointerId};svg.setPointerCapture(e.pointerId);},true); svg.addEventListener('pointermove',e=>{if(!drag)return;e.preventDefault();putReference(E.transform(drag.original,drag.kind,drag.start,world(e)));W.render();}); svg.addEventListener('pointerup',e=>{if(!drag)return;const id=drag.pointerId;finish();if(svg.hasPointerCapture(id))svg.releasePointerCapture(id);}); svg.addEventListener('pointercancel',()=>finish(true));svg.addEventListener('lostpointercapture',()=>{if(drag)finish(true);}); document.addEventListener('keydown',e=>{if(document.querySelector('.modal.show,dialog[open]'))return;if(e.key==='Escape'&&adjusting){e.preventDefault();e.stopImmediatePropagation();finish(true);return;}if(!selected||W.mode!=='create'||e.target.matches('input,textarea,select')||!e.target.closest('#mapsCanvas'))return;const r=ref();if(!r)return;if(['Delete','Backspace'].includes(e.key)){e.preventDefault();e.stopImmediatePropagation();action('remove');}else if(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)&&!r.isLocked){e.preventDefault();e.stopImmediatePropagation();const handle=e.target.dataset.referenceHandle,positive=['ArrowRight','ArrowUp'].includes(e.key);W.edit(()=>{if(handle==='rotate')putReference({...r,rotation:E.angle(r.rotation+(positive?1:-1)*(e.shiftKey?10:1))});else if(handle==='scale'){const factor=positive?1.02:1/1.02;putReference({...r,width:r.width*factor,height:r.height*factor});}else{const step=e.shiftKey?20:5;putReference({...r,x:r.x+(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0),y:r.y+(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0)});}});if(handle)handles.querySelector(`[data-reference-handle="${handle}"]`)?.focus({preventScroll:true});}},true); window.addEventListener('pd-map-mode',()=>{if(adjusting)finish();selected=false;inspecting=false;render();}); window.addEventListener('pd-map-saved',()=>{const id=ref()?.imageID||null;if(id!==savedID){const previous=metadata(savedID),next=metadata(id);if(previous)previous.useCount=Math.max(0,(previous.useCount||0)-1);if(next)next.useCount=(next.useCount||0)+1;savedID=id;}}); window.PlotDirectorMapAppearance={render,details:showDetails,completeAdjustment:()=>finish(),get adjusting(){return adjusting;},get palette(){return E.palette(W.document?.map);},clearSelection(){selected=false;inspecting=false;},context(target){if(!target.closest('[data-reference-image],[data-reference-handle]'))return null;if(W.mode==='create')inspect(true);const r=ref();return {invoker:image,commands:[{label:'Reference image details',icon:'details',run:()=>inspect(true)},...(W.mode==='create'&&r?[{label:r.isLocked?'Unlock image position':'Lock image position',icon:r.isLocked?'unlock':'lock',run:()=>action('lock')},{label:'Remove reference from map',icon:'remove',run:()=>action('remove')}]:[])]};}}; render(); })();