41 lines
7.4 KiB
JavaScript
41 lines
7.4 KiB
JavaScript
(() => {
|
|
'use strict';
|
|
const mounted=new WeakMap(),ns='http://www.w3.org/2000/svg';
|
|
function mount(host){
|
|
const canvas=host.querySelector('[data-context-map-canvas]'),source=host.querySelector('[data-context-map-data]');if(!canvas||!source||mounted.get(host)?.canvas===canvas)return;
|
|
const data=JSON.parse(source.textContent),doc=data.document,E=window.PlotDirectorMaps,features=doc.features.filter(f=>f.isPlaced),byId=new Map(features.map(f=>[f.featureID,f]));
|
|
const make=(tag,attrs={},text)=>{const node=document.createElementNS(ns,tag);for(const [key,value]of Object.entries(attrs))node.setAttribute(key,String(value));if(text!==undefined)node.textContent=text;return node;};
|
|
const viewport=()=>canvas.viewBox.baseVal;
|
|
const setView=(x,y,w,h)=>{const value=[x,y,Math.max(10,Math.min(1e7,w)),Math.max(10,Math.min(1e7,h))].join(' ');if(canvas.getAttribute('viewBox')!==value)canvas.setAttribute('viewBox',value);};
|
|
let reference;try{reference=JSON.parse(doc.map.referenceJson||'{}');}catch{}
|
|
if(reference?.isVisible!==false&&/^[0-9a-f-]{36}$/i.test(reference?.imageID||''))canvas.append(make('image',{href:`/Maps/ReferenceImage?projectId=${data.projectID}&imageId=${reference.imageID}`,x:reference.x-reference.width/2,y:reference.y-reference.height/2,width:reference.width,height:reference.height,opacity:Math.max(0,Math.min(1,reference.opacity??.35)),transform:`rotate(${reference.rotation||0} ${reference.x} ${reference.y})`}));
|
|
const nodes=new Map();
|
|
for(const f of features){
|
|
const group=make('g',{'data-map-feature':f.featureID,tabindex:0,role:'button','aria-label':f.name});let shape;
|
|
if(f.geometryClass==='Path')shape=make('path',{d:E.curve(E.pathPoints(f,features)),fill:'none',stroke:'var(--plotline-muted)','stroke-width':3});
|
|
else if(f.geometryClass==='Area')shape=make('path',{d:E.curve(E.coastline(f).map(p=>[p[0]*f.width,p[1]*f.height]),true),transform:`translate(${f.x} ${f.y}) rotate(${f.rotation})`,fill:'var(--plotline-panel-muted,var(--plotline-panel))',stroke:'var(--plotline-line)','stroke-width':2});
|
|
else{shape=make('circle',{cx:f.x,cy:f.y,r:Math.max(8,f.width/3),fill:'var(--plotline-panel)',stroke:'var(--plotline-muted)','stroke-width':2});group.append(make('text',{x:f.x,y:f.y+5,'text-anchor':'middle','font-size':18,fill:'var(--plotline-ink)'},E.library.find(a=>a.type===f.type)?.symbol||'◇'));}
|
|
group.prepend(shape);if(f.showLabel)group.append(make('text',{x:f.x+(f.labelX||0),y:f.y+(f.labelY||0)+(f.geometryClass==='Marker'?36:0),'text-anchor':'middle','font-size':16,fill:'var(--plotline-ink)'},f.name));canvas.append(group);nodes.set(f.featureID,group);
|
|
}
|
|
function fit(){const bounds=features.flatMap(f=>f.geometryClass==='Path'?E.pathPoints(f,features):f.geometryClass==='Area'?E.coastline(f).map(p=>E.localToWorld(f,p)):[[f.x-f.width,f.y-f.height],[f.x+f.width,f.y+f.height]]);if(reference?.isVisible!==false&&reference?.imageID)bounds.push([reference.x-reference.width/2,reference.y-reference.height/2],[reference.x+reference.width/2,reference.y+reference.height/2]);if(!bounds.length){setView(-300,-200,600,400);return;}const xs=bounds.map(p=>p[0]),ys=bounds.map(p=>p[1]);setView(Math.min(...xs)-80,Math.min(...ys)-80,Math.max(300,Math.max(...xs)-Math.min(...xs)+160),Math.max(250,Math.max(...ys)-Math.min(...ys)+160));}
|
|
function focus(){const f=byId.get(data.position?.featureID);if(!f)return;const v=viewport();setView(f.x-v.width/2,f.y-v.height/2,v.width,v.height);}
|
|
function zoom(ratio){canvas.dataset.contextManualPan='true';const v=viewport();setView(v.x+v.width*(1-ratio)/2,v.y+v.height*(1-ratio)/2,v.width*ratio,v.height*ratio);}
|
|
function refresh(){
|
|
if(canvas.dataset.contextManualPan!=='true')focus();
|
|
const lens=host.querySelector('[data-context-map-lens]').value,selected=host.querySelector('[data-context-map-feature]').value;
|
|
const highlighted=new Set(lens==='scene'?[data.position?.featureID]:lens==='people'?(data.story?.stops||[]).filter(p=>p.sceneID===data.sceneID).map(p=>p.position.featureID):lens==='plots'?(data.story?.scenes||[]).filter(s=>s.plotLineIDs.length).map(s=>s.position.featureID):features.map(f=>f.featureID));
|
|
for(const[id,node]of nodes){node.classList.toggle('is-scene-place',id===data.position?.featureID);node.classList.toggle('is-explored',id===selected);node.style.opacity=lens==='all'||highlighted.has(id)||id===selected?'1':'.35';}
|
|
const feature=byId.get(selected),detail=host.querySelector('[data-context-map-detail]');
|
|
if(feature){const relationships=doc.relationships.filter(r=>r.sourceID===selected||r.targetID===selected).map(r=>{const other=byId.get(r.sourceID===selected?r.targetID:r.sourceID);return[other?.name,r.direction,r.relativeDistance,r.measuredDistance!=null?r.measuredDistance+' '+(r.unit||''):null,r.typicalTravelTime,r.notes].filter(Boolean).join(' · ');});detail.textContent=[feature.name,feature.notes,...relationships].filter(Boolean).join(' — ');}else detail.textContent='Select a place to inspect its saved relationships.';
|
|
}
|
|
host.querySelector('[data-context-map-fit]').addEventListener('click',()=>{canvas.dataset.contextManualPan='true';fit();});host.querySelector('[data-context-map-focus]').addEventListener('click',()=>{delete canvas.dataset.contextManualPan;focus();});host.querySelectorAll('[data-context-map-zoom]').forEach(button=>button.addEventListener('click',()=>zoom(Number(button.dataset.contextMapZoom))));
|
|
host.querySelector('[data-context-map-feature]').addEventListener('change',event=>select(event.target.value));host.querySelector('[data-context-map-lens]').addEventListener('change',refresh);
|
|
const select=id=>{host.querySelector('[data-context-map-feature]').value=id;const place=byId.get(id);if(place){canvas.dataset.contextManualPan='true';const v=viewport();setView(place.x-v.width/2,place.y-v.height/2,v.width,v.height);}refresh();};canvas.addEventListener('click',event=>{const f=event.target.closest('[data-map-feature]');if(f)select(f.dataset.mapFeature);});canvas.addEventListener('keydown',event=>{const f=event.target.closest('[data-map-feature]');if(f&&['Enter',' '].includes(event.key)){event.preventDefault();select(f.dataset.mapFeature);}else if(['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key)){event.preventDefault();canvas.dataset.contextManualPan='true';const v=viewport();setView(v.x+({'ArrowLeft':-.1,'ArrowRight':.1}[event.key]||0)*v.width,v.y+({'ArrowUp':-.1,'ArrowDown':.1}[event.key]||0)*v.height,v.width,v.height);}});
|
|
let drag=null;canvas.addEventListener('pointerdown',event=>{if(event.button!==0)return;const v=viewport();drag={x:event.clientX,y:event.clientY,left:v.x,top:v.y,w:v.width,h:v.height};canvas.setPointerCapture(event.pointerId);});canvas.addEventListener('pointermove',event=>{if(drag){canvas.dataset.contextManualPan='true';setView(drag.left-(event.clientX-drag.x)*drag.w/canvas.clientWidth,drag.top-(event.clientY-drag.y)*drag.h/canvas.clientHeight,drag.w,drag.h);}});canvas.addEventListener('pointerup',()=>drag=null);canvas.addEventListener('pointercancel',()=>drag=null);
|
|
host.querySelector('[data-context-map-choice]').addEventListener('change',event=>{const url=new URL(host.dataset.componentUrl,location.origin);url.searchParams.set('mapId',event.target.value);host.dataset.componentUrl=url.pathname+url.search;delete host.dataset.loaded;root(host).dispatchEvent(new CustomEvent('writing-view-activated'));});
|
|
mounted.set(host,{refresh,canvas});fit();focus();refresh();
|
|
}
|
|
function root(host){return host.closest('[data-writing-context]');}
|
|
window.PlotDirectorContextMap={mount,refresh:host=>mounted.get(host)?.refresh()};
|
|
})();
|