PlotDirector/PlotLine/wwwroot/js/context-relationships.js

118 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(() => {
'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 previous=saved.get(paneId),prior=previous?.book===Number(host.dataset.book)?previous:null,state={paneId,host,node,abort,lens:prior?.lens||'family',views:prior?.views||{family:fresh(),story:fresh()},cache:{},data:null,loading:null,epoch:0,families:new Map(prior?.families||[]),familyKey:prior?.scene===Number(host.dataset.scene)?prior?.familyKey:null,index:null,branches:[],familyWarnings:[],newScene:!prior||prior.scene!==Number(host.dataset.scene)};mounted.set(node,state);
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 familyView(key,focus,reset=false){
state.familyKey=key;let v=state.families.get(key);if(!v){v={...fresh(),expanded:[]};v.focusID=focus;state.families.set(key,v);}if(reset){const changed=v.focusID!==focus;v.focusID=focus;v.selected={kind:'node',id:focus};if(changed)v.initialised=false;}
state.families.delete(key);state.families.set(key,v);while(state.families.size>12)state.families.delete(state.families.keys().next().value);state.views.family=v;return v;
}
function familyIndex(){const box=host.querySelector('[data-family-index]');box.hidden=state.lens!=='family';box.replaceChildren();if(box.hidden||!state.index)return;
const groups=[...state.index.groups];if(state.familyKey!=null&&!groups.some(g=>g.key===state.familyKey)&&state.data?.lens==='family'){const focus=state.data.nodes.find(n=>n.id===view().focusID);if(focus)groups.push({key:state.familyKey,focusID:focus.id,label:focus.name+' · explored family'});}
if(!groups.length){box.append(html('p','No physical participants or POV recorded. Find a character to explore their family.','small'));return;}
function choose(group){familyView(group.key,group.focusID);state.cache.family=null;void state.load();}
const tabs=html('div',null,'context-family-tabs context-edit-actions');tabs.setAttribute('role','group');tabs.setAttribute('aria-label','Families');const more=html('details'),summary=html('summary','More families'),rest=html('div');more.append(summary,rest);
for(const [i,g]of groups.entries()){const b=button(g.label,()=>choose(g));b.dataset.familyKey=g.key;b.setAttribute('aria-pressed',String(g.key===state.familyKey));b.title=g.label+(g.isPov?' · POV family':'');(i<3?tabs:rest).append(b);}if(groups.length>3)tabs.append(more);box.append(tabs);
const label=html('label','Family in this scene','context-family-compact'),select=html('select',null,'form-select');select.dataset.familySelect='';for(const g of groups){const option=html('option',g.label+(g.isPov?' · POV':''));option.value=g.key;option.selected=g.key===state.familyKey;select.append(option);}listen(select,'change',()=>choose(groups.find(g=>String(g.key)===select.value)));label.append(select);box.append(label);for(const warning of state.index.warnings)box.append(html('p',warning,'small context-family-warning'));
}
async function loadFamily(force,epoch,requestSignal,restored=false){
const read=async(path,params)=>{const response=await fetch('/Writing/Context/Relationships/'+path+'?'+params,{cache:'no-store',signal:requestSignal});if(!response.ok||response.redirected){const payload=await response.json().catch(()=>null),error=Error(payload?.message||'Family reference is unavailable. Check access and retry.');error.status=response.status;throw error;}return response.json();};
const common={bookId:host.dataset.book,sceneId:host.dataset.scene},refreshed=force||!state.index;if(refreshed)state.index=await read('FamilyIndex',new URLSearchParams(common));if(epoch!==state.epoch)return;
if(state.familyKey==null){const group=state.index.groups.find(g=>g.key===state.index.defaultKey);if(group)familyView(group.key,group.focusID,state.newScene);state.newScene=false;}
if(state.familyKey==null){state.data={lens:'family',focusID:null,povID:Number(host.dataset.pov)||null,canEdit:host.dataset.canEdit==='true',nodes:[],links:[],truncated:false};state.branches=[];state.familyWarnings=[];familyIndex();render();return;}
const v=view();if(!force&&state.cache.family?.familyKey===state.familyKey){const cached=state.cache.family;state.data=cached.graph;state.branches=cached.branches;state.familyWarnings=cached.warnings;familyIndex();render();return;}
const params=new URLSearchParams({...common,focusId:v.focusID});for(const id of v.expanded||[])params.append('expanded',id);
let result;try{result=await read('FamilyTree',params);}catch(error){if(refreshed&&error.status===400&&v.expanded?.length){v.expanded=[];params.delete('expanded');result=await read('FamilyTree',params);}else throw error;}if(epoch!==state.epoch||!node.isConnected)return;
// A membership edit may merge/split the component; retain this focus and reconcile its key.
const remembered=state.families.get(result.familyKey);
if(result.familyKey!==state.familyKey&&remembered&&remembered!==v&&!restored){const oldKey=state.familyKey;remembered.focusID=v.focusID;remembered.selected={kind:'node',id:v.focusID};remembered.initialised=false;state.views.family=remembered;state.familyKey=result.familyKey;state.families.delete(oldKey);state.families.delete(result.familyKey);state.families.set(result.familyKey,remembered);state.cache.family=null;return loadFamily(true,epoch,requestSignal,true);}
if(result.familyKey!==state.familyKey){state.families.delete(state.familyKey);state.familyKey=result.familyKey;state.families.set(result.familyKey,v);}
state.cache.family=result;state.data=result.graph;state.branches=result.branches;state.familyWarnings=result.warnings;familyIndex();render();
}
function familyFocus(id){const matching=state.index?.groups.find(g=>g.sceneMembers?.includes(id));const key=matching?.key??(state.data?.lens==='family'&&state.data.nodes.some(n=>n.id===id)?state.familyKey:id);familyView(key,id,true).initialised=false;state.cache.family=null;void state.load();}
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',()=>{if(state.lens==='family'){familyFocus(person.id);return;}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){const previous=v.layout;v.layout=state.lens==='family'?layoutEngine.family(data.nodes,data.links):layoutEngine.story(data.nodes,data.links,data.focusID);v.signature=key;if(state.lens==='family'&&previous&&v.initialised){const anchor=v.selected?.kind==='node'?v.selected.id:data.focusID,a=previous.positions[anchor],b=v.layout.positions[anchor];if(a&&b){v.x+=(a.x-b.x)*v.scale;v.y+=(a.y-b.y)*v.scale;}}else 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}`;}
if(state.lens==='family')group.append(svgEl('path',{d,fill:'none',stroke:'var(--plotline-panel,#fff)','stroke-width':6,'pointer-events':'none','aria-hidden':'true'}));
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(state.lens==='family'&&(link.endSceneID||['ex spouse','former spouse'].includes((link.type||'').toLowerCase().replaceAll('-',' '))||['divorced','ended'].includes((link.state||'').toLowerCase())))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);
}
if(state.lens==='family'){
for(const j of layout.junctions||[])edgeGroup.append(svgEl('circle',{cx:j.x,cy:j.y,r:3,fill:familyColours.parent,'pointer-events':'none','aria-hidden':'true'}));
for(const branch of state.branches){const p=layout.positions[branch.id],person=data.nodes.find(n=>n.id===branch.id);if(!p||!person)continue;const action=branch.expanded?'Collapse':'Expand',label=`${action} recorded relatives of ${person.name}${branch.expanded?'':`; ${branch.hidden} additional adjacent relatives`}`,g=svgEl('g',{transform:`translate(${p.x+183} ${p.y+19})`,class:'context-family-branch',role:'button',tabindex:0,'data-family-branch':branch.id,'aria-label':label,'aria-expanded':String(branch.expanded)});g.append(svgEl('title',{},label),svgEl('rect',{width:28,height:28,rx:7}),svgEl('text',{x:14,y:19,'text-anchor':'middle'},branch.expanded?'−':'+'));
const toggle=e=>{e.stopPropagation();const v=view();v.expanded||=[];if(branch.expanded)v.expanded=v.expanded.filter(id=>id!==branch.id);else if(v.expanded.length<64)v.expanded.push(branch.id);else{window.PlotDirector?.toast?.info('Collapse a branch before expanding another.');return;}state.cache.family=null;void state.load().then(()=>host.querySelector(`[data-family-branch="${branch.id}"]`)?.focus({preventScroll:true}));};listen(g,'click',toggle);listen(g,'keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle(e);}});viewport.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 (dashed: former / ended)','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=true;host.querySelector('[data-graph-expand]').disabled=v.depth>=6;host.querySelector('[data-graph-range]').textContent=state.lens==='family'?`${data.nodes.length} relatives / identities shown · use branch + / −`:'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?(state.lens==='family'?'View limit reached: 128 people or 256 connections. Centre another person or open the full editor.':'More recorded connections lie outside this view. Expand or centre another person.'):null,...(state.lens==='family'?state.familyWarnings:[]),...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.querySelector('[data-family-index]').hidden=lens!=='family';host.querySelectorAll('[data-relationship-lens]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.relationshipLens===lens)));if(lens!=='family'&&!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{if(lens==='family'){await loadFamily(force,epoch,AbortSignal.any([signal,graphRequest.signal,AbortSignal.timeout(20000)]));return;}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',()=>{if(state.lens==='family'){state.familyKey=null;state.newScene=true;state.cache.family=null;void state.load(true);return;}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,suppressFamilyClickUntil=0;
listen(svg,'click',e=>{if(state.lens==='family'&&performance.now()<suppressFamilyClickUntil&&!e.target.closest('[data-family-branch]')){e.preventDefault();e.stopPropagation();}},{capture:true});
listen(svg,'pointerdown',e=>{
if(e.target.closest('[data-family-branch]'))return;const interactive=!!e.target.closest('[data-graph-node],[data-graph-connection]');if(interactive&&state.lens!=='family')return;
if(!interactive)svg.setPointerCapture(e.pointerId);pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={x:e.clientX,y:e.clientY,waiting:interactive};if(!interactive)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);if(state.lens==='family')suppressFamilyClickUntil=performance.now()+500;}
else if(drag){if(drag.waiting&&Math.hypot(e.clientX-drag.x,e.clientY-drag.y)<7)return;if(drag.waiting){drag.waiting=false;svg.setPointerCapture(e.pointerId);}view().x+=e.clientX-drag.x;view().y+=e.clientY-drag.y;transform();if(state.lens==='family')suppressFamilyClickUntil=performance.now()+500;}
drag={x:e.clientX,y:e.clientY,waiting:false};
});
for(const type of ['pointerup','pointercancel','lostpointercapture'])listen(svg,type,e=>{if(type==='lostpointercapture'&&e.target!==svg)return;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':''),()=>{if(state.lens==='family'){box.replaceChildren();familyFocus(row.id);return;}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),book:Number(state.host.dataset.book),families:[...state.families],familyKey:state.familyKey});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';}};
})();