190 lines
40 KiB
JavaScript
190 lines
40 KiB
JavaScript
(() => {
|
|
'use strict';
|
|
const W=window.PlotDirectorMapWorkspace,E=window.PlotDirectorMapStory,$=id=>document.getElementById(id);
|
|
if(!W||!$('mapStoryLens'))return;
|
|
const app=$('mapsApp'),svg=$('mapsCanvas'),layer=$('mapsStoryLayer'),boot=JSON.parse($('mapsBootstrap').textContent),ns='http://www.w3.org/2000/svg';
|
|
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
const option=(id,label)=>`<option value="${esc(id)}">${esc(label)}</option>`;
|
|
const ids=['mapStoryLens','mapStoryBook','mapStoryScenario','mapStoryScene','mapStoryChapter','mapStoryTime','mapStoryMapping','mapStoryPlanning',...Array.from({length:3},(_,i)=>'mapStoryCharacter'+(i+1)),...Array.from({length:3},(_,i)=>'mapStoryPlot'+(i+1))];
|
|
const state={lens:'overview',scenarioID:Number(new URLSearchParams(location.search).get('scenarioId'))||0,bookID:0,chapterID:0,sceneID:0,characterIDs:[],plotIDs:[],mapping:'all',planning:'all',at:'',visible:true,selection:{kind:'overview'}};
|
|
let loadRequest=null;
|
|
let data=null,scenes=new Map(),people=new Map(),requestVersion=0,loading=false,error='',internalSelect=false,restored=false,initialContextApplied=false;
|
|
const overlayNodes=new Map(),colors=[...(window.PlotDirectorMapAppearance?.palette.story||['#265e83','#7c4f83','#936027'])],styles=['8 5','2 5','12 4 2 4'];
|
|
window.addEventListener('pd-map-palette',e=>{colors.splice(0,colors.length,...e.detail.story);if(data)redraw();});
|
|
const active=()=>W.mode==='story';
|
|
const sceneLabel=s=>`${s.bookTitle} · Ch ${s.chapterNumber} · ${s.sceneNumber}: ${s.sceneTitle}`;
|
|
const dateLabel=s=>s?.timePrecision?`${s.startDateTime.replace('T',' ').slice(0,s.timePrecision==='Day'?10:16)}${s.timePrecision==='Day'?' (date only)':''}`:s?.relativeTimeText||'Story time unknown';
|
|
const windowParams=new URLSearchParams(location.search),detachedQuery=windowParams.get('detached')==='true'?'&detached=true'+(windowParams.get('workspace')?'&workspace='+encodeURIComponent(windowParams.get('workspace')):''):'';
|
|
const mapURL=id=>`/Maps?projectId=${boot.projectId}&id=${id}&mode=story${state.sceneID?'&sceneId='+state.sceneID:''}${data?.scenarioID?'&scenarioId='+data.scenarioID:''}${detachedQuery}`;
|
|
const stopDate=(scene,characterID)=>{const stop=data?.stops.find(s=>s.sceneID===scene.sceneID&&s.characterID===characterID);return stop?.timePrecision&&stop.observedAt?dateLabel({...scene,startDateTime:stop.observedAt,timePrecision:stop.timePrecision}):'Appearance time unknown';};
|
|
function floorPlanURL(id,scene=scenes.get(state.sceneID)){return `/FloorPlans/Edit/${id}${active()&&scene?.floorPlanID===id?`?storySceneId=${scene.sceneID}&storyMapId=${W.document.map.mapID}${data?.scenarioID?'&storyScenarioId='+data.scenarioID:''}`:''}`;}
|
|
const sceneLink=s=>`<a href="/Scenes/Edit/${s.sceneID}">Open / edit scene</a>`;
|
|
function remember(){if(!data)return;try{sessionStorage.setItem(`pd-map-story:${data.userID}:${boot.projectId}:${data.mapID}`,JSON.stringify({lens:state.lens,characterIDs:state.characterIDs,plotIDs:state.plotIDs,visible:state.visible}));}catch{}}
|
|
function restore(){if(restored)return;restored=true;try{const saved=JSON.parse(sessionStorage.getItem(`pd-map-story:${data.userID}:${boot.projectId}:${data.mapID}`)||'null');if(saved){if(['overview','scene','character','chapter','plot','time'].includes(saved.lens))state.lens=saved.lens;state.characterIDs=(saved.characterIDs||[]).filter(id=>people.has(id)).slice(0,3);state.plotIDs=(saved.plotIDs||[]).filter(id=>data.plotLines.some(p=>p.plotLineID===id)).slice(0,3);state.visible=saved.visible!==false;}}catch{}}
|
|
function setup(){
|
|
scenes=new Map(data.scenes.map(s=>[s.sceneID,s]));people=new Map(data.characters.map(p=>[p.characterID,p]));restore();
|
|
const params=new URLSearchParams(location.search);if(!initialContextApplied&¶ms.has('sceneId')&&scenes.has(Number(params.get('sceneId')))){state.sceneID=Number(params.get('sceneId'));state.lens='scene';state.selection={kind:'scene',sceneID:state.sceneID};}initialContextApplied=true;
|
|
$('mapStoryScenario').innerHTML=option(0,'Canonical manuscript')+data.scenarios.map(s=>option(s.scenarioID,s.scenarioName)).join('');$('mapStoryScenario').value=String(data.scenarioID||0);state.scenarioID=data.scenarioID||0;
|
|
$('mapStoryBook').innerHTML=option(0,'All books')+[...new Map(data.scenes.map(s=>[s.bookID,s.bookTitle])).entries()].map(([id,name])=>option(id,name)).join('');$('mapStoryBook').value=String(state.bookID);
|
|
for(let i=1;i<=3;i++){$('mapStoryCharacter'+i).innerHTML=option(0,i===1?'Choose character':'None')+[...data.characters].sort((a,b)=>a.name.localeCompare(b.name,undefined,{sensitivity:'base'})||a.characterID-b.characterID).map(c=>option(c.characterID,c.name)).join('');$('mapStoryCharacter'+i).value=String(state.characterIDs[i-1]||0);$('mapStoryPlot'+i).innerHTML=option(0,i===1?'All Plot Lines':'None')+data.plotLines.map(p=>option(p.plotLineID,p.plotLineName)).join('');$('mapStoryPlot'+i).value=String(state.plotIDs[i-1]||0);}
|
|
$('mapStoryLens').value=state.lens;scopeOptions();
|
|
}
|
|
function scopeOptions(){
|
|
const scoped=data.scenes.filter(s=>!state.bookID||s.bookID===state.bookID),query=$('mapStorySceneSearch').value.toLowerCase();
|
|
$('mapStoryScene').innerHTML=scoped.filter(s=>sceneLabel(s).toLowerCase().includes(query)).map(s=>option(s.sceneID,sceneLabel(s))).join('');
|
|
if(!scoped.some(s=>s.sceneID===state.sceneID))state.sceneID=scoped[0]?.sceneID||0;
|
|
$('mapStoryScene').value=String(state.sceneID);
|
|
const chapters=[...new Map(scoped.map(s=>[s.chapterID,`${s.bookTitle} · Ch ${s.chapterNumber}: ${s.chapterTitle}`])).entries()];
|
|
$('mapStoryChapter').innerHTML=option(0,'All chapters')+chapters.map(([id,label])=>option(id,label)).join('');if(state.chapterID&&!chapters.some(([id])=>id===state.chapterID))state.chapterID=0;$('mapStoryChapter').value=String(state.chapterID);
|
|
const times=E.timeEvents(data,state.bookID);$('mapStoryTime').innerHTML=times.map(s=>option(s.startDateTime,`${dateLabel(s)} · ${s.sceneTitle}`)).join('');if(!times.some(s=>s.startDateTime===state.at))state.at=times[0]?.startDateTime||'';$('mapStoryTime').value=state.at;
|
|
}
|
|
function load(force=false){if(loadRequest&&!force)return loadRequest;const request=loadCore(force);loadRequest=request;request.finally(()=>{if(loadRequest===request)loadRequest=null;});return request;}
|
|
async function loadCore(force=false){
|
|
if(!W.document)return;
|
|
if(W.dirty){error='Save or undo geography changes in Create before loading Story. Story navigation never saves your map.';data=null;refresh();return;}
|
|
if(data&&!force){refresh();return;}
|
|
const version=++requestVersion;loading=true;error='';refresh();
|
|
try{
|
|
const scenario=state.scenarioID;
|
|
const response=await fetch(`/Maps/Story?projectId=${boot.projectId}&id=${W.document.map.mapID}${scenario?'&scenarioId='+scenario:''}`);
|
|
if(!response.ok||response.redirected)throw Error('Story data is unavailable. Check access or sign in again, then refresh.');
|
|
const result=await response.json();if(version!==requestVersion)return;data=result;setup();
|
|
}catch(e){if(version===requestVersion){data=null;error=e.message;}}
|
|
finally{if(version===requestVersion){loading=false;refresh();}}
|
|
}
|
|
function controls(){
|
|
$('mapsStoryToolbar').hidden=!active();if($('mapStorySearchLabel'))$('mapStorySearchLabel').hidden=state.lens!=='scene';app.dataset.storyLens=state.lens;for(const link of $('mapsBreadcrumbs').querySelectorAll('a')){const url=new URL(link.href);if(!url.searchParams.has('id'))continue;if(active()){url.searchParams.set('mode','story');if(state.sceneID)url.searchParams.set('sceneId',state.sceneID);if(data?.scenarioID)url.searchParams.set('scenarioId',data.scenarioID);else url.searchParams.delete('scenarioId');}else{url.searchParams.delete('mode');url.searchParams.delete('sceneId');url.searchParams.delete('scenarioId');}link.href=url.href;}
|
|
const show={'Story scene':state.lens==='scene','Story characters':['character','time'].includes(state.lens),'Story chapter':state.lens==='chapter','Story plot':state.lens==='plot','Story time':state.lens==='time','Story navigation':['scene','time'].includes(state.lens)};
|
|
for(const[label,visible]of Object.entries(show))document.querySelectorAll(`#mapsStoryToolbar [data-pwa-context="${label}"]`).forEach(n=>n.hidden=!visible);
|
|
$('mapStoryPrevious').textContent=state.lens==='time'?'Previous dated event':'Previous scene';$('mapStoryNext').textContent=state.lens==='time'?'Next dated event':'Next scene';
|
|
$('mapStoryLayer').setAttribute('aria-pressed',String(state.visible));
|
|
if($('mapStoryFilters'))$('mapStoryFilters').hidden=['character','time'].includes(state.lens);
|
|
for(const id of ['mapsNew','mapsRename','mapsDuplicate','mapsDelete'])$(id).hidden=active();
|
|
document.querySelector('.maps-toolbar [data-pwa-context="Map actions"]').hidden=active();
|
|
}
|
|
function visibleScenes(){return data?E.filterScenes(data,state):[];}
|
|
function refresh(){
|
|
controls();$('mapStoryScrubberRow').hidden=!active()||!data||state.lens!=='scene';if(!active()){layer.toggleAttribute('hidden',true);document.querySelectorAll('.map-story-muted').forEach(n=>n.classList.remove('map-story-muted'));return;}
|
|
$('mapsStory').hidden=false;
|
|
if(!data){$('mapsStory').textContent=loading?'Loading manuscript geography…':error||'Choose Refresh story to load manuscript geography.';layer.toggleAttribute('hidden',true);$('mapsDetailContent').innerHTML=`<div class="maps-story-details"><p>${esc(loading?'Loading canonical story data…':error||'No story projection loaded.')}</p></div>`;return;}
|
|
const selected=visibleScenes();if(state.lens==='scene'&&!selected.some(s=>s.sceneID===state.sceneID)){state.sceneID=selected[0]?.sceneID||0;$('mapStoryScene').value=String(state.sceneID);state.selection={kind:'overview'};}const mapped=selected.filter(s=>E.mapped(s.position)).length,unmapped=selected.filter(s=>s.position.status==='Unmapped').length,missing=selected.filter(s=>!s.primaryLocationID).length;
|
|
$('mapsStory').textContent=`${state.lens==='plot'?'Plot Line':state.lens[0].toUpperCase()+state.lens.slice(1)} · ${selected.length} scenes · ${mapped} on this map · ${unmapped} unmapped · ${missing} without a Location. Journeys show story movement, not literal routes.`;
|
|
if(state.lens==='character'){const stops=E.journeys(data,state.characterIDs,selected);$('mapsStory').textContent=`Character journeys · ${state.characterIDs.length} selected · ${stops.length} appearances · ${stops.filter(s=>s.position.featureID).length} mapped stops · ${stops.filter(s=>s.position.status==='Unmapped').length} unmapped stops. Numbered revisits are preserved; lines are not literal routes.`;}
|
|
if(state.lens==='time'){$('mapsStory').textContent=`Time · ${state.at?state.at.replace('T',' '):'No confirmed dated events'} · Last known Locations only. Positions between scenes are not established.`;}
|
|
const sequence=state.lens==='time'?E.timeEvents(data,state.bookID):selected,index=state.lens==='time'?sequence.findIndex(s=>s.startDateTime===state.at):sequence.findIndex(s=>s.sceneID===state.sceneID);
|
|
$('mapStoryPrevious').disabled=index<=0;$('mapStoryNext').disabled=index<0||index>=sequence.length-1;
|
|
const current=scenes.get(state.sceneID),scrubber=$('mapStoryScrubber');scrubber.max=String(Math.max(0,selected.length-1));scrubber.value=String(Math.max(0,index));scrubber.disabled=!selected.length;
|
|
const context=current?`${index+1} / ${selected.length} · Ch ${current.chapterNumber} · ${current.position.locationName||'No Location'} · ${current.position.status}`:'No scenes in this scope';scrubber.setAttribute('aria-valuetext',context);$('mapStoryScrubberContext').textContent=context;
|
|
$('mapStoryCoverage').hidden=!unmapped;$('mapStoryCoverage').title='Story Mode can only place scenes whose Locations are represented on this map.';
|
|
if(mapped<selected.length&&state.lens!=='time')$('mapsStory').textContent+=' Story Mode can only place scenes whose Locations are represented on this map.';
|
|
redraw();renderDetails(W.selected[0]);remember();sceneExplorer?.sync();
|
|
if(active())window.dispatchEvent(new CustomEvent('pd-map-story-state',{detail:{...state,selection:undefined,mapID:W.document.map.mapID}}));
|
|
}
|
|
function position(f){return [f.x,f.y];}
|
|
function redraw(){
|
|
if(!active()||!data){layer.toggleAttribute('hidden',true);return;}layer.toggleAttribute('hidden',!state.visible);
|
|
const selected=visibleScenes(),features=new Map(W.document.features.map(f=>[f.featureID,f])),wanted=new Map(),inUse=new Set(),scale=W.view.w/Math.max(1,svg.clientWidth);
|
|
const node=(key,markup,cls,label,attrs={})=>wanted.set(key,{markup,cls,label,attrs});
|
|
function badge(key,p,text,label,attrs={},offset=0,color=colors[0]){const f=features.get(p?.featureID);if(!f)return;inUse.add(f.featureID);const x=f.x+offset*scale,y=f.y-30*scale;node(key,`<rect x="${x-Math.max(28,String(text).length*6+12)*scale/2}" y="${y-13*scale}" width="${Math.max(28,String(text).length*6+12)*scale}" height="${26*scale}" rx="${13*scale}" fill="#fffef1" stroke="${color}" stroke-width="${2*scale}"/><text class="maps-story-label" x="${x}" y="${y+4*scale}" text-anchor="middle" style="font-size:${11*scale}px;stroke-width:${2*scale}px">${esc(text)}</text>`,'maps-story-point',label,attrs);}
|
|
if(state.lens==='character'){
|
|
const stops=E.journeys(data,state.characterIDs,selected),groups=new Map();
|
|
for(const stop of stops){if(!E.mapped(stop.position))continue;const key=stop.characterID+':'+stop.position.featureID;if(!groups.has(key))groups.set(key,[]);groups.get(key).push(stop);}
|
|
for(const[key,visits]of groups){const first=visits[0],index=state.characterIDs.indexOf(first.characterID);badge('stop:'+key,first.position,`${String.fromCharCode(65+index)}${visits.map(s=>s.sequence).slice(0,3).join(',')}${visits.length>3?'…':''}`,`${people.get(first.characterID)?.name}: stops ${visits.map(s=>s.sequence).join(', ')}. Select for scenes.`,{'data-story-character':first.characterID,'data-story-feature':first.position.featureID},index*100,colors[index]);}
|
|
const allowed=new Set(stops.map(s=>s.characterID+':'+s.sceneID)),pairCounts=new Map(),drawnConnections=new Set();
|
|
for(const leg of data.legs){if(!allowed.has(leg.characterID+':'+leg.fromSceneID)||!allowed.has(leg.characterID+':'+leg.toSceneID)||!E.mapped(leg.from)||!E.mapped(leg.to)||leg.from.featureID===leg.to.featureID)continue;const a=features.get(leg.from.featureID),b=features.get(leg.to.featureID);if(!a||!b)continue;const connection=leg.characterID+':'+leg.from.featureID+':'+leg.to.featureID;if(drawnConnections.has(connection))continue;drawnConnections.add(connection);const index=state.characterIDs.indexOf(leg.characterID),pair=leg.characterID+':'+[leg.from.featureID,leg.to.featureID].sort().join(':'),visit=pairCounts.get(pair)||0;pairCounts.set(pair,visit+1);const bend=((index+1)*30+visit*24)*scale,length=Math.hypot(b.x-a.x,b.y-a.y)||1,d=`M${a.x} ${a.y} Q${(a.x+b.x)/2-(b.y-a.y)/length*bend} ${(a.y+b.y)/2+(b.x-a.x)/length*bend} ${b.x} ${b.y}`;node(`leg:${leg.characterID}:${leg.fromSceneID}:${leg.toSceneID}`,`<path d="${d}" fill="none" stroke="${colors[index]}" stroke-width="${2.5*scale}" stroke-dasharray="${styles[index]}"/><path d="${d}" fill="none" stroke="transparent" stroke-width="${12*scale}"/>`,'maps-story-leg',`${String.fromCharCode(65+index)} ${people.get(leg.characterID)?.name}: movement from ${leg.from.locationName||'Unknown'} to ${leg.to.locationName||'Unknown'}. Not a literal route.`,{'data-story-leg':`${leg.characterID}:${leg.fromSceneID}:${leg.toSceneID}`});}
|
|
}else if(state.lens==='time'){
|
|
const positions=E.timePositions(data,state.at,state.characterIDs,state.bookID),display=state.characterIDs.length?positions:positions.slice(0,8),groups=new Map();
|
|
display.forEach(p=>{if(!p.position?.featureID)return;const key=p.position.featureID;if(!groups.has(key))groups.set(key,[]);groups.get(key).push(p);});
|
|
for(const[key,group]of groups)badge('time:'+key,group[0].position,`${group.length} last`,group.map(p=>`${p.character.name}: last known ${p.position.locationName}`).join('; '),{'data-story-feature':key});
|
|
}else if(state.lens==='scene'){
|
|
const s=scenes.get(state.sceneID);if(s&&selected.some(x=>x.sceneID===s.sceneID))badge('scene:'+s.sceneID,s.position,'●',`${s.sceneTitle}: ${s.position.status}`,{'data-story-scene':s.sceneID});
|
|
}else{
|
|
for(const[id,used]of E.density(selected))badge('density:'+id,used[0].position,String(used.length),`${features.get(id)?.name}: ${used.length} scenes`,{'data-story-feature':id});
|
|
}
|
|
const keep=new Set(wanted.keys());for(const[key,n]of overlayNodes)if(!keep.has(key)){n.remove();overlayNodes.delete(key);}
|
|
// Draw journey legs below their stop badges. Keep keyed groups and the base geography intact.
|
|
const ordered=[...wanted].sort((a,b)=>Number(!a[0].startsWith('leg:'))-Number(!b[0].startsWith('leg:')));for(const[key,content]of ordered){
|
|
let n=overlayNodes.get(key);if(!n){n=document.createElementNS(ns,'g');n.dataset.storyKey=key;n.setAttribute('tabindex','0');n.setAttribute('role','button');overlayNodes.set(key,n);layer.append(n);}
|
|
n.setAttribute('class',content.cls);n.setAttribute('aria-label',content.label);for(const[k,v]of Object.entries(content.attrs))n.setAttribute(k,v);
|
|
if(n.innerHTML!==content.markup)n.innerHTML=content.markup;
|
|
}
|
|
ordered.forEach(([key],i)=>{const n=overlayNodes.get(key);if(layer.children[i]!==n)layer.insertBefore(n,layer.children[i]||null);});
|
|
const fade=['plot','chapter','character','scene'].includes(state.lens);
|
|
document.querySelectorAll('#mapsScene [data-feature-id], #mapsScene [data-boundary-feature-id], #mapsLabels [data-label-feature-id]').forEach(n=>{const f=features.get(n.dataset.featureId||n.dataset.boundaryFeatureId||n.dataset.labelFeatureId);n.classList.toggle('map-story-muted',fade&&!!f?.locationID&&!inUse.has(f.featureID));});
|
|
const shared=document.querySelectorAll('#mapsScene [data-shared-edge-id]');if(shared.length&&window.PlotDirectorTopology){const topology=window.PlotDirectorTopology.context(W.document.features);shared.forEach(n=>n.classList.toggle('map-story-muted',fade&&topology.users(n.dataset.sharedEdgeId).every(id=>!!features.get(id)?.locationID&&!inUse.has(id))));}
|
|
}
|
|
function locationLinks(p,scene){let html='';if(p.detailMapID)html+=`<a href="${mapURL(p.detailMapID)}">Open ${p.status==='On ancestor map'?'ancestor':'detailed'} map ↳</a>`;
|
|
const floor=scene?.floorPlanID||p.floorPlanID;if(floor)html+=`<a href="${floorPlanURL(floor,scene)}">${scene?.floorPlanID===floor?'Open Floor Plan Story / occupancy':'Open linked Floor Plan'}</a>`;
|
|
if(p.locationID)html+=`<a href="/Locations/Details/${p.locationID}">Open story Location</a>`;return `<div class="maps-story-links">${html}</div>`;}
|
|
function sceneButton(s,label,person=0){return `<button type="button" data-story-scene="${s.sceneID}" ${person?`data-story-person="${person}"`:''}>${esc(label||sceneLabel(s))}</button>`;}
|
|
function sceneDetails(s,stop){const p=stop?.position||s.position;return `<h3>${esc(s.sceneTitle)}</h3><p>${esc(sceneLabel(s))}</p><p>${esc(p.locationName||'No Location assigned')} · ${esc(p.status)}${p.isProvisional?' · ◇ Planning map piece':''}</p><p>${esc(dateLabel(s))}</p>${stop?`<p>${esc(stop.evidence)} · ${esc(stopDate(s,stop.characterID))}</p>`:''}${s.summary?`<p>${esc(s.summary)}</p>`:''}${sceneLink(s)}${locationLinks(p,s)}${p.status==='Unmapped'?`<button type="button" data-story-place="${p.locationID}">Switch to Create to place this Location</button>`:''}<p class="maps-story-summary">Characters: ${esc(s.characterIDs.map(id=>people.get(id)?.name).filter(Boolean).join(', ')||'None recorded')}<br/>Plot Lines: ${esc(s.plotLineIDs.map(id=>data.plotLines.find(p=>p.plotLineID===id)?.plotLineName).filter(Boolean).join(', ')||'None recorded')}</p>`;}
|
|
function legDetails(leg){const a=scenes.get(leg.fromSceneID),b=scenes.get(leg.toSceneID),character=people.get(leg.characterID);return `<h3>${esc(character?.name)} · journey leg</h3><p>${esc(leg.from.locationName||'Unknown')} → ${esc(leg.to.locationName||'Unknown')}</p><p class="maps-story-notice">Movement between known scene points. This does not establish a straight-line journey or use of any road.</p><div class="maps-story-list">${sceneButton(a,'From: '+sceneLabel(a),leg.characterID)}${sceneButton(b,'To: '+sceneLabel(b),leg.characterID)}</div><p>${esc(stopDate(a,leg.characterID))} → ${esc(stopDate(b,leg.characterID))}</p><p>${leg.direction?'Origin is '+esc(leg.direction)+' of destination. ':''}${esc(leg.relativeDistance||'Relative distance unknown')}</p><p>${leg.measuredDistance!=null?`${esc(leg.measuredDistance)} ${esc(leg.unit||'units unspecified')}`:'Measured distance unknown'}</p><p>Typical travel: ${leg.typicalMinutes?esc(leg.typicalMinutes)+' minutes':esc(leg.typicalTravelTime||'Unknown')}<br/>Elapsed story time: ${leg.elapsedMinutes!=null?esc(leg.elapsedMinutes)+' minutes':'Not enough confirmed timestamps'}<br/>Evidence level ${leg.evidenceLevel}</p><p>Author-selected route: ${esc(W.document.features.find(f=>f.featureID===leg.note?.routeFeatureID)?.name||'None specified')}<br/>Method: ${esc(leg.note?.travelMethod||'Not specified')}</p>${data.legs.filter(l=>l.characterID===leg.characterID&&l.from.featureID&&l.to.featureID&&((l.from.featureID===leg.from.featureID&&l.to.featureID===leg.to.featureID)||(l.to.featureID===leg.from.featureID&&l.from.featureID===leg.to.featureID))).length>1?`<details><summary>Repeated movements on this connection</summary><div class="maps-story-list">${data.legs.filter(l=>l.characterID===leg.characterID&&l.from.featureID&&l.to.featureID&&((l.from.featureID===leg.from.featureID&&l.to.featureID===leg.to.featureID)||(l.to.featureID===leg.from.featureID&&l.from.featureID===leg.to.featureID))).map(l=>`<button type="button" data-story-leg="${l.characterID}:${l.fromSceneID}:${l.toSceneID}">${esc(scenes.get(l.fromSceneID)?.sceneTitle)} → ${esc(scenes.get(l.toSceneID)?.sceneTitle)}</button>`).join('')}</div></details>`:''}${leg.timingObservation?'<p class="maps-story-notice">Possible travel timing to review. The elapsed confirmed story time is shorter than the explicit typical journey time. Review this transition if it was not intentional.</p>':''}<details><summary>Author-selected travel context</summary><form id="mapStoryJourneyForm"><label>Travel via <select name="routeFeatureID">${option('','No route specified')}${W.document.features.filter(f=>f.geometryClass==='Path').map(f=>`<option value="${f.featureID}" ${f.featureID===leg.note?.routeFeatureID?'selected':''}>${esc(f.name)}</option>`).join('')}</select></label><label>Method (descriptive only)<input name="travelMethod" list="mapStoryTravelMethods" maxlength="80" value="${esc(leg.note?.travelMethod)}" placeholder="Walk, car, horse, portal…" /></label><datalist id="mapStoryTravelMethods">${['Walk','Horse','Car','Train','Boat','Air','Other'].map(m=>option(m,m)).join('')}</datalist><label>Author's typical duration, minutes (optional)<input name="typicalMinutes" type="number" min="1" max="525600" value="${esc(leg.note?.typicalMinutes)}" /></label><button type="submit">Save travel context</button><p class="maps-hint">Leave all fields empty to clear. No speed is assumed from method, route or map spacing.</p></form></details>`;}
|
|
function overviewDetails(selected){const counts=E.density(selected),missing=selected.filter(s=>!s.primaryLocationID),unmapped=selected.filter(s=>s.position.status==='Unmapped'),elsewhere=selected.filter(s=>!s.position.featureID&&s.position.detailMapID);return `<h3>${state.lens==='plot'?'Plot Line geography':state.lens==='chapter'?'Chapter geography':'Story geography'}</h3><p>${selected.length} scenes · ${counts.size} mapped places · ${new Set(unmapped.map(s=>s.primaryLocationID)).size} unmapped story Locations · ${missing.length} scenes without a Location.</p><p class="maps-hint">Density counts use primary scene Locations, not physical area. Location Details also include explicit character-position evidence. Ordinary terrain is not treated as unused story geography.</p>${[...counts].sort((a,b)=>b[1].length-a[1].length).slice(0,12).map(([id,list])=>`<div class="maps-story-list"><button type="button" data-story-feature="${id}">${esc(W.document.features.find(f=>f.featureID===id)?.name)} · ${list.length} scenes (${Math.round(list.length/Math.max(1,selected.length)*100)}%)</button></div>`).join('')}<p>${elsewhere.length} scenes have a Location on another map level.</p><button type="button" data-story-view="gaps">Inspect unmapped / no-Location scenes</button><p><a href="/PlotLineWorkspace?projectId=${boot.projectId}">Open Plot Lines Workspace</a> · <a href="/Timeline?projectId=${boot.projectId}">Open Timeline</a></p>`;}
|
|
function renderDetails(featureID){
|
|
if(!active())return false;if(!data){refresh();return true;}
|
|
let html='',selection=state.selection,selected=visibleScenes();
|
|
if(selection.kind==='scene'){const s=scenes.get(selection.sceneID);if(s)html=sceneDetails(s,selection.characterID?data.stops.find(x=>x.characterID===selection.characterID&&x.sceneID===selection.sceneID):null);}
|
|
if(selection.kind==='leg'){const leg=data.legs.find(l=>`${l.characterID}:${l.fromSceneID}:${l.toSceneID}`===selection.key);if(leg)html=legDetails(leg);}
|
|
if(selection.kind==='gaps'){
|
|
const groups=new Map();for(const s of selected.filter(s=>!s.position.featureID)){const key=s.position.status+':'+(s.primaryLocationID||0);if(!groups.has(key))groups.set(key,[]);groups.get(key).push(s);}
|
|
html='<h3>Unmapped / no Location</h3><p>Nothing is positioned automatically. Scene Locations are edited in the existing scene editor.</p>'+[...groups].map(([,list])=>{const p=list[0].position;return `<h4>${esc(p.locationName||'No Location assigned')} · ${esc(p.status)}</h4>${locationLinks(p,list[0])}${p.status==='Unmapped'?`<button type="button" data-story-place="${p.locationID}">Place this Location in Create</button>`:''}<div class="maps-story-list">${list.map(s=>sceneButton(s)).join('')}</div>`;}).join('');if(!groups.size)html+='<p>All scenes in the current scope are represented on this map.</p>';
|
|
}
|
|
if(selection.kind==='observations'){const observations=data.legs.filter(l=>l.timingObservation&&selected.some(s=>s.sceneID===l.toSceneID));html='<h3>Travel observations</h3><p>Observations use confirmed exact timestamps and explicit typical travel durations at exact, established map endpoints. Teleportation, off-page travel and intentional timing remain possible.</p>'+observations.map(l=>`<div class="maps-story-list"><button type="button" data-story-leg="${l.characterID}:${l.fromSceneID}:${l.toSceneID}">Possible travel timing to review: ${esc(people.get(l.characterID)?.name)} · ${esc(l.from.locationName)} → ${esc(l.to.locationName)}</button></div>`).join('');if(!observations.length)html+='<p>No timing observations with sufficient evidence in this scope. Canvas distance and relative distance categories never establish travel time.</p>';}
|
|
if(!html&&selection.kind==='feature'&&featureID){const feature=W.document.features.find(f=>f.featureID===featureID),scopeIDs=new Set(selected.map(s=>s.sceneID)),physical=data.stops.filter(s=>s.position.featureID===featureID&&scopeIDs.has(s.sceneID)),physicalScenes=new Set(physical.map(s=>s.sceneID)),used=selected.filter(s=>s.position.featureID===featureID||physicalScenes.has(s.sceneID)),location=boot.locations.find(l=>l.locationID===feature?.locationID),stops=physical.filter(s=>state.characterIDs.includes(s.characterID));html=`<h3>${esc(feature?.name)}</h3><p>${feature?.isProvisional?'◇ Planning map piece':'Established map piece'}${location?' · linked story Location':''}</p>${location?.description?`<p>${esc(location.description)}</p>`:''}<p>${used.length} scenes in the current scope. ${used.length===0&&feature?.locationID?'No scenes in this scope use this Location.':''}</p><p>Chapters: ${new Set(used.map(s=>s.chapterID)).size}<br/>Characters: ${esc([...new Set(physical.map(s=>s.characterID))].map(id=>people.get(id)?.name).filter(Boolean).join(', ')||'None recorded')}<br/>Plot Lines: ${esc([...new Set(used.flatMap(s=>s.plotLineIDs))].map(id=>data.plotLines.find(p=>p.plotLineID===id)?.plotLineName).filter(Boolean).join(', ')||'None recorded')}</p>${used.length?`<p>First: ${esc(sceneLabel(used[0]))}<br/>Last: ${esc(sceneLabel(used.at(-1)))}</p>`:''}${locationLinks({locationID:feature?.locationID,floorPlanID:feature?.floorPlanID,detailMapID:boot.maps.find(m=>m.parentMapID===W.document.map.mapID&&m.parentFeatureID===featureID)?.mapID,status:'Detail map'})}<div class="maps-story-list">${(state.lens==='character'?stops.map(stop=>sceneButton(scenes.get(stop.sceneID),`${people.get(stop.characterID)?.name} · stop ${stop.sequence} · ${sceneLabel(scenes.get(stop.sceneID))}`,stop.characterID)):used.map(s=>sceneButton(s))).join('')}</div>`;}
|
|
if(!html&&state.lens==='character'){
|
|
const stops=E.journeys(data,state.characterIDs,selected);html='<h3>Character journeys</h3><p>Choose up to three characters. Letters A/B/C, stop numbers and different line patterns distinguish their journeys. Repeated visits retain their sequence. Unknown stops break the drawn journey.</p>';
|
|
for(const[idIndex,id]of state.characterIDs.entries()){const visits=stops.filter(s=>s.characterID===id);html+=`<h4>${String.fromCharCode(65+idIndex)} · ${esc(people.get(id)?.name)}</h4><p>${new Set(visits.map(s=>s.position.locationID).filter(Boolean)).size} known Locations · ${visits.filter(s=>s.position.status==='Unmapped').length} unmapped stops · ${visits.filter(s=>!s.position.locationID).length} unknown stops</p><ol role="list">${visits.map(s=>`<li><button type="button" data-story-scene="${s.sceneID}" data-story-person="${id}">${s.sequence}. ${esc(s.position.locationName||'Unknown')} · ${esc(s.position.status)} · ${esc(scenes.get(s.sceneID)?.sceneTitle)}</button></li>`).join('')}</ol><div class="maps-story-list">${data.legs.filter(l=>l.characterID===id&&visits.some(v=>v.sceneID===l.fromSceneID)&&visits.some(v=>v.sceneID===l.toSceneID)).map(l=>`<button type="button" data-story-leg="${l.characterID}:${l.fromSceneID}:${l.toSceneID}">Journey leg: ${esc(l.from.locationName||'Unknown')} → ${esc(l.to.locationName||'Unknown')} · ${esc(scenes.get(l.toSceneID)?.sceneTitle)}</button>`).join('')}</div>`;}
|
|
}
|
|
if(!html&&state.lens==='time'){const positions=E.timePositions(data,state.at,state.characterIDs,state.bookID);html='<h3>Last known geography</h3><p>Confirmed dated evidence only. No positions are interpolated between scenes. Date-only appearances cannot establish an intraday position. Undated / estimated appearances are not positioned in time.</p>'+(!state.at?'<p>No confirmed dated events in this scope.</p>':`<p>As of ${esc(state.at.replace('T',' '))}. ${state.characterIDs.length?'Selected characters':'Markers show up to eight significant characters; the list includes everyone'}.</p>`)+positions.map(p=>`<h4>${esc(p.character.name)}</h4><p>${p.position?'Last known: '+esc(p.position.locationName)+' · '+esc(p.position.status):'Unknown'}${p.scene?' · '+esc(dateLabel(p.scene)):''}</p><p class="maps-hint">${esc(p.reason)}</p>${p.scene?sceneButton(p.scene,'Inspect evidence: '+p.scene.sceneTitle):''}${p.position?locationLinks(p.position,p.scene):''}`).join('');}
|
|
if(!html&&state.lens==='scene'){const s=scenes.get(state.sceneID);html=s?sceneDetails(s):'<p>No scenes in this scope.</p>';}
|
|
if(!html)html=overviewDetails(selected);
|
|
const pane=$('mapsDetails'),scroll=pane.scrollTop;$('mapsDetailContent').innerHTML=`<div class="maps-story-details">${html}</div>`;pane.scrollTop=scroll;return true;
|
|
}
|
|
function chooseScene(id,characterID=0){const s=scenes.get(id);if(!s)return;state.sceneID=id;state.selection={kind:'scene',sceneID:id,characterID};if(![...$('mapStoryScene').options].some(o=>Number(o.value)===id)){$('mapStorySceneSearch').value='';scopeOptions();}$('mapStoryScene').value=String(id);const stop=characterID?data.stops.find(x=>x.characterID===characterID&&x.sceneID===id):null,p=stop?.position||s.position;internalSelect=true;if(p.featureID){W.select(p.featureID);W.focus(p.featureID);}else W.clearSelection();internalSelect=false;refresh();}
|
|
function navigateStep(direction){if(!data)return;if(state.lens==='scene'){sceneExplorer.step(direction);return;}const sequence=state.lens==='time'?E.timeEvents(data,state.bookID):visibleScenes(),index=state.lens==='time'?sequence.findIndex(s=>s.startDateTime===state.at):sequence.findIndex(s=>s.sceneID===state.sceneID),next=sequence[index+direction];if(!next)return;if(state.lens==='time'){state.at=next.startDateTime;$('mapStoryTime').value=state.at;state.selection={kind:'overview'};refresh();}else chooseScene(next.sceneID);}
|
|
svg.addEventListener('pointerdown',e=>{if(active()&&e.target.closest('[data-feature-id]')&&!internalSelect)state.selection={kind:'feature'};},true);
|
|
document.addEventListener('click',e=>{if(active()&&e.target.closest('[data-search-feature]'))state.selection={kind:'feature'};},true);
|
|
document.addEventListener('click',e=>{
|
|
if(!active()||!data)return;
|
|
const leg=e.target.closest('[data-story-leg]');if(leg){state.selection={kind:'leg',key:leg.dataset.storyLeg};renderDetails();return;}
|
|
const scene=e.target.closest('[data-story-scene]');if(scene){chooseScene(Number(scene.dataset.storyScene),Number(scene.dataset.storyPerson)||0);return;}
|
|
const feature=e.target.closest('[data-story-feature]');if(feature){state.selection={kind:'feature'};internalSelect=true;W.select(feature.dataset.storyFeature);internalSelect=false;refresh();return;}
|
|
const view=e.target.closest('[data-story-view]');if(view){state.selection={kind:view.dataset.storyView};renderDetails();}
|
|
const place=e.target.closest('[data-story-place]');if(place){W.setMode('create');$('mapsLocationSearch').value='';$('mapsLocationSearch').dispatchEvent(new Event('input'));document.querySelector(`[data-location="${Number(place.dataset.storyPlace)}"]`)?.click();}
|
|
});
|
|
layer.addEventListener('keydown',e=>{if(['Enter',' '].includes(e.key)){e.preventDefault();e.target.closest('[data-story-key]')?.dispatchEvent(new MouseEvent('click',{bubbles:true}));}});
|
|
document.addEventListener('change',e=>{
|
|
if(!ids.includes(e.target.id)||!data)return;
|
|
if(e.target.id==='mapStoryScenario'){state.scenarioID=Number(e.target.value)||0;state.selection={kind:'overview'};load(true);return;}
|
|
state.lens=$('mapStoryLens').value;if(['character','time'].includes(state.lens)){$('mapStoryMapping').value='all';$('mapStoryPlanning').value='all';}state.bookID=Number($('mapStoryBook').value)||0;state.chapterID=Number($('mapStoryChapter').value)||0;state.mapping=$('mapStoryMapping').value;state.planning=$('mapStoryPlanning').value;
|
|
state.characterIDs=[...new Set([1,2,3].map(i=>Number($('mapStoryCharacter'+i).value)).filter(Boolean))];state.plotIDs=[...new Set([1,2,3].map(i=>Number($('mapStoryPlot'+i).value)).filter(Boolean))];
|
|
if(e.target.id==='mapStoryBook')scopeOptions();
|
|
if(e.target.id==='mapStoryScene'){chooseScene(Number(e.target.value));return;}
|
|
state.at=$('mapStoryTime').value;state.selection={kind:'overview'};W.clearSelection();refresh();
|
|
});
|
|
$('mapStorySceneSearch').addEventListener('input',()=>{if(data)scopeOptions();});
|
|
document.addEventListener('submit',async e=>{
|
|
if(e.target.closest('#mapsStoryToolbar')){e.preventDefault();return;}
|
|
if(e.target.id!=='mapStoryJourneyForm')return;e.preventDefault();const leg=data.legs.find(l=>`${l.characterID}:${l.fromSceneID}:${l.toSceneID}`===state.selection.key);if(!leg)return;
|
|
const values=Object.fromEntries(new FormData(e.target)),button=e.target.querySelector('button[type=submit]');button.disabled=true;
|
|
try{const note={mapID:data.mapID,characterID:leg.characterID,fromSceneID:leg.fromSceneID,toSceneID:leg.toSceneID,routeFeatureID:values.routeFeatureID||null,travelMethod:values.travelMethod||null,typicalMinutes:values.typicalMinutes?Number(values.typicalMinutes):null};
|
|
const response=await fetch(`/Maps/Journey?projectId=${boot.projectId}${data.scenarioID?'&scenarioId='+data.scenarioID:''}`,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':document.querySelector('input[name="__RequestVerificationToken"]').value},body:JSON.stringify(note)});
|
|
if(!response.ok||response.redirected)throw Error('Travel context could not be saved. Check access/subscription, then try again.');await load(true);
|
|
}catch(error){const message=document.createElement('p');message.setAttribute('role','alert');message.textContent=error.message;e.target.append(message);}finally{button.disabled=false;}
|
|
});
|
|
const sceneExplorer = window.PlotDirectorSceneExplorer.create({focusAdapter:false,host:$('mapStoryScrubberRow'),
|
|
positions:()=>visibleScenes().map(s=>({id:s.sceneID,label:sceneLabel(s)})),selected:()=>state.sceneID,
|
|
change:p=>chooseScene(Number(p.id)),select:$('mapStoryScene'),range:$('mapStoryScrubber'),
|
|
previous:$('mapStoryPrevious'),next:$('mapStoryNext'),output:$('mapStoryScrubberContext'),
|
|
listenSelect:false,listenButtons:false,enabled:()=>active()&&!!data&&state.lens==='scene'});
|
|
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.projectID===Number(boot.projectId)&&!!focus.sceneID,go:async focus=>{if(W.dirty||W.busy||window.PlotDirectorMapAppearance?.adjusting||svg.classList.contains('placing'))throw Error('Finish or save the current map edit before displaying Current Focus.');W.setMode('story');if(W.mode!=='story')throw Error('Finish the current map operation before displaying Current Focus.');await load();if(!data)throw Error(error||'Story data could not be loaded. Your local map position is retained.');if(!scenes.has(focus.sceneID))throw Error('The focused scene is not available on this map or scenario. Your map filters and journey context are retained.');if(!E.filterScenes(data,{...state,lens:'scene',bookID:focus.bookID}).some(s=>s.sceneID===focus.sceneID))throw Error('Current Focus is hidden by the map mapping or planning filters. Adjust those local filters to reveal it; their values have been retained.');state.lens='scene';state.visible=true;state.bookID=focus.bookID;state.chapterID=0;state.sceneID=focus.sceneID;$('mapStoryLens').value='scene';$('mapStoryBook').value=String(focus.bookID);$('mapStorySceneSearch').value='';controls();scopeOptions();chooseScene(focus.sceneID);if(!E.mapped(scenes.get(focus.sceneID).position))throw Error('Current Focus is selected, but this scene has no verified position on this map. The scene details remain available.');}});
|
|
$('mapStoryCoverage').onclick=()=>{state.selection={kind:'gaps'};renderDetails();};
|
|
$('mapStoryPrevious').onclick=()=>navigateStep(-1);$('mapStoryNext').onclick=()=>navigateStep(1);$('mapStoryLayer').onclick=()=>{state.visible=!state.visible;refresh();};$('mapStoryGaps').onclick=()=>{state.selection={kind:'gaps'};renderDetails();document.querySelector('#mapsStoryToolbar details').open=false;};$('mapStoryObservations').onclick=()=>{state.selection={kind:'observations'};renderDetails();document.querySelector('#mapsStoryToolbar details').open=false;};$('mapStoryRefresh').onclick=()=>load(true);
|
|
window.addEventListener('pd-map-saved',()=>{requestVersion++;loadRequest=null;data=null;loading=false;error='';});
|
|
window.addEventListener('pd-map-mode',e=>{controls();if(e.detail==='story')load();else refresh();});
|
|
window.addEventListener('pageshow',e=>{if(e.persisted&&active())load(true);});
|
|
window.PlotDirectorStoryOverlay={redraw,details:renderDetails,floorPlanURL,get data(){return data;},get state(){return state;},refresh:()=>load(true),chooseScene};
|
|
// Map windows own their mode, selection, and story filters independently.
|
|
controls();if(new URLSearchParams(location.search).get('mode')==='story')W.setMode('story');
|
|
})();
|