72 lines
20 KiB
JavaScript
72 lines
20 KiB
JavaScript
(() => {
|
||
'use strict';const saved=new Map(),mounted=new WeakMap(),NS='http://www.w3.org/2000/svg',layoutEngine=window.PlotDirectorContextRelationshipLayout;
|
||
const svgEl=(tag,attrs={},text)=>{const n=document.createElementNS(NS,tag);for(const [k,v]of Object.entries(attrs))n.setAttribute(k,String(v));if(text!=null)n.textContent=text;return n;};
|
||
const html=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;};
|
||
const colours={'Family':'#976512','Friendship':'#2d805c','Hostile / Conflict':'#b94a48','Romantic / Sexual':'#9957a7','Professional / Social':'#397ba2','Other':'#767676'};
|
||
const familyColours={parent:'#6b727a',biological:'#397ba2',adoptive:'#2d805c',step:'#a16b27',partner:'#9957a7',sibling:'#777',half:'#a16b27',other:'#777'};
|
||
function fresh(){return {focusID:null,follow:true,depth:3,x:0,y:0,scale:1,selected:null,initialised:false,signature:null,layout:null};}
|
||
function mount(node,{paneId}){
|
||
const host=node.querySelector('[data-context-relationships]');if(!host)return;const abort=new AbortController(),signal=abort.signal,svg=host.querySelector('[data-relationship-svg]'),viewport=svg.querySelector('[data-relationship-viewport]'),status=host.querySelector('[data-relationship-status]'),details=host.querySelector('[data-relationship-details]');
|
||
const prior=saved.get(paneId),state={paneId,host,node,abort,lens:prior?.lens||'family',views:prior?.views||{family:fresh(),story:fresh()},cache:{},data:null,loading:null,epoch:0};mounted.set(node,state);
|
||
if(state.views.family.follow)state.views.family.focusID=Number(host.dataset.pov)||null;if(!prior||prior.scene!==Number(host.dataset.scene)){if(state.views.story.follow)state.views.story.focusID=null;state.views.story.initialised=false;}
|
||
const listen=(target,event,fn,options={})=>target.addEventListener(event,fn,{...options,signal});let graphRequest,lookupRequest,lookupTimer;
|
||
const view=()=>state.views[state.lens];
|
||
const transform=()=>{const v=view();viewport.setAttribute('transform',`translate(${v.x} ${v.y}) scale(${v.scale})`);};
|
||
function centre(id){const v=view(),p=v.layout?.positions[id||state.data?.focusID];if(!p)return;const box=svg.getBoundingClientRect();v.x=box.width/2-(p.x+90)*v.scale;v.y=box.height/2-(p.y+33)*v.scale;v.initialised=true;transform();}
|
||
function zoom(factor,cx,cy){const v=view(),box=svg.getBoundingClientRect();cx??=box.width/2;cy??=box.height/2;const next=Math.max(.4,Math.min(3,v.scale*factor));v.x=cx-(cx-v.x)*next/v.scale;v.y=cy-(cy-v.y)*next/v.scale;v.scale=next;transform();}
|
||
function button(text,action){const n=html('button',text,'btn btn-outline-secondary btn-sm');n.type='button';listen(n,'click',action);return n;}
|
||
function editorLink(link){const a=html('a','Open in Relationships Editor');a.href='/RelationshipMap?bookId='+host.dataset.book;a.target='_blank';a.rel='noopener';a.dataset.contextWorkspaceTarget='relationships';if(link)a.dataset.contextEntity=link.id;if(state.lens==='family')a.dataset.contextNarrative='author';if(link?.editSceneID&&!link.initial)a.dataset.contextOpenScene=link.editSceneID;return a;}
|
||
function highlights(){const selected=view().selected;viewport.querySelectorAll('[data-graph-node]').forEach(n=>{const on=selected?.kind==='node'&&Number(n.dataset.graphNode)===selected.id;n.classList.toggle('is-selected',on);n.setAttribute('aria-pressed',String(on));});viewport.querySelectorAll('[data-graph-edge]').forEach(n=>{const link=state.data.links.find(l=>l.id===Number(n.dataset.graphEdge));const active=!selected||selected.kind==='link'&&selected.id===link.id||selected.kind==='node'&&(link.a===selected.id||link.b===selected.id);n.style.opacity=active?'1':state.lens==='family'?'.8':'.16';n.classList.toggle('is-selected',selected?.kind==='link'&&selected.id===link.id);n.querySelector('[data-graph-connection]')?.setAttribute('pointer-events',state.lens==='story'&&!active?'none':'stroke');});}
|
||
function describe(){details.replaceChildren();const selected=view().selected,data=state.data;if(!data)return;
|
||
if(selected?.kind==='link'){const link=data.links.find(l=>l.id===selected.id);if(!link){view().selected=null;return describe();}const a=data.nodes.find(n=>n.id===link.a),b=data.nodes.find(n=>n.id===link.b);details.append(html('h3',`${a?.name||'Recorded identity'} ${link.reciprocal?'↔':'→'} ${b?.name||'Recorded identity'}`,'h6'),html('p',`${link.category} · ${link.type} · ${link.state}`));
|
||
if(link.endSceneID)details.append(html('p','An ending is recorded. Historical and biological connections are not erased.','small'));if(link.notes)details.append(html('p',link.notes));
|
||
details.append(html('p','Recorded author reference. This does not prove a first meeting, mutual trust or viewpoint knowledge.','small'));
|
||
if(link.recent.length){const list=html('ul');for(const change of link.recent){const li=html('li',`${change.label} · ${change.stateName}${change.notes?' · '+change.notes:''}`);if(change.sceneID){const source=html('a',' Source scene');source.href='/Scenes/Edit/'+change.sceneID;source.target='_blank';source.rel='noopener';source.dataset.contextWorkspaceTarget='scene';source.dataset.contextEntity=change.sceneID;li.append(source);}list.append(li);}details.append(list);}
|
||
if(data.canEdit&&(state.lens==='story'||link.initial||link.editSceneID)){const edit=button(state.lens==='family'?(link.initial?'Correct initial family connection':'Correct recorded source development'):'Record / correct this scene’s development',()=>{});edit.dataset.contextRelationshipEdit=state.lens==='family'&&link.initial?'initial':'scene';edit.dataset.relationshipReference=state.lens;edit.dataset.relationshipId=link.id;if(state.lens==='family'&&link.editSceneID)edit.dataset.contextEditScene=link.editSceneID;details.append(edit);}
|
||
else if(data.canEdit&&state.lens==='family')details.append(html('p','This development belongs to another book; use the full editor to select its source.','small'));
|
||
details.append(editorLink(link));
|
||
}else{const person=data.nodes.find(n=>n.id===(selected?.id||data.focusID));if(!person){details.append(html('p','No canonical characters are available for this view.'));return;}view().selected={kind:'node',id:person.id};details.append(html('h3',person.name,'h6'));if(person.birthDate)details.append(html('p','Recorded birth date: '+person.birthDate.slice(0,10),'small'));if(person.archived)details.append(html('p','Archived identity. Archival is not evidence of death.','small'));details.append(html('p',person.physical?'Recorded as physically participating in this scene.':'Physical participation is not established by this diagram.','small'));
|
||
if(state.lens==='family'){details.append(html('p',`Life status: ${person.isDeceased===true?'Deceased':person.isDeceased===false?'Living':'Unrecorded'} · global author reference. No death scene or viewpoint knowledge is implied.`,'small'));if(data.canEdit){const edit=button('Correct life status',()=>{});edit.dataset.contextEdit='life-status';edit.dataset.characterId=person.id;details.append(edit);}}
|
||
details.append(button('Centre tree / network on this person',()=>{view().focusID=person.id;view().follow=false;view().initialised=false;void state.load(true);}));const focus=button('Focus in Characters',()=>focus.dispatchEvent(new CustomEvent('context-command',{bubbles:true,detail:{action:'character.focus',characterID:person.id}})));details.append(focus);
|
||
const connections=data.links.filter(l=>l.a===person.id||l.b===person.id);if(connections.length){const disclosure=html('details'),summary=html('summary',`Recorded connections (${connections.length})`),list=html('div',null,'context-edit-actions');disclosure.append(summary,list);for(const link of connections.slice(0,12)){const other=data.nodes.find(n=>n.id===(link.a===person.id?link.b:link.a));const inspect=button(`${link.type} · ${other?.name||'Recorded identity'} · ${link.state}`,()=>select('link',link.id));inspect.dataset.inspectConnection=link.id;list.append(inspect);}if(connections.length>12)list.append(html('p','Showing 12 connections; use the full editor for the complete set.','small'));details.append(disclosure);}
|
||
const a=html('a','Open character workspace');a.href='/Characters/Details/'+person.id;a.target='_blank';a.rel='noopener';a.dataset.contextWorkspaceTarget='characters';a.dataset.contextEntity=person.id;details.append(a);
|
||
}highlights();
|
||
}
|
||
function select(kind,id){view().selected={kind,id};describe();}
|
||
function render(){const data=state.data,v=view();viewport.replaceChildren();const key=layoutEngine.signature(data.nodes,data.links)+(state.lens==='story'?':'+data.focusID+':'+data.nodes.map(n=>n.physical).join(','):'');
|
||
if(v.signature!==key||!v.layout){v.layout=state.lens==='family'?layoutEngine.family(data.nodes,data.links):layoutEngine.story(data.nodes,data.links,data.focusID);v.signature=key;v.initialised=false;}
|
||
const layout=v.layout,defs=svgEl('defs'),markerID='pd-context-arrow-'+paneId+'-'+crypto.randomUUID();const marker=svgEl('marker',{id:markerID,markerWidth:9,markerHeight:9,refX:8,refY:4.5,orient:'auto-start-reverse',markerUnits:'userSpaceOnUse'});marker.append(svgEl('path',{d:'M 0 0 L 9 4.5 L 0 9 Z',fill:'context-stroke'}));defs.append(marker);viewport.append(defs);
|
||
const edgeGroup=svgEl('g'),nodeGroup=svgEl('g');viewport.append(edgeGroup,nodeGroup);
|
||
for(const route of layout.routes){const link=data.links.find(l=>l.id===route.id),colour=state.lens==='family'?familyColours[route.kind]||familyColours.other:colours[link.category]||colours.Other,group=svgEl('g',{'data-graph-edge':link.id});let d=route.d;
|
||
if(state.lens==='story'){const a=layout.positions[link.a],b=layout.positions[link.b],dx=b.x-a.x,dy=b.y-a.y,t=1/Math.max(Math.abs(dx)/90,Math.abs(dy)/33);d=`M ${a.x+90+dx*t} ${a.y+33+dy*t} L ${b.x+90-dx*t} ${b.y+33-dy*t}`;}
|
||
const line=svgEl('path',{d,fill:'none',stroke:colour,'stroke-width':2,'aria-hidden':'true','pointer-events':'none'});if(['adoptive','step','half','other'].includes(route.kind))line.setAttribute('stroke-dasharray',route.kind==='step'?'2 5':'7 4');if(link.endSceneID&&state.lens==='family')line.setAttribute('stroke-dasharray','8 4');if(state.lens==='story'){line.setAttribute('marker-end',`url(#${markerID})`);if(link.reciprocal)line.setAttribute('marker-start',`url(#${markerID})`);}group.append(line);
|
||
const a=data.nodes.find(n=>n.id===link.a),b=data.nodes.find(n=>n.id===link.b),hit=svgEl('path',{d,fill:'none',stroke:'transparent','stroke-width':16,role:'button',tabindex:0,'data-graph-connection':link.id,'aria-label':`${a?.name} ${link.type} ${b?.name}; ${link.state}`});hit.append(svgEl('title',{},`${link.type} · ${link.state}`));listen(hit,'click',()=>select('link',link.id));listen(hit,'keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();select('link',link.id);details.focus();}});group.append(hit);edgeGroup.append(group);
|
||
}
|
||
for(const n of data.nodes){const p=layout.positions[n.id];if(!p)continue;const g=svgEl('g',{transform:`translate(${p.x} ${p.y})`,role:'button',tabindex:0,'data-graph-node':n.id,'aria-label':`${n.name}${n.physical?', recorded scene presence':''}${n.archived?', archived identity':''}${state.lens==='family'&&n.isDeceased===true?', deceased; author reference':''}`});g.append(svgEl('title',{},n.name),svgEl('rect',{width:180,height:66,rx:9,class:n.physical?'is-physical':''}));
|
||
const words=n.name.split(/\s+/),lines=[''];for(const word of words){const i=lines.length-1;if((lines[i]+' '+word).trim().length>23&&i===0)lines.push(word);else lines[i]=(lines[i]+' '+word).trim();}if(lines[1]?.length>23)lines[1]=lines[1].slice(0,21)+'…';if(lines[0].length>23)lines[0]=lines[0].slice(0,21)+'…';
|
||
lines.slice(0,2).forEach((text,i)=>g.append(svgEl('text',{x:10,y:20+i*17,class:'context-graph-name'},text)));g.append(svgEl('text',{x:10,y:57,class:'context-graph-meta'},`${n.id===data.povID?'POV · ':''}${state.lens==='family'&&n.isDeceased===true?'† Deceased · ':state.lens==='family'&&n.isDeceased===false?'Living · ':''}${n.archived?'Archived':n.physical?'Scene presence':'Recorded identity'}`));listen(g,'click',()=>select('node',n.id));listen(g,'keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();select('node',n.id);details.focus();}});nodeGroup.append(g);
|
||
}
|
||
const legend=host.querySelector('[data-relationship-legend]');legend.replaceChildren();const entries=state.lens==='family'?[['Parent / unspecified','parent'],['Biological','biological'],['Adoptive (dashed)','adoptive'],['Step (dotted)','step'],['Partner / spouse','partner'],['Sibling / half-sibling','sibling'],['Other recorded connection','other']]:[...new Set(data.links.map(l=>l.category))].map(c=>[c,c]);for(const [label,key]of entries){const item=html('span',label);item.style.setProperty('--connection-colour',state.lens==='family'?familyColours[key]:colours[key]||colours.Other);legend.append(item);}
|
||
host.querySelector('[data-relationship-caption]').textContent=state.lens==='family'?'Author-established family structure across story points, independent of viewpoint knowledge. Select a person or connection to inspect.':'Author reference at this scene; recorded physical participants first. Later developments are excluded. Select a connection for established details, without inferred meetings or viewpoint knowledge.';
|
||
host.querySelector('[data-graph-expand]').hidden=state.lens!=='family';host.querySelector('[data-graph-expand]').disabled=v.depth>=6;host.querySelector('[data-graph-range]').textContent=state.lens==='family'?`Up to ${v.depth} recorded links from focus · 128-person limit`:'Selected scene · up to 256 connections';
|
||
const add=host.querySelector('[data-relationship-add]');if(add){add.hidden=!data.canEdit;add.textContent=state.lens==='family'?'Add one family connection':'Add one scene relationship';add.dataset.contextRelationshipEdit=state.lens==='family'?'initial':'scene';add.dataset.relationshipReference=state.lens;}
|
||
status.textContent=[!data.links.length?(state.lens==='family'?'No family connections recorded for this focus.':'No relationship is established for these characters at this point.'):null,data.truncated?'More recorded connections lie outside this view. Expand or centre another person.':null,...layout.warnings].filter(Boolean).join(' ');
|
||
const full=host.querySelector('[data-relationship-editor]');full.dataset.contextNarrative=state.lens==='family'?'author':'scene';
|
||
if(!v.initialised)centre(data.focusID);else transform();describe();
|
||
}
|
||
async function load(force=false){const epoch=++state.epoch;graphRequest?.abort();graphRequest=new AbortController();const lens=state.lens,v=view();host.querySelectorAll('[data-relationship-lens]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.relationshipLens===lens)));if(!force&&state.cache[lens]){state.data=state.cache[lens];render();return;}status.textContent='Loading recorded relationships…';svg.setAttribute('aria-busy','true');
|
||
const params=new URLSearchParams({bookId:host.dataset.book,sceneId:host.dataset.scene,lens,depth:v.depth});if(v.focusID)params.set('focusId',v.focusID);
|
||
try{const response=await fetch('/Writing/Context/Relationships/Graph?'+params,{cache:'no-store',signal:AbortSignal.any([signal,graphRequest.signal,AbortSignal.timeout(20000)])});if(!response.ok||response.redirected)throw Error('Relationship reference is unavailable. Check book access and retry.');const data=await response.json();if(epoch!==state.epoch||!node.isConnected)return;state.data=data;state.cache[lens]=data;render();}
|
||
catch(error){if(error.name!=='AbortError'&&epoch===state.epoch)status.textContent=error.message;}finally{if(epoch===state.epoch)svg.removeAttribute('aria-busy');}
|
||
}
|
||
state.load=force=>state.loading=load(force);state.select=select;
|
||
listen(host,'click',e=>{const lens=e.target.closest('[data-relationship-lens]');if(lens&&state.lens!==lens.dataset.relationshipLens){state.lens=lens.dataset.relationshipLens;void state.load();}});
|
||
listen(host.querySelector('[data-relationship-pov]'),'click',()=>{view().focusID=Number(host.dataset.pov)||null;view().selected=view().focusID?{kind:'node',id:view().focusID}:null;view().follow=true;view().initialised=false;void state.load(true);});listen(host.querySelector('[data-graph-expand]'),'click',()=>{view().depth=Math.min(6,view().depth+1);void state.load(true);});listen(host.querySelector('[data-graph-centre]'),'click',()=>centre(view().selected?.kind==='node'?view().selected.id:state.data?.focusID));for(const b of host.querySelectorAll('[data-graph-zoom]'))listen(b,'click',()=>zoom(b.dataset.graphZoom==='in'?1.2:1/1.2));
|
||
const pointers=new Map();let drag;listen(svg,'pointerdown',e=>{if(e.target.closest('[data-graph-node],[data-graph-connection]'))return;svg.setPointerCapture(e.pointerId);pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={x:e.clientX,y:e.clientY};e.preventDefault();});listen(svg,'pointermove',e=>{if(!pointers.has(e.pointerId))return;const before=[...pointers.values()];pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});const after=[...pointers.values()];if(after.length===2&&before.length===2){const old=Math.hypot(before[0].x-before[1].x,before[0].y-before[1].y),now=Math.hypot(after[0].x-after[1].x,after[0].y-after[1].y),box=svg.getBoundingClientRect();if(old>0)zoom(now/old,(after[0].x+after[1].x)/2-box.left,(after[0].y+after[1].y)/2-box.top);}else if(drag){view().x+=e.clientX-drag.x;view().y+=e.clientY-drag.y;transform();}drag={x:e.clientX,y:e.clientY};});for(const type of ['pointerup','pointercancel','lostpointercapture'])listen(svg,type,e=>{pointers.delete(e.pointerId);drag=null;});
|
||
listen(svg,'wheel',e=>{if(!e.ctrlKey&&!e.metaKey&&document.activeElement!==svg)return;e.preventDefault();const box=svg.getBoundingClientRect();zoom(e.deltaY<0?1.1:1/1.1,e.clientX-box.left,e.clientY-box.top);},{passive:false});listen(svg,'keydown',e=>{if(e.target!==svg)return;if(['+','=','-','Home','ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(e.key))e.preventDefault();if(e.key==='+'||e.key==='=')zoom(1.2);else if(e.key==='-')zoom(1/1.2);else if(e.key==='Home')centre(state.data?.focusID);else if(e.key.startsWith('Arrow')){view().x+=e.key==='ArrowLeft'?40:e.key==='ArrowRight'?-40:0;view().y+=e.key==='ArrowUp'?40:e.key==='ArrowDown'?-40:0;transform();}});
|
||
listen(host.querySelector('[data-relationship-person]'),'input',e=>{clearTimeout(lookupTimer);lookupRequest?.abort();const value=e.target.value.trim(),box=host.querySelector('[data-relationship-matches]');box.replaceChildren();if(value.length<2)return;lookupTimer=setTimeout(async()=>{lookupRequest=new AbortController();try{const response=await fetch('/Writing/Context/Relationships/Lookup?'+new URLSearchParams({bookId:host.dataset.book,sceneId:host.dataset.scene,search:value}),{cache:'no-store',signal:AbortSignal.any([signal,lookupRequest.signal])});if(!response.ok||response.redirected)throw Error();const rows=await response.json();box.replaceChildren();for(const row of rows)box.append(button(row.name+(row.archived?' · archived':''),()=>{view().focusID=row.id;view().selected={kind:'node',id:row.id};view().follow=false;view().initialised=false;box.replaceChildren();void state.load(true);}));if(!rows.length)box.textContent='No matching canonical identity or alias.';}catch(error){if(error.name!=='AbortError')box.textContent='Character lookup is unavailable.';}},250);});
|
||
signal.addEventListener('abort',()=>{graphRequest?.abort();lookupRequest?.abort();clearTimeout(lookupTimer);},{once:true});void state.load();
|
||
}
|
||
window.PlotDirectorContextLifecycles.relationships={mount,dispose(node){const state=mounted.get(node);if(!state)return;saved.set(state.paneId,{lens:state.lens,views:state.views,scene:Number(state.host.dataset.scene)});state.abort.abort();mounted.delete(node);},async onInteraction(node,command){const state=mounted.get(node);if(!state||command.action!=='relationship.focus'||command.storyPoint?.sceneID&&command.storyPoint.sceneID!==Number(state.host.dataset.scene))return 'not-visible';await state.loading;if(!state.data?.links.some(l=>l.id===command.relationshipID)){state.lens='story';await state.load(true);}if(!state.data?.links.some(l=>l.id===command.relationshipID))return 'not-visible';state.select('link',command.relationshipID);state.host.querySelector('[data-relationship-details]').focus();return 'focused';}};
|
||
})();
|