Redesign Context Family as scene-indexed genealogical trees with branches

This commit is contained in:
Nick Beckley 2026-11-22 20:04:52 +00:00
parent 467861718f
commit f357cbde81
20 changed files with 428 additions and 31 deletions

View File

@ -0,0 +1,61 @@
# Context Family tree redesign — 22 November 2026
Requested base: deployed `d955971`; repository evidence-only HEAD was `4678617`. Scope is the Context Family lens. The Story lens, main Relationships editor, canonical relationship types and manuscript records are preserved. Production is outside scope.
## Family identification and scene index
The index starts from explicit physical participants under existing canonical presence rules, plus the POV independently of presence. Mentioned Only overrides a contradictory presence label. Names/surnames, scene co-occurrence, residence, friendship, hostility and professional partnerships never establish membership.
New `ContextFamilyTopology` builds connected components over supported canonical parent/child, biological/adoptive/step parentage, recorded marriages/family partnerships, siblings/half-siblings and explicit aunt/uncle/niece/nephew/cousin links. Parent direction must be unambiguous. Iterative strong-component analysis excludes ancestry-cycle edges; descendants of a cycle are not automatically branded as cycles. Reciprocal parent/child, self-links, unknown type semantics and guardianship alone do not establish genealogy. Known unverified primary evidence for a relationship's establishing scene is excluded by the reader. Other canonical author-established relationships retain their existing authority; no verification field or knowledge engine is invented.
One entry represents each eligible connected family structure. Its key is the smallest canonical character ID in the component, and its label uses up to two recognisable scene characters, with POV first. Other entries sort predictably by label and ID. Explicit marriage can connect ancestral branches into a broader navigable family; actual parentage remains separately recorded and drawn. An individual with no qualifying relatives gets their own entry. Three compact buttons plus More are used where needed; panes narrower than 560px use a labelled selector.
Initial/new-scene selection prefers the POV family. Same-scene manual exploration survives notifications. Each pane is independent. A scene change resets the default family choice without recalculating an unchanged layout; if the same POV remains focused, pan/zoom need not reset. No new pinning system.
## Genealogical layout
The existing small deterministic SVG layout is extended, without a new graph library. Explicit directional ancestry establishes vertical generations; partners and recorded siblings align only where ancestry permits. Reliable birth dates order known siblings. Separate parental rails retain biological, adoptive and step semantics. Children attach beneath their actual recorded parent, or beneath an explicit recorded partnership when compatible parentage exists for both partners. Co-parentage alone creates no partner or union marker.
Multiple partnerships have separate rails and children keep their exact recorded parent links; half-siblings do not acquire each other's second parent. Single parents remain single. Ended/former partnerships remain visible with dashed status. Deceased and archived relatives remain visible; archival does not imply death. Global life status retains its existing author-reference label.
Orthogonal generation-gap buses and outer corridors for skipped generations avoid unrelated cards. A connector halo distinguishes crossings, and junction dots identify explicit parental unions. Unknown relatives/ancestry are never fabricated. Explicit kinship without enough parentage to place generations is shown with an explanatory warning. Structural signatures exclude notes/state-only changes; unchanged structures keep their cached deterministic layout. The graph retains readable 180×66 cards, pan/zoom and fixed text sizes.
## Compact branches and retained state
Initial visibility includes the focus, recorded adjacent relatives, siblings supported by common recorded parentage and nearby recorded partners. It does not load all generations into the browser. A node's + appears only when additional recorded adjacent relatives exist. Its accessible title gives an exact count of hidden adjacent relatives, not a speculative total descendant count. Expanding adds recorded neighbours; − removes that expansion. No expansion creates people or relationships, and it cannot open an editing modal.
Each tree request reauthorises book, scene, project and focus. Expansion IDs must belong to the selected component. If a membership edit makes previously saved expansion IDs obsolete, the refreshed index/tree reconciles the component and retries a compact tree. Concurrently changed returned records are rechecked so disconnected physical participants cannot remain in the selected tree. Branch changes preserve the selected person's screen position where practical.
Each pane retains at most 12 recently used family view states: focus, selection, up to 64 expanded nodes, pan, zoom and layout. Only the current Family data response and existing Story response are cached. A book change discards the previous book's family state. State is in-window lifecycle state, not unlimited persisted diagrams or a new cross-window messaging system.
Family gestures permit drag/pinch from cards or connectors after a movement threshold, preserving taps for selection and protecting branch controls. This addresses mobile touch target adjustment near cards. Story gesture semantics remain unchanged. Branch controls support touch, Enter and Space; SVG keyboard pan/zoom and the shared correction modals remain available.
## Services, queries and safety
`ContextRelationshipLenses.Scope`, canonical characters, existing narrative ordering, `RelationshipMapService.BuildAtScene` projection, verified evidence projection, existing focused relationship editing, shared `PlotDirector.toast`, Context invalidation and My Windows remain authoritative. No additional SignalR connection, name inference, new relationship category, inline application SQL or bulk canonical migration.
Forward migration **305_ContextFamilyExploration.sql** adds two read-only stored procedures. Structure returns only eligible seed names and at most 8,193 relationship metadata rows (the 8,193rd is a rejection sentinel). The server identifies components; it never sends the project membership graph to the browser. Tree returns at most 128 requested identities and 256 requested canonical links, with existing minimal narrative ordering metadata (20,000-item limit) and at most three verified developments per visible link through the existing event reader. Additional character details are fetched when a branch is expanded. No complete manuscript or relationship history is fetched for the tree. Very large metadata requests fail explicitly and retain a full-editor route rather than silently declaring incomplete families unrelated.
Development-only backup `context-family-20261122T194552Z.bak` succeeded with CHECKSUM and VERIFYONLY. Effective database was verified as `PlotDirector_Development`; only migration305 was applied. No canonical rows were changed by the migration. Backup verification is not claimed as a restore test. Original untracked investigation documents were preserved.
## Verification evidence
Isolated canonical fixtures cover separate families in one scene; actual siblings sharing an entry; biological versus adoptive parentage; single parents; exact half-sibling parentage; multiple marriages; step relations; isolated individuals; cyclic/ambiguous records; membership merge/split after editing; independent POV inclusion and mentioned-only exclusion. Service tests cover Viewer access, project/book isolation, selected-component-only snapshots and foreign branch rejection.
Browser interaction acceptance covers one family at a time, POV bias, More and compact selectors, branch +/−, keyboard activation, preserved family zoom/selection through notifications, obsolete expansion recovery after a split, regrouping after a merge, independent panes, new scene POV defaults, and eviction after 12 retained families. Responsive cases include full-width, half-width columns, stacked panes, 390px mobile and two simultaneous Relationships tools. Existing Family/Story browser regression retains exact Story scene-state, direction, focus and editing checks.
Layout assertions cover four generations, biological/adoptive/step styles, multiple partners, exact parentage, known birth order, no invented union for co-parents, no overlapping cards and orthogonal paths avoiding unrelated cards. Large/deep metadata fixtures exercise the bounded server selection and iterative ancestry traversal. Touch-emulated Chromium covers branch taps without editing, card selection, real CDP drag and pinch, zoom, lens switching and no document horizontal overflow. Physical-device/PWA installation is not claimed.
Additional real-manuscript acceptance used existing authorised Development data read-only: one eligible scene identity and scene-family entry, plus two additional recorded family components. Three deidentified snapshots contained ten visible identities and eight recorded connections, with no overlapping cards or invented identities. Canonical relationship checksums were unchanged before/after. No real manuscript relationship was edited. This is structural data acceptance, not author editorial approval of every family.
Final qualification: solution build succeeded with **zero warnings/errors**; full executable regression harness completed with **770 PASS lines and exit0**. This includes 21 new Family domain/access/performance assertions, existing Family/Story and focused-editing regressions, and the wider application harness. Broad/deep 4,096-edge metadata fixtures completed in 72ms on this host (an observed fixture result, not a database latency guarantee). Actual SVG connector hit selection, membership merge/split recovery and the 12-family state bound passed in the Family browser. Existing shared modal acceptance passed all nine character/name variants plus relationship forms; My Windows real-SignalR isolation/reconnect passed; shared notification and touch/gesture checks passed. No forced browser clicks or modal/authorisation bypasses.
Predeployment evidence: `/tmp/context-family-final-build2.log`, `/tmp/context-family-final-regression.log`, `/tmp/context-family-final-browser.log`, `/tmp/context-family-final-story-browser.log`, `/tmp/context-family-final-shared-browser.log`, `/tmp/context-family-final-windows-browser.log`, `/tmp/context-family-final-touch.log`, `/tmp/context-family-notifications.log`, `/tmp/context-family-readonly-final.log`. Deployment and live endpoint/editing evidence are recorded below after installation.
## Limits / future manual acceptance
- Explicit cousin/aunt/uncle and similar kinship without parentage cannot reliably establish missing ancestors or precise generations. The interface labels this limitation rather than inventing them.
- Ambiguous or unsupported records require correction in the existing Relationships Editor; excluded records are not used to merge index entries.
- Membership metadata is bounded at 8,192 project family records, a visible tree at 128 people/256 links and retained state at 12 families/64 expansions. Larger structures require recentering or the full editor; metadata beyond the hard limit needs future incremental membership infrastructure.
- Author-reference truth is independent of POV knowledge. No new viewpoint-knowledge, biological inference or first-meeting logic is provided.
- Physical phones/tablets, installed PWA windowing and screen-reader review remain manual acceptance. Editorial review of representative author-owned complex families is recommended; those records were not modified for testing.

View File

@ -0,0 +1,7 @@
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');const sandbox={window:{}};vm.runInNewContext(fs.readFileSync('PlotLine/wwwroot/js/context-relationship-layout.js','utf8'),sandbox);const engine=sandbox.window.PlotDirectorContextRelationshipLayout;
const nodes=Array.from({length:15},(_,i)=>({id:i+1,name:'Person '+(i+1),birthDate:i===6?'2000-01-01':i===7?'2002-01-01':null}));let seq=0;const links=[];function add(a,b,type,reciprocal=false){links.push({id:++seq,a,b,type,reciprocal});return seq;}
add(1,2,'Spouse',true);add(1,3,'Parent');add(2,3,'Parent');add(3,4,'Spouse',true);add(3,5,'Parent');add(4,5,'Parent');add(5,6,'Spouse',true);add(5,10,'Former spouse',true);add(5,7,'Biological Parent');add(6,7,'Biological Parent');add(5,8,'Parent');add(6,8,'Parent');add(5,9,'Parent');add(10,9,'Parent');add(11,7,'Adoptive Parent');add(12,7,'Step Parent');add(3,15,'Child');add(1,14,'Grandparent');add(13,14,'Cousin');
const layout=engine.family(nodes,links),p=layout.positions;assert(p[1].y<p[3].y&&p[3].y<p[5].y&&p[5].y<p[7].y);assert.equal(p[5].y,p[6].y);assert.equal(p[5].y,p[10].y);assert(p[7].x<p[8].x);assert(layout.junctions.length>0);assert(layout.routes.some(r=>r.kind==='adoptive'));assert(layout.routes.some(r=>r.kind==='step'));
// Orthogonal connectors may cross with a visual bridge, but must not enter an unrelated card.
for(const route of layout.routes){const edge=links.find(l=>l.id===route.id);let cursor={x:0,y:0};const parts=[...route.d.matchAll(/([MHV])\s*(-?[\d.]+)(?:\s+(-?[\d.]+))?/g)];for(const part of parts){const next=part[1]==='M'?{x:+part[2],y:+part[3]}:part[1]==='H'?{x:+part[2],y:cursor.y}:{x:cursor.x,y:+part[2]};if(part[1]!=='M')for(const n of nodes){if(n.id===edge.a||n.id===edge.b)continue;const rect=p[n.id],inside=cursor.x===next.x?cursor.x>rect.x+1&&cursor.x<rect.x+179&&Math.max(Math.min(cursor.y,next.y),rect.y+1)<Math.min(Math.max(cursor.y,next.y),rect.y+65):cursor.y>rect.y+1&&cursor.y<rect.y+65&&Math.max(Math.min(cursor.x,next.x),rect.x+1)<Math.min(Math.max(cursor.x,next.x),rect.x+179);assert(!inside,`edge ${edge.id} crosses unrelated card ${n.id}`);}cursor=next;}}
assert.equal(JSON.stringify(engine.family(nodes,links).positions),JSON.stringify(layout.positions));const lone=engine.family([{id:1,name:'One known parent'},{id:2,name:'Child'}],[{id:1,a:1,b:2,type:'Parent'}]);assert.equal(lone.junctions.length,0);const coParents=engine.family([{id:1},{id:2},{id:3}],[{id:1,a:1,b:3,type:'Biological Parent'},{id:2,a:2,b:3,type:'Adoptive Parent'}]);assert.equal(coParents.junctions.length,0);console.log('PASS genealogical layout: generations, recorded unions, exact half-sibling parentage, biological/adoptive/step styles, birth order, deterministic positions, single/co-parent records create no inferred union, orthogonal routes avoid unrelated cards.');

View File

@ -0,0 +1,8 @@
// Opt-in Development acceptance; only the explicitly disposable qualification characters may be edited.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),scope=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,scope.user);assert(who.Email.startsWith('pwa-browser-'));assert.equal(scope.characters.length,2);const b=await chromium.launch();let step='login';try{const pages=[],counts=[];for(let i=0;i<2;i++){const c=await b.newContext({viewport:{width:1366,height:1000}}),p=await c.newPage();await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]);const counter={hubs:0,word:0};counts.push(counter);p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))counter.hubs++;if(/\/(Writing\/Context|WriterWord)\/Navigate/.test(new URL(r.url()).pathname))counter.word++;});await p.goto('https://dev.plotdirector.com/Writing/Context?'+new URLSearchParams({projectId:scope.project,bookId:scope.book,sceneId:scope.scene}));await p.selectOption('[data-context-tab]','relationships');await p.locator('[data-family-key]').first().waitFor();await p.locator('[data-graph-node]').first().waitFor();await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');await p.evaluate(()=>{window.successes=0;const before=PlotDirector.toast.success;PlotDirector.toast.success=(...a)=>{successes++;before(...a);};});pages.push(p);}
const [p,remote]=pages;async function index(page){return page.evaluate(async args=>{const response=await fetch('/Writing/Context/Relationships/FamilyIndex?'+new URLSearchParams(args));if(!response.ok)throw Error('Index read failed');return response.json();},{bookId:scope.book,sceneId:scope.scene});}let current=await index(p);assert(scope.characters.every(id=>current.groups.some(g=>g.sceneMembers.includes(id))),'both qualification characters must be explicitly eligible scene participants');const merged=()=>current.groups.some(g=>scope.characters.every(id=>g.sceneMembers.includes(id)));
async function save(){await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}
if(!merged()){step='focused family connection groups two scene entries';await p.locator('[data-relationship-add]').click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(scope.characters[0]));await p.selectOption('[name=TargetID]',String(scope.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&/Parent/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);if(state)await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic family grouping qualification');await save();await remote.waitForFunction(()=>document.querySelectorAll('[data-family-key]').length===1);current=await index(p);assert(merged());}
step='focused family correction persists and refreshes quiet peer';for(const page of pages){await page.locator(`[data-graph-node="${scope.characters[0]}"]`).click();await page.locator('[data-relationship-details] details summary').click();await page.locator('[data-inspect-connection]').first().click();}await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');const note='Synthetic family source correction '+Date.now();await p.locator('[name=Notes]').fill(note);await save();await remote.waitForFunction(note=>document.querySelector('[data-relationship-details]').textContent.includes(note),note);assert.equal(await remote.evaluate(()=>successes),0);assert(await p.evaluate(()=>successes)>=1);assert(counts.every(c=>c.hubs===1&&c.word===0));assert.equal(await p.locator('[data-context-scene]').inputValue(),String(scope.scene));console.log('PASS Development Family editing: authorised scene index and one tree; focused canonical family add/inspection/correction, membership regrouping, persisted notes, quiet receiving window, one SignalR connection per Context, no Word navigation. Disposable qualification characters only.');
}catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,16 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});let merged=false,split=false,many=false,trees=0;for(const [route,fixture]of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{if(route==='FamilyTree')trees++;const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search+'&large=true&merge='+merged+'&many='+many+'&split='+split})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','relationships');const pane=p.locator('[data-context-pane="0"]');await pane.locator('[data-graph-node="5"]').waitFor();
const index=()=>pane.locator('[data-family-key]');const visibleIDs=()=>pane.locator('[data-graph-node]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.graphNode)));
step='scene family index and one tree';assert.equal(await index().count(),5);assert.equal(await pane.locator('[data-family-key][aria-pressed=true]').getAttribute('data-family-key'),'1');assert((await visibleIDs()).includes(8));assert(!(await visibleIDs()).includes(22));assert(!(await visibleIDs()).includes(25));assert(!(await visibleIDs()).includes(30));assert.equal(await pane.locator('[data-family-index] details').count(),1);await p.screenshot({path:'/tmp/context-family-initial-desktop.png',fullPage:true});
step='real genealogical connector inspection';await pane.locator('[data-relationship-svg]').scrollIntoViewIfNeeded();const point=await pane.locator('[data-graph-connection="7"]').evaluate(n=>{const p=n.getPointAtLength(n.getTotalLength()-12),m=n.getScreenCTM();return{x:m.a*p.x+m.c*p.y+m.e,y:m.b*p.x+m.d*p.y+m.f};});await p.mouse.click(point.x,point.y);await pane.locator('[data-graph-edge="7"].is-selected').waitFor({state:'attached'});assert.match(await pane.locator('[data-relationship-details]').innerText(),/Recorded person 3/);await pane.locator('[data-graph-node="5"]').click();
step='per-family view and unrelated notification stability';await pane.locator('[data-graph-zoom=in]').click();const zoom=await pane.locator('[data-relationship-viewport]').getAttribute('transform');await pane.locator('[data-family-key="21"]').click();await pane.locator('[data-graph-node="22"]').waitFor();assert(!(await visibleIDs()).includes(5));const before=trees;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-family-key="21"]')?.getAttribute('aria-pressed')==='true');await p.waitForTimeout(180);assert(trees>before);assert((await visibleIDs()).includes(22));await pane.locator('[data-family-key="1"]').click();await pane.locator('[data-graph-node="5"]').waitFor();assert.equal(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),zoom);
step='branch expand/collapse, exact recorded relatives and no edit';await pane.locator('[data-family-branch="3"]').click();await pane.locator('[data-graph-node="1"]').waitFor();assert.equal(await p.locator('[data-context-edit-dialog][open]').count(),0);await pane.locator('[data-family-branch="7"]').click();await pane.locator('[data-graph-node="11"]').waitFor();assert((await visibleIDs()).includes(12));assert((await visibleIDs()).includes(16));assert(!(await visibleIDs()).includes(100));assert.equal(await pane.locator('[data-family-branch="7"]').getAttribute('aria-expanded'),'true');await pane.locator('[data-family-branch="7"]').click();await p.waitForFunction(()=>!document.querySelector('[data-graph-node="11"]'));await pane.locator('[data-family-branch="3"]').focus();await p.keyboard.press('Enter');await p.waitForFunction(()=>!document.querySelector('[data-graph-node="1"]'));
step='split membership prunes obsolete expansions';await pane.locator('[data-family-branch="3"]').click();await pane.locator('[data-graph-node="1"]').waitFor();split=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-family-key="5"]')?.getAttribute('aria-pressed')==='true');assert(!(await visibleIDs()).includes(3));assert(!(await visibleIDs()).includes(15));split=false;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-family-key="1"]')?.getAttribute('aria-pressed')==='true');
step='isolated and cyclic entries';await pane.locator('[data-family-index] details summary').click();await pane.locator('[data-family-key="40"]').click();await pane.locator('[data-graph-node="40"]').waitFor();assert.deepEqual(await visibleIDs(),[40]);assert.match(await pane.locator('[data-relationship-status]').innerText(),/cyclic/);await pane.locator('[data-family-key="30"]').click();await pane.locator('[data-graph-node="30"]').waitFor();assert.deepEqual(await visibleIDs(),[30]);
step='independent family selection in two panes';await p.selectOption('[data-context-layout]','columns');await p.locator('[data-context-pane="1"] [data-context-tab]').selectOption('relationships');await p.locator('[data-context-pane="1"] [data-graph-node="5"]').waitFor();assert((await visibleIDs()).includes(30));await pane.locator('[data-family-key="21"]').click();await pane.locator('[data-graph-node="22"]').waitFor();assert.equal(await p.locator('[data-context-pane="1"] [data-family-key="1"]').getAttribute('aria-pressed'),'true');
step='new scene chooses new POV family';await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.locator('[data-context-pane="1"] [data-graph-node="22"]').waitFor();assert.equal(await p.locator('[data-context-pane="1"] [data-family-key="21"]').getAttribute('aria-pressed'),'true');
step='membership edit reconciles index';merged=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelectorAll('[data-context-pane="0"] [data-family-key]').length===4);assert.equal(await pane.locator('[data-family-key="1"]').getAttribute('aria-pressed'),'true');
step='full half stacked narrow compact selection';for(const width of [1366,760,390]){await p.setViewportSize({width,height:1000});for(const layout of ['single','columns','rows']){await p.selectOption('[data-context-layout]',layout);await p.waitForTimeout(60);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}await p.selectOption('[data-context-layout]','single');assert(await pane.locator('[data-family-select]').isVisible());assert.equal(await pane.locator('.context-family-tabs').isVisible(),false);await pane.locator('[data-family-select]').selectOption('30');await pane.locator('[data-graph-node="30"]').waitFor();await p.screenshot({path:'/tmp/context-family-mobile.png',fullPage:true});
step='bounded retained family views';await pane.locator('[data-graph-zoom=in]').click();assert.match(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),/scale\(1.2\)/);many=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelectorAll('[data-context-pane="0"] [data-family-select] option').length>12);for(const id of [31,32,33,34,35,36,37,38,39,42,43,44,45,46]){await pane.locator('[data-family-select]').selectOption(String(id));await pane.locator(`[data-graph-node="${id}"]`).waitFor();}await pane.locator('[data-family-select]').selectOption('30');await pane.locator('[data-graph-node="30"]').waitFor();assert.match(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),/scale\(1\)/);
assert.deepEqual(errors,[]);console.log('PASS Family browser: distinct scene groups, POV bias, one tree, individual/cycle safeguards, per-family zoom/selection, notifications, branch +/- and keyboard, exact ancestry/adoption/step nodes, independent panes, new scene POV, membership merge/split regrouping, real SVG connector inspection, More and compact selector, 12-family retained-state bound, full/half/stacked/mobile.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -8,7 +8,7 @@ const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('nod
async function save(){await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}
step='live canonical description and quiet remote refresh';await open('description');await p.locator('[name=Value]').fill(stamp);await save();await remote.waitForFunction(stamp=>document.querySelector('[data-character-explorer]').textContent.includes(stamp),stamp);assert.equal(await p.evaluate(()=>successes),1);assert.equal(await remote.evaluate(()=>successes),0);
step='canonical life-status persistence and lens separation';await open('life-status');const originalLife=await p.locator('[name=Value]').inputValue();await p.selectOption('[name=Value]','true');await save();await remote.waitForFunction(()=>document.querySelector('[data-character-explorer]').textContent.includes('Deceased'));
for(const lens of ['family','story']){const graph=await p.evaluate(async args=>{const response=await fetch('/Writing/Context/Relationships/Graph?'+new URLSearchParams(args));if(!response.ok)throw Error('Graph '+response.status);return response.json();},{bookId:s.book,sceneId:s.scene,focusId:id,lens});assert.equal(graph.nodes.find(n=>n.id===id).isDeceased,lens==='family'?true:null);}
for(const lens of ['family','story']){const graph=await p.evaluate(async args=>{const response=await fetch('/Writing/Context/Relationships/'+(args.lens==='family'?'FamilyTree':'Graph')+'?'+new URLSearchParams(args));if(!response.ok)throw Error('Graph '+response.status);const data=await response.json();return data.graph||data;},{bookId:s.book,sceneId:s.scene,focusId:id,lens});assert.equal(graph.nodes.find(n=>n.id===id).isDeceased,lens==='family'?true:null);}
await open('life-status');assert.equal(await p.locator('[name=Value]').inputValue(),'true');await p.selectOption('[name=Value]',originalLife);await save();
step='cancel persists nothing';await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.locator('[name=Value]').fill('Discarded synthetic draft');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.click('[data-context-edit-cancel]');
async function lookupIdentity(query){const details=p.locator('[data-established-names]');if(!await details.evaluate(n=>n.open))await details.locator('summary').first().click();await p.locator('[data-context-name-lookup] [name=search]').fill(query);await p.locator('[data-context-name-lookup] [type=submit]').click();await p.locator('[data-context-name-identities] [data-name-usage-fragment]').waitFor();await p.locator(`[data-context-name-identities] [data-name-identity="${id}"]`).click();await p.waitForSelector('[data-name-identity-fragment]');}

View File

@ -1,9 +1,9 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1280,height:900}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});
await c.route('**/Writing/Context/EditCharacter?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-edit-fixture?field='+u.searchParams.get('field')})});});await c.route('**/Writing/Context/EditRelationship?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})}));
await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');
await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search})});});for(const [route,fixture] of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');
step='all shared modal forms fill content';for(const width of [1280,390]){await p.setViewportSize({width,height:900});for(const field of ['life-status','classification','description','emotion','condition','location','name','alias-add','alias:11']){await p.evaluate(field=>{const host=document.querySelector('[data-character-explorer]'),button=document.createElement('button');button.dataset.contextEdit=field;button.dataset.characterId='5';host.append(button);button.click();button.remove();},field);await p.waitForSelector('[data-context-edit-form]');assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92&&n.scrollWidth<=n.clientWidth+2)));await p.keyboard.press('Escape');await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}}
step='relationship modal shares full-width layout';await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="9"]').click();await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);await p.keyboard.press('Escape');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');
step='relationship modal shares full-width layout';await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="10"]').click();await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);await p.keyboard.press('Escape');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');
step='main shell registers on existing native connection';const main=await c.newPage();let hubs=0;main.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))hubs++;});await main.goto(base+'/fixture?layout=full');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));assert.equal(hubs,1);
step='scene editor reuses main window with no popup';const originalPages=c.pages().length;await p.click('[data-context-editor]');await main.waitForURL(/\/Scenes\/Edit\/22/);assert.equal(c.pages().length,originalPages);assert.equal(await p.locator('[data-context-tab]').first().inputValue(),'characters');
step='repeat navigation retains one main window';await p.waitForTimeout(550);await main.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));await p.click('[data-context-editor]');await p.waitForTimeout(700);assert.equal(c.pages().length,originalPages);

View File

@ -1,11 +1,11 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:900}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});let graphReads=0,large=false,readOnly=false,editQuery;await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{graphReads++;const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search+'&large='+large+'&readonly='+readOnly})});});await c.route('**/Writing/Context/Relationships/Lookup?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-lenses-lookup-fixture'})}));await c.route('**/Writing/Context/EditRelationship?*',async r=>{editQuery=new URL(r.request().url()).searchParams;await r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-graph-node="5"]');
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:900}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});let graphReads=0,large=false,readOnly=false,editQuery;await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{graphReads++;const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search+'&large='+large+'&readonly='+readOnly})});});await c.route('**/Writing/Context/Relationships/Lookup?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-lenses-lookup-fixture'})}));await c.route('**/Writing/Context/EditRelationship?*',async r=>{editQuery=new URL(r.request().url()).searchParams;await r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})});});for(const [route,fixture] of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{const u=new URL(r.request().url());graphReads++;await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search+'&large='+large+'&readonly='+readOnly})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-graph-node="5"]');
async function selectEdge(id){await p.locator('[data-context-pane="0"] [data-relationship-svg]').scrollIntoViewIfNeeded();const hit=p.locator(`[data-context-pane="0"] [data-graph-connection="${id}"]`);const pt=await hit.evaluate(n=>{const p=n.getPointAtLength(n.getTotalLength()*.35),m=n.getScreenCTM();return {x:m.a*p.x+m.c*p.y+m.e,y:m.b*p.x+m.d*p.y+m.f};});await p.mouse.click(pt.x,pt.y);await p.locator(`[data-context-pane="0"] [data-graph-edge="${id}"].is-selected`).waitFor({state:'attached'});}
step='genealogical view and specific connection edit';assert.equal(await p.locator('[data-relationship-lens="family"]').getAttribute('aria-pressed'),'true');assert.equal(await p.locator('[data-graph-node]').count(),24);assert.match(await p.locator('[data-graph-node="6"]').getAttribute('aria-label'),/deceased; author reference/);assert.equal(await p.locator('[data-relationship-details] [data-context-edit="life-status"]').count(),1);assert.match(await p.locator('[data-relationship-caption]').innerText(),/Author-established/);await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="9"]').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Biological Parent'));await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert.equal(editQuery.get('referenceLens'),'family');assert.equal(editQuery.get('mode'),'initial');await p.click('[data-context-edit-cancel]');
step='genealogical view and specific connection edit';assert.equal(await p.locator('[data-relationship-lens="family"]').getAttribute('aria-pressed'),'true');assert.equal(await p.locator('[data-graph-node]').count(),9);assert.match(await p.locator('[data-graph-node="6"]').getAttribute('aria-label'),/deceased; author reference/);assert.equal(await p.locator('[data-relationship-details] [data-context-edit="life-status"]').count(),1);assert.match(await p.locator('[data-relationship-caption]').innerText(),/Author-established/);await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="10"]').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Biological Parent'));await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert.equal(editQuery.get('referenceLens'),'family');assert.equal(editQuery.get('mode'),'initial');await p.click('[data-context-edit-cancel]');
step='pan zoom and unchanged-family notification stability';await p.click('[data-graph-zoom="in"]');await p.locator('[data-relationship-svg]').focus();await p.keyboard.press('ArrowRight');const transform=await p.locator('[data-relationship-viewport]').getAttribute('transform');await p.evaluate(()=>{window.familyLayouts=0;const original=window.PlotDirectorContextRelationshipLayout.family;window.PlotDirectorContextRelationshipLayout.family=(...a)=>{familyLayouts++;return original(...a);};});const before=graphReads;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-graph-node="5"]'));await p.waitForTimeout(200);assert(graphReads>before);assert.equal(await p.evaluate(()=>familyLayouts),0);assert.equal(await p.locator('[data-relationship-viewport]').getAttribute('transform'),transform);
step='Story network and recorded point';await p.click('[data-relationship-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]').textContent.includes('Later developments are excluded'));assert(await p.locator('[data-graph-edge]').count()>30);assert.equal(await p.locator('[data-graph-node] rect.is-physical').count(),2);assert.equal(await p.locator('[data-relationship-details] [data-context-edit="life-status"]').count(),0);assert.doesNotMatch(await p.locator('[data-graph-node="6"]').getAttribute('aria-label'),/deceased/);await selectEdge(1);await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Rival'));assert.match(await p.locator('[data-relationship-details]').innerText(),/does not prove a first meeting/);await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.waitForFunction(()=>document.querySelector('[data-relationship-details]')?.textContent.includes('Later established'));await p.click('[data-relationship-lens="family"]');await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]').textContent.includes('Author-established'));assert.equal(await p.locator('[data-relationship-viewport]').getAttribute('transform'),transform);
step='lookup and recenter';await p.locator('[data-relationship-person]').fill('relative 7');await p.locator('[data-relationship-matches] button').waitFor();await p.locator('[data-relationship-matches] button').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('name 7'));
step='large family and independent panes';large=true;await p.click('[data-graph-expand]');await p.waitForFunction(()=>document.querySelectorAll('[data-graph-node]').length===120);await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','relationships');await p.locator('[data-context-pane="1"] [data-graph-node="5"]').waitFor();await p.locator('[data-context-pane="1"] [data-relationship-lens="story"]').click();await p.waitForTimeout(120);assert.equal(await p.locator('[data-context-pane="0"] [data-relationship-lens="family"]').getAttribute('aria-pressed'),'true');
step='Story network and recorded point';await p.click('[data-relationship-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]').textContent.includes('Later developments are excluded'));assert(await p.locator('[data-graph-edge]').count()>30);assert.equal(await p.locator('[data-graph-node] rect.is-physical').count(),2);assert.equal(await p.locator('[data-relationship-details] [data-context-edit="life-status"]').count(),0);assert.doesNotMatch(await p.locator('[data-graph-node="6"]').getAttribute('aria-label'),/deceased/);await selectEdge(1);await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Rival'));assert.match(await p.locator('[data-relationship-details]').innerText(),/does not prove a first meeting/);await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.waitForFunction(()=>document.querySelector('[data-relationship-details]')?.textContent.includes('Later established'));await p.click('[data-relationship-lens="family"]');await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]').textContent.includes('Author-established'));assert.equal(await p.locator('[data-family-key="21"]').getAttribute('aria-pressed'),'true');
step='lookup and recenter';await p.locator('[data-relationship-person]').fill('relative 7');await p.locator('[data-relationship-matches] button').waitFor();await p.locator('[data-relationship-matches] button').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Recorded person 7'));
step='large family and independent panes';large=true;await p.locator('[data-family-branch="5"]').click();await p.waitForSelector('[data-graph-node="3"]');await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','relationships');await p.locator('[data-context-pane="1"] [data-graph-node="22"]').waitFor();await p.locator('[data-context-pane="1"] [data-relationship-lens="story"]').click();await p.waitForTimeout(120);assert.equal(await p.locator('[data-context-pane="0"] [data-relationship-lens="family"]').getAttribute('aria-pressed'),'true');
step='container widths and keyboard navigation';for(const width of [1366,760,390]){await p.setViewportSize({width,height:900});for(const layout of ['single','columns','rows']){await p.selectOption('[data-context-layout]',layout);await p.waitForTimeout(50);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}await p.selectOption('[data-context-layout]','single');await p.locator('[data-context-pane="0"] [data-relationship-svg]').focus();await p.keyboard.press('Home');await p.keyboard.press('+');
step='read-only graph removes edit controls';readOnly=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForTimeout(350);assert.equal(await p.locator('[data-context-pane="0"] [data-relationship-add]:visible').count(),0);assert.deepEqual(errors,[]);console.log('PASS visual Relationships browser: Family and Story lenses, real SVG hit selection/edit, pan/zoom/keyboard, stable family layout through notifications, scene changes, lookup/recentre, 120-node family, dense network, independent panes, full/half/stacked/mobile and read-only controls.');
step='read-only graph removes edit controls';readOnly=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForTimeout(350);assert.equal(await p.locator('[data-context-pane="0"] [data-relationship-add]:visible').count(),0);assert.deepEqual(errors,[]);console.log('PASS visual Relationships browser: Family and Story lenses, real SVG hit selection/edit, pan/zoom/keyboard, stable family layout through notifications, scene changes, lookup/recentre, compact family branches, dense Story network, independent panes, full/half/stacked/mobile and read-only controls.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,58 @@
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.Context;
using PlotLine.Services;
using PlotLine.ViewModels;
internal static class ContextFamilyTests
{
internal static (ContextFamilyStructure Structure,SceneEditViewModel Scene) Fixture(bool large=false,int sceneID=22,bool many=false)
{
var people=Enumerable.Range(1,80).Concat(Enumerable.Range(100,large?120:0)).Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id switch{5=>"Scene viewpoint",15=>"Scene sibling",22=>"Other family participant",30=>"An individual",_=>"Recorded person "+id},BirthDate=id is 7 or 8?new(2000+(id-7)*2,1,1):null,IsArchived=id==6,IsDeceased=id==6?true:null}).ToList();
var links=new List<CharacterRelationship>();int sequence=0;
void Add(int a,int b,string type,bool reciprocal=false,string category="Family")=>links.Add(new(){CharacterRelationshipID=++sequence,ProjectID=7,CharacterAID=a,CharacterBID=b,RelationshipTypeName=type,RelationshipCategoryName=category,IsReciprocal=reciprocal,IsInitialRelationship=true});
Add(1,2,"Spouse",true,"Romantic / Sexual");Add(1,3,"Parent");Add(2,3,"Parent");Add(3,4,"Spouse",true,"Romantic / Sexual");Add(3,5,"Parent");Add(4,5,"Parent");Add(3,15,"Parent");Add(5,6,"Spouse",true,"Romantic / Sexual");Add(5,10,"Former spouse",true,"Romantic / Sexual");Add(5,7,"Biological Parent");Add(6,7,"Biological Parent");Add(5,8,"Parent");Add(6,8,"Parent");Add(5,9,"Parent");Add(10,9,"Parent");Add(7,9,"Half-sibling",true);Add(11,7,"Adoptive Parent");Add(12,7,"Step Parent");Add(7,16,"Parent");Add(16,17,"Parent");
Add(21,22,"Parent");Add(21,23,"Spouse",true,"Romantic / Sexual");Add(24,21,"Parent");Add(24,25,"Parent");
Add(40,41,"Parent");Add(41,40,"Parent");Add(50,51,"Parent",true);Add(60,61,"Guardian");Add(5,22,"Friend",true,"Friendship");Add(5,30,"Partner",true,"Professional / Social");
if(large)for(int id=100;id<220;id++)Add(id==100?17:100+(id-101)/2,id,"Parent");
var scene=new SceneEditViewModel{SceneID=sceneID,ChapterID=10,SceneTitle="Family exploration fixture",POVCharacterID=sceneID==23?22:5,SceneCharacters=[..new[]{5,15,22,30,40,41}.Select(id=>new SceneCharacter{CharacterID=id,PresenceTypeName="Present"}),new(){CharacterID=25,PresenceTypeName="Present",RoleInSceneTypeName="Mentioned Only"}]};
if(many)scene.SceneCharacters=[..scene.SceneCharacters,..new[]{31,32,33,34,35,36,37,38,39,42,43,44,45,46}.Select(id=>new SceneCharacter{CharacterID=id,PresenceTypeName="Present"})];
return(new(people,links),scene);
}
public static void Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Context family: "+message);}
var(data,scene)=Fixture(true);var topology=new ContextFamilyTopology(data.Links);var index=ContextFamilyExploration.Index(data,scene);
Check(index.Groups.First().IsPov&&index.DefaultKey==topology.Key(5),"POV family sorts first; scene co-occurrence does not group unrelated families");
Check(index.Groups.Single(g=>g.SceneMembers.Contains(5)).SceneMembers.Contains(15)&&topology.Key(5)!=topology.Key(22),"siblings and common recorded ancestry share one index entry; unrelated families remain separate");
Check(!index.Groups.Any(g=>g.SceneMembers.Contains(25))&&index.Groups.Single(g=>g.SceneMembers.Contains(30)).SceneMembers.Count==1,"mentioned-only is not physical; a person without genealogy remains an individual despite professional partnership");
Check(topology.Key(40)!=topology.Key(41)&&topology.Key(50)!=topology.Key(51)&&topology.Key(60)!=topology.Key(61)&&index.Warnings.Any(),"cyclic, reciprocal-parent and ambiguous guardianship records cannot merge families or establish ancestry");
var initial=topology.Visible(5,[]);Check(initial.People.Contains(15)&&!initial.People.Contains(1)&&!initial.People.Contains(100)&&!initial.People.Contains(22),"initial family is compact, includes recorded siblings, and excludes distant generations and other families");
var expand=topology.Visible(5,[3,7]);Check(expand.People.Contains(1)&&expand.People.Contains(2)&&expand.People.Contains(11)&&expand.People.Contains(12)&&expand.People.Contains(16),"node expansion reveals only recorded ancestors, adoption, step-parentage and descendants");
Check(topology.Visible(5,[]).People.SequenceEqual(initial.People)&&expand.Branches.Any(b=>b.ID==3&&b.Expanded),"collapse returns the compact tree and expansion state is explicit");
Check(data.Links.Single(r=>r.CharacterAID==11&&r.CharacterBID==7).RelationshipTypeName=="Adoptive Parent"&&data.Links.Single(r=>r.CharacterAID==6&&r.CharacterBID==7).RelationshipTypeName=="Biological Parent","adoptive and biological parentage retain separate canonical semantics");
Check(!data.Links.Any(r=>r.CharacterAID==11&&r.CharacterBID==12)&&topology.Visible(30,[]).People.SequenceEqual([30]),"no second parent or parental partnership is invented for an individual");
Check(data.Links.Any(r=>r.CharacterAID==5&&r.CharacterBID==9)&&data.Links.Any(r=>r.CharacterAID==10&&r.CharacterBID==9)&&!data.Links.Any(r=>r.CharacterAID==6&&r.CharacterBID==9),"multiple unions and half-siblings retain exact recorded parentage");
var changed=new ContextFamilyStructure(data.Seeds,data.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList());Check(ContextFamilyExploration.Index(changed,scene).Groups.Count==index.Groups.Count-1,"a canonical connection correction recomputes family membership");
Check(ContextFamilyExploration.Index(data,Fixture(false,23).Scene).Groups.First().SceneMembers.Contains(22),"a new scene defaults to its new POV family independently of knowledge");
scene.POVCharacterID=25;Check(ContextFamilyExploration.Index(data,scene).Groups.First().SceneMembers.Contains(25),"POV is included independently of physical classification");
try{topology.Visible(5,[22]);throw new Exception("foreign branch accepted");}catch(ArgumentException){Check(true,"branch expansion cannot import a different family");}
var watch=System.Diagnostics.Stopwatch.StartNew();var broad=new ContextFamilyTopology(Enumerable.Range(2,4096).Select(id=>new CharacterRelationship{CharacterRelationshipID=id,CharacterAID=1,CharacterBID=id,RelationshipTypeName="Parent",RelationshipCategoryName="Family"}).ToList());var bounded=broad.Visible(1,[]);Check(bounded.Truncated&&bounded.People.Length==128&&bounded.Links.Length<=256,"a 4,097-person family remains bounded without sorting the focus neighbourhood per person");
var deep=new ContextFamilyTopology(Enumerable.Range(1,4096).Select(id=>new CharacterRelationship{CharacterRelationshipID=id,CharacterAID=id,CharacterBID=id+1,RelationshipTypeName="Parent",RelationshipCategoryName="Family"}).ToList());Check(deep.Key(4097)==1&&deep.Visible(1,[]).People.Length==2,"deep canonical ancestry uses iterative traversal and starts with only adjacent generations");Console.WriteLine($"Family 4096-edge broad/deep metadata qualification: {watch.ElapsedMilliseconds}ms");
RunAccess().GetAwaiter().GetResult();
}
static async Task RunAccess()
{
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Context family access: "+message);}
var(data,scene)=Fixture();var structures=0;var trees=0;int[] requested=[];var role="Viewer";
var reader=NativeWorkflowTests.Proxy<IContextFamilyReader>((name,args)=>{if(name=="Structure"){structures++;requested=((IReadOnlyList<int>)args![2]!).ToArray();return Task.FromResult(data);}trees++;var people=(IReadOnlyList<int>)args![2]!;var links=(IReadOnlyList<int>)args[3]!;return Task.FromResult(new RelationshipMapData{Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10}],Characters=data.Seeds.Where(c=>people.Contains(c.CharacterID)).ToList(),Relationships=data.Links.Where(r=>links.Contains(r.CharacterRelationshipID)).ToList()});});
var characters=NativeWorkflowTests.Proxy<ICharacterRepository>((_,a)=>Task.FromResult<Character?>(new(){CharacterID=(int)a![0]!,ProjectID=(int)a[0]! ==99?8:7}));var user=NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4);
var lenses=new ContextRelationshipLenses(NativeWorkflowTests.Proxy<IContextRelationshipReader>((_,_)=>throw new Exception("Story reader should not be used")),characters,NativeWorkflowTests.Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),user,NativeWorkflowTests.Proxy<IStoryContextService>((_,_)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=scene})));
var service=new ContextFamilyExploration(lenses,reader,characters,user);await service.Index(12,22,CancellationToken.None);Check(requested.Contains(5)&&requested.Contains(15)&&!requested.Contains(25),"authorised index receives explicit physical seeds plus POV, not mentioned-only identities");
var tree=await service.Tree(12,22,5,[],CancellationToken.None);Check(!tree.Graph.CanEdit&&tree.Graph.Nodes.Count<=128&&tree.Graph.Nodes.All(n=>n.ID!=22),"viewer receives a bounded selected-family tree without unrelated physical participants");
var before=structures;try{await service.Tree(12,22,99,[],CancellationToken.None);throw new Exception("Foreign focus accepted");}catch(UnauthorizedAccessException){Check(before==structures,"foreign-project focus is rejected before reading family metadata");}
try{await service.Tree(12,999,5,[],CancellationToken.None);throw new Exception("Foreign scene accepted");}catch(UnauthorizedAccessException){Check(before==structures,"foreign-book scene is rejected before reading family metadata");}
var beforeTrees=trees;try{await service.Tree(12,22,5,[22],CancellationToken.None);throw new Exception("Foreign branch accepted");}catch(ArgumentException){Check(beforeTrees==trees,"branch IDs from another component cannot request a tree snapshot");}
}
}

View File

@ -182,6 +182,7 @@ if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text.
if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;}
if(args.Contains("--context-family")){ContextFamilyTests.Run();return;}
if(args.Contains("--context-lenses")){await ContextRelationshipLensTests.Run();return;}
if(args.Contains("--context-names")){await ContextNamesTests.Run();return;}
if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;}
@ -190,6 +191,7 @@ if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;}
var tests = new (string Name, Action Test)[]
{
("Scene family identification and branch exploration",ContextFamilyTests.Run),
("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()),
("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()),
("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()),

View File

@ -395,6 +395,21 @@ internal static class ToolbarBrowserHost
await RenderFullAsync(context,"Writing","Context",page,new Dictionary<string,object?> { ["NativeSnapshot"]=pinned });
}).WithOrder(-1);
app.MapGet("/Writing/Intent",context=>{context.Response.Redirect("/Writing/Context"+context.Request.QueryString);return Task.CompletedTask;}).WithOrder(-1);
app.MapGet("/context-family-index-fixture",context=>{
var fixture=ContextFamilyTests.Fixture(context.Request.Query["large"]=="true",int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:22,context.Request.Query["many"]=="true");
if(context.Request.Query["split"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Where(r=>!(r.CharacterAID is 3 or 4 && r.CharacterBID==5)).ToList());
if(context.Request.Query["merge"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList());
return context.Response.WriteAsJsonAsync(PlotLine.Services.Context.ContextFamilyExploration.Index(fixture.Structure,fixture.Scene));
});
app.MapGet("/context-family-tree-fixture",context=>{
var fixture=ContextFamilyTests.Fixture(context.Request.Query["large"]=="true",int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:22,context.Request.Query["many"]=="true");var focus=int.TryParse(context.Request.Query["focusId"],out var fid)?fid:5;
if(context.Request.Query["split"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Where(r=>!(r.CharacterAID is 3 or 4 && r.CharacterBID==5)).ToList());
if(context.Request.Query["merge"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList());
var expanded=context.Request.Query["expanded"].Select(s=>int.Parse(s!)).ToArray();var topology=new PlotLine.Services.Context.ContextFamilyTopology(fixture.Structure.Links);(int[] People,int[] Links,IReadOnlyList<PlotLine.Services.Context.ContextFamilyBranch> Branches,bool Truncated) visible;
try{visible=topology.Visible(focus,expanded);}catch(ArgumentException){context.Response.StatusCode=400;return context.Response.WriteAsJsonAsync(new{message="Choose branches within the selected family."});}
var graph=PlotLine.Services.Context.ContextRelationshipLenses.Compose(new(new(){Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=fixture.Scene.SceneID,ChapterID=10}],Characters=fixture.Structure.Seeds.Where(c=>visible.People.Contains(c.CharacterID)).ToList(),Relationships=fixture.Structure.Links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).ToList()},focus,visible.Truncated),"family",fixture.Scene,context.Request.Query["readonly"]!="true");
return context.Response.WriteAsJsonAsync(new PlotLine.Services.Context.ContextFamilyTree(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People)));
});
app.MapGet("/context-edit-fixture",async context=>{
var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false);
var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"};

View File

@ -1,11 +1,17 @@
using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize,Route("Writing/Context/Relationships"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class ContextRelationshipLensesController(ContextRelationshipLenses lenses):Controller
public sealed class ContextRelationshipLensesController(ContextRelationshipLenses lenses,ContextFamilyExploration families):Controller
{
[HttpGet("Graph")]
public async Task<IActionResult> Graph(int bookId,int sceneId,string lens="family",int? focusId=null,int depth=3,CancellationToken cancellationToken=default)
{try{return Ok(await lenses.Graph(bookId,sceneId,lens,focusId,depth,cancellationToken));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("FamilyIndex")]
public async Task<IActionResult> FamilyIndex(int bookId,int sceneId,CancellationToken cancellationToken)
{try{return Ok(await families.Index(bookId,sceneId,cancellationToken));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("FamilyTree")]
public async Task<IActionResult> FamilyTree(int bookId,int sceneId,int focusId,[FromQuery] int[]? expanded,CancellationToken cancellationToken)
{try{return Ok(await families.Tree(bookId,sceneId,focusId,expanded??[],cancellationToken));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("Lookup")]
public async Task<IActionResult> Lookup(int bookId,int sceneId,string search,CancellationToken cancellationToken)
{if(string.IsNullOrWhiteSpace(search)||search.Length>120)return BadRequest();try{return Ok((await lenses.Lookup(bookId,sceneId,search,cancellationToken)).Select(c=>new{id=c.CharacterID,name=c.CharacterName,archived=c.IsArchived}));}catch(UnauthorizedAccessException){return Forbid();}}

View File

@ -0,0 +1,32 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Models;
using PlotLine.Services;
namespace PlotLine.Data;
public sealed record ContextFamilyStructure(IReadOnlyList<Character> Seeds,IReadOnlyList<CharacterRelationship> Links);
public interface IContextFamilyReader
{
Task<ContextFamilyStructure> Structure(int project,int user,IReadOnlyList<int> seeds,CancellationToken cancellationToken);
Task<RelationshipMapData> Tree(int project,int user,IReadOnlyList<int> people,IReadOnlyList<int> links,CancellationToken cancellationToken);
}
public sealed class ContextFamilyReader(ISqlConnectionFactory connections,IConfiguration configuration):IContextFamilyReader
{
public async Task<ContextFamilyStructure> Structure(int project,int user,IReadOnlyList<int> seeds,CancellationToken cancellationToken)
{
using var db=connections.CreateConnection();using var rows=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextFamily_Structure",new{ProjectID=project,UserID=user,Seeds=JsonSerializer.Serialize(seeds)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken));
var names=(await rows.ReadAsync<Character>()).ToList();var links=(await rows.ReadAsync<CharacterRelationship>()).ToList();
if(links.Count>8192)throw new ArgumentException("Family membership exceeds the Context limit. Use the full Relationships Editor.");
return new(names,links);
}
public async Task<RelationshipMapData> Tree(int project,int user,IReadOnlyList<int> people,IReadOnlyList<int> links,CancellationToken cancellationToken)
{
using var db=connections.CreateConnection();RelationshipMapData data;
using(var rows=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextFamily_Tree",new{ProjectID=project,UserID=user,CharacterIDs=JsonSerializer.Serialize(people),RelationshipIDs=JsonSerializer.Serialize(links)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken)))
data=new(){Books=(await rows.ReadAsync<Book>()).ToList(),Chapters=(await rows.ReadAsync<Chapter>()).ToList(),Scenes=(await rows.ReadAsync<Scene>()).ToList(),Characters=(await rows.ReadAsync<Character>()).ToList(),Relationships=(await rows.ReadAsync<CharacterRelationship>()).ToList()};
if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Narrative ordering exceeds the Context limit. Use the full Relationships Editor.");
var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();
var changes=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=order.Count-1},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();
await ParagraphEvidenceProjection.Apply(db,configuration,changes);return new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters,Relationships=data.Relationships,RelationshipEvents=changes};
}
}

View File

@ -296,6 +296,8 @@ public class Program
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipEditing>();
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipLenses>();
builder.Services.AddScoped<PlotLine.Data.IContextFamilyReader,PlotLine.Data.ContextFamilyReader>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextFamilyExploration>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterEditing>();
builder.Services.AddSingleton<IManuscriptScanPreviewStore, ManuscriptScanPreviewStore>();
builder.Services.AddSingleton<IOnboardingStoryIntelligenceBatchStore, OnboardingStoryIntelligenceBatchStore>();

View File

@ -0,0 +1,87 @@
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Context;
public sealed record ContextFamilyEntry(int Key,int FocusID,string Label,IReadOnlyList<int> SceneMembers,bool IsPov);
public sealed record ContextFamilyIndex(IReadOnlyList<ContextFamilyEntry> Groups,int? DefaultKey,IReadOnlyList<string> Warnings);
public sealed record ContextFamilyBranch(int ID,int Hidden,bool Expanded);
public sealed record ContextFamilyTree(int FamilyKey,ContextLensGraph Graph,IReadOnlyList<ContextFamilyBranch> Branches,IReadOnlyList<string> Warnings);
public sealed record FamilySemantics(string Kind,int From=0,int To=0,int Generations=0);
// Membership is explicit kinship, not co-occurrence, surnames or character knowledge.
public sealed class ContextFamilyTopology
{
public static string Normalise(string value)=>string.Join(' ',value.ToLowerInvariant().Replace('-',' ').Replace('_',' ').Split(' ',StringSplitOptions.RemoveEmptyEntries));
public static FamilySemantics Semantics(CharacterRelationship r)
{
if(!ContextRelationshipLenses.Family(r.RelationshipCategoryName,r.RelationshipTypeName))return new("ambiguous");
var type=Normalise(r.RelationshipTypeName);
var parents=new[]{"parent","mother","father","biological parent","adoptive parent","step parent","grandparent","grandmother","grandfather","great grandparent"};
var children=new[]{"child","son","daughter","biological child","adopted child","adoptive child","step child","stepchild","grandchild","grandson","granddaughter","great grandchild"};
if(parents.Contains(type)||children.Contains(type))return r.IsReciprocal||r.CharacterAID==r.CharacterBID?new("ambiguous"):new("parent",parents.Contains(type)?r.CharacterAID:r.CharacterBID,parents.Contains(type)?r.CharacterBID:r.CharacterAID,type.StartsWith("great ")?3:type.StartsWith("grand")?2:1);
if(type is "spouse" or "partner" or "ex spouse" or "former spouse" or "romantic partner")return new("partner");
if(type is "sibling" or "half sibling" or "sister" or "brother")return new("sibling");
if(type is "aunt" or "uncle" or "niece" or "nephew" or "cousin")return new("kinship");
// Guardianship alone does not establish genealogical membership.
return new("ambiguous");
}
public IReadOnlyList<CharacterRelationship> Links {get;}
public IReadOnlyList<CharacterRelationship> Rejected {get;}
readonly Dictionary<int,List<int>> neighbours=[];
readonly Dictionary<int,int> components=[];
public ContextFamilyTopology(IReadOnlyList<CharacterRelationship> records)
{
var roles=records.ToDictionary(r=>r.CharacterRelationshipID,Semantics);
var directed=records.Where(r=>roles[r.CharacterRelationshipID].Kind=="parent").GroupBy(r=>roles[r.CharacterRelationshipID].From).ToDictionary(g=>g.Key,g=>g.Select(r=>roles[r.CharacterRelationshipID].To).Distinct().ToList());
// Strong components identify ancestry cycles without labelling their descendants as cycles.
var postorder=new List<int>();var visited=new HashSet<int>();var all=records.SelectMany(r=>new[]{r.CharacterAID,r.CharacterBID}).Distinct().Order().ToArray();
foreach(var id in all){var pending=new Stack<(int ID,bool Exit)>();pending.Push((id,false));while(pending.TryPop(out var frame)){if(frame.Exit){postorder.Add(frame.ID);continue;}if(!visited.Add(frame.ID))continue;pending.Push((frame.ID,true));foreach(var child in directed.GetValueOrDefault(frame.ID,[]).OrderDescending())if(!visited.Contains(child))pending.Push((child,false));}}
var reverse=directed.SelectMany(pair=>pair.Value.Select(child=>(Parent:pair.Key,Child:child))).GroupBy(e=>e.Child).ToDictionary(g=>g.Key,g=>g.Select(e=>e.Parent).ToList());
int component=0;var scc=new Dictionary<int,int>();var sizes=new Dictionary<int,int>();
foreach(var id in postorder.AsEnumerable().Reverse()){if(scc.ContainsKey(id))continue;var pending=new Stack<int>();pending.Push(id);int count=0;while(pending.TryPop(out var n)){if(!scc.TryAdd(n,component))continue;count++;foreach(var parent in reverse.GetValueOrDefault(n,[]))if(!scc.ContainsKey(parent))pending.Push(parent);}sizes[component++]=count;}
bool Valid(CharacterRelationship r){var role=roles[r.CharacterRelationshipID];return r.CharacterAID!=r.CharacterBID&&role.Kind!="ambiguous"&&(role.Kind!="parent"||scc[role.From]!=scc[role.To]||sizes[scc[role.From]]==1);}
Links=records.Where(Valid).OrderBy(r=>r.CharacterRelationshipID).ToList();Rejected=records.Where(r=>!Valid(r)).ToList();
foreach(var r in Links){if(!neighbours.ContainsKey(r.CharacterAID))neighbours[r.CharacterAID]=[];if(!neighbours.ContainsKey(r.CharacterBID))neighbours[r.CharacterBID]=[];neighbours[r.CharacterAID].Add(r.CharacterBID);neighbours[r.CharacterBID].Add(r.CharacterAID);}
foreach(var id in neighbours.Keys.Order()){if(components.ContainsKey(id))continue;var members=new HashSet<int>{id};var todo=new Queue<int>();todo.Enqueue(id);while(todo.TryDequeue(out var n))foreach(var adjacent in neighbours[n])if(members.Add(adjacent))todo.Enqueue(adjacent);var key=members.Min();foreach(var n in members)components[n]=key;}
}
public int Key(int id)=>components.GetValueOrDefault(id,id);
public IReadOnlyList<string> Warnings(IEnumerable<int> people){var set=people.ToHashSet();return Rejected.Any(r=>set.Contains(r.CharacterAID)||set.Contains(r.CharacterBID))?["An ambiguous, unsupported or cyclic family record was excluded from membership and ancestry. Review it in the Relationships Editor."]:[];}
public IReadOnlyList<int> Adjacent(int id)=>neighbours.GetValueOrDefault(id,[]).Distinct().Order().ToList();
public (int[] People,int[] Links,IReadOnlyList<ContextFamilyBranch> Branches,bool Truncated) Visible(int focus,IReadOnlyList<int> expanded)
{
if(expanded.Count>64||expanded.Any(id=>Key(id)!=Key(focus)))throw new ArgumentException("Choose branches within the selected family (maximum 64).");
var near=Adjacent(focus).ToHashSet();var visible=new HashSet<int>{focus};visible.UnionWith(near);
var parents=Links.Where(r=>Semantics(r) is {Kind:"parent",Generations:1} s&&s.To==focus).Select(r=>Semantics(r).From).ToHashSet();
// Shared recorded parentage supports siblings; no missing parent or union is inferred.
foreach(var r in Links){var role=Semantics(r);if(role.Kind=="parent"&&role.Generations==1&&parents.Contains(role.From))visible.Add(role.To);}
var basePeople=visible.ToHashSet();foreach(var r in Links)if(Semantics(r).Kind=="partner"&&(basePeople.Contains(r.CharacterAID)||basePeople.Contains(r.CharacterBID))){visible.Add(r.CharacterAID);visible.Add(r.CharacterBID);}
bool changed;do{changed=false;foreach(var id in expanded.Where(visible.Contains))foreach(var other in Adjacent(id))if(visible.Add(other))changed=true;}while(changed);
var all=visible.OrderBy(id=>id==focus?0:near.Contains(id)?1:2).ThenBy(id=>id).ToList();var people=all.Take(128).ToArray();var bounded=people.ToHashSet();var edges=Links.Where(r=>bounded.Contains(r.CharacterAID)&&bounded.Contains(r.CharacterBID)).ToList();
var branches=people.Select(id=>new ContextFamilyBranch(id,Adjacent(id).Count(n=>!bounded.Contains(n)),expanded.Contains(id))).Where(b=>b.Hidden>0||b.Expanded).ToList();
return(people,edges.Take(256).Select(r=>r.CharacterRelationshipID).ToArray(),branches,all.Count>128||edges.Count>256);
}
}
public sealed class ContextFamilyExploration(ContextRelationshipLenses lenses,IContextFamilyReader reader,ICharacterRepository characters,ICurrentUserService user)
{
static int[] Seeds(SceneEditViewModel scene,int? extra=null)=>scene.SceneCharacters.Where(ContextRelationshipLenses.Physical).Select(c=>c.CharacterID).Distinct().Order().Take(32).Concat(scene.POVCharacterID.HasValue?[scene.POVCharacterID.Value]:Array.Empty<int>()).Concat(extra.HasValue?[extra.Value]:Array.Empty<int>()).Distinct().ToArray();
public static ContextFamilyIndex Index(ContextFamilyStructure data,SceneEditViewModel scene)
{
var topology=new ContextFamilyTopology(data.Links);var seeds=Seeds(scene).ToHashSet();var names=data.Seeds.Where(c=>seeds.Contains(c.CharacterID)).ToDictionary(c=>c.CharacterID);
var groups=names.Values.GroupBy(c=>topology.Key(c.CharacterID)).Select(g=>{var ordered=g.OrderByDescending(c=>c.CharacterID==scene.POVCharacterID).ThenBy(c=>c.CharacterName,StringComparer.OrdinalIgnoreCase).ThenBy(c=>c.CharacterID).ToList();return new ContextFamilyEntry(g.Key,ordered[0].CharacterID,string.Join(" & ",ordered.Take(2).Select(c=>c.CharacterName))+(ordered.Count>2?" …":""),ordered.Select(c=>c.CharacterID).ToArray(),ordered.Any(c=>c.CharacterID==scene.POVCharacterID));}).OrderByDescending(g=>g.IsPov).ThenBy(g=>g.Label,StringComparer.OrdinalIgnoreCase).ThenBy(g=>g.Key).ToList();
var warnings=topology.Warnings(seeds).ToList();if(scene.SceneCharacters.Where(ContextRelationshipLenses.Physical).Select(c=>c.CharacterID).Distinct().Count()>32)warnings.Add("The index shows the first 32 physical participants plus the POV. Find another character to explore further families.");
return new(groups,groups.FirstOrDefault()?.Key,warnings);
}
public async Task<ContextFamilyIndex> Index(int book,int scene,CancellationToken cancellationToken){var scope=await lenses.Scope(book,scene);return Index(await reader.Structure(scope.Book.ProjectID,user.UserId!.Value,Seeds(scope.Scene),cancellationToken),scope.Scene);}
public async Task<ContextFamilyTree> Tree(int book,int scene,int focus,IReadOnlyList<int> expanded,CancellationToken cancellationToken)
{
var scope=await lenses.Scope(book,scene);var author=user.UserId!.Value;if((await characters.GetReferenceCharacterAsync(focus,author))?.ProjectID!=scope.Book.ProjectID)throw new UnauthorizedAccessException();
var structure=await reader.Structure(scope.Book.ProjectID,author,Seeds(scope.Scene,focus),cancellationToken);var topology=new ContextFamilyTopology(structure.Links);var visible=topology.Visible(focus,expanded);var data=await reader.Tree(scope.Book.ProjectID,author,visible.People,visible.Links,cancellationToken);
// Re-check the returned records: a concurrent edit must not leave disconnected
// physical participants in the chosen tree after an edge changed semantics.
var current=new ContextFamilyTopology(data.Relationships);var reachable=new HashSet<int>{focus};var pending=new Queue<int>();pending.Enqueue(focus);while(pending.TryDequeue(out var id))foreach(var adjacent in current.Adjacent(id))if(reachable.Add(adjacent))pending.Enqueue(adjacent);
var safe=new RelationshipMapData{Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters.Where(c=>reachable.Contains(c.CharacterID)).ToList(),Relationships=current.Links.Where(r=>reachable.Contains(r.CharacterAID)&&reachable.Contains(r.CharacterBID)).ToList(),RelationshipEvents=data.RelationshipEvents};
var graph=ContextRelationshipLenses.Compose(new(safe,focus,visible.Truncated),"family",scope.Scene,scope.CanEdit);
// Unlike Story, Family contains only the chosen genealogical component, including isolated focus.
return new(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People));
}
}

View File

@ -0,0 +1,38 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Family membership metadata only; no manuscript, event histories or name/surname inference.
CREATE OR ALTER PROCEDURE dbo.ContextFamily_Structure @ProjectID int,@UserID int,@Seeds nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.ProjectID=@ProjectID AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Project unavailable',1;
IF ISJSON(@Seeds)<>1 OR LEN(@Seeds)>1000 THROW 51000,'Invalid family seeds',1;
SELECT TOP(34) c.CharacterID,c.ProjectID,c.CharacterName FROM dbo.Characters c JOIN OPENJSON(@Seeds) j ON c.CharacterID=TRY_CONVERT(int,j.value) WHERE c.ProjectID=@ProjectID ORDER BY c.CharacterID;
SELECT TOP(8193) r.CharacterRelationshipID,r.ProjectID,r.CharacterAID,r.CharacterBID,r.IsReciprocal,t.TypeName AS RelationshipTypeName,cat.CategoryName AS RelationshipCategoryName
FROM dbo.CharacterRelationships r JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID
JOIN dbo.Characters ca ON ca.CharacterID=r.CharacterAID AND ca.ProjectID=@ProjectID JOIN dbo.Characters cb ON cb.CharacterID=r.CharacterBID AND cb.ProjectID=@ProjectID
WHERE r.ProjectID=@ProjectID AND r.IsArchived=0 AND (cat.CategoryName=N'Family' OR (cat.CategoryName=N'Romantic / Sexual' AND t.TypeName IN(N'Spouse',N'Partner',N'Ex-spouse',N'Former spouse',N'Romantic Partner')))
AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents e JOIN dbo.ManuscriptEvidenceIndex m ON m.EventKind=N'Relationship' AND m.EventID=e.RelationshipEventID AND m.IsPrimary=1 AND m.EvidenceState<>N'Verified' WHERE e.CharacterRelationshipID=r.CharacterRelationshipID AND e.SceneID=r.StartSceneID)
ORDER BY r.CharacterRelationshipID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextFamily_Tree @ProjectID int,@UserID int,@CharacterIDs nvarchar(max),@RelationshipIDs nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.ProjectID=@ProjectID AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Project unavailable',1;
IF ISJSON(@CharacterIDs)<>1 OR ISJSON(@RelationshipIDs)<>1 OR LEN(@CharacterIDs)>2000 OR LEN(@RelationshipIDs)>4000 THROW 51000,'Invalid family request',1;
DECLARE @people table(ID int PRIMARY KEY);INSERT @people SELECT DISTINCT TOP(128) TRY_CONVERT(int,value) FROM OPENJSON(@CharacterIDs) WHERE TRY_CONVERT(int,value) IS NOT NULL;
SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@ProjectID AND IsArchived=0;
SELECT TOP(20001) c.ChapterID,c.BookID,c.ChapterNumber,c.SortOrder FROM dbo.Chapters c JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0;
SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0;
SELECT c.CharacterID,c.ProjectID,c.CharacterName,c.BirthDate,c.IsArchived,c.IsDeceased,c.AvatarImagePath,c.AvatarThumbnailPath FROM dbo.Characters c JOIN @people p ON p.ID=c.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY c.CharacterID;
SELECT TOP(256) r.*,a.CharacterName AS CharacterAName,b.CharacterName AS CharacterBName,t.TypeName AS RelationshipTypeName,cat.CategoryName AS RelationshipCategoryName,s.StateName AS InitialRelationshipStateName
FROM dbo.CharacterRelationships r JOIN @people pa ON pa.ID=r.CharacterAID JOIN @people pb ON pb.ID=r.CharacterBID JOIN dbo.Characters a ON a.CharacterID=r.CharacterAID AND a.ProjectID=@ProjectID JOIN dbo.Characters b ON b.CharacterID=r.CharacterBID AND b.ProjectID=@ProjectID JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID LEFT JOIN dbo.RelationshipStates s ON s.RelationshipStateID=r.InitialRelationshipStateID
WHERE r.ProjectID=@ProjectID AND r.IsArchived=0 AND EXISTS(SELECT 1 FROM OPENJSON(@RelationshipIDs) j WHERE TRY_CONVERT(int,j.value)=r.CharacterRelationshipID)
AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents e JOIN dbo.ManuscriptEvidenceIndex m ON m.EventKind=N'Relationship' AND m.EventID=e.RelationshipEventID AND m.IsPrimary=1 AND m.EvidenceState<>N'Verified' WHERE e.CharacterRelationshipID=r.CharacterRelationshipID AND e.SceneID=r.StartSceneID)
ORDER BY r.CharacterRelationshipID;
END;
GO

View File

@ -2,6 +2,7 @@
@{var point=Model.Context!.Position;var scene=Model.Context.Scene!;}
<div data-context-relationships data-book="@point.BookId" data-scene="@scene.SceneID" data-pov="@scene.POVCharacterID" data-can-edit="@Model.ContextRelationshipCanEdit.ToString().ToLowerInvariant()">
<div class="context-lens-selector" role="group" aria-label="Relationship lens"><button type="button" class="btn btn-outline-primary" data-relationship-lens="family" aria-pressed="true">Family</button><button type="button" class="btn btn-outline-primary" data-relationship-lens="story" aria-pressed="false">Story</button></div>
<nav data-family-index class="context-family-index" aria-label="Families represented in this scene"></nav>
<div class="context-explorer-controls"><label>Find a character or alias <input type="search" class="form-control" data-relationship-person maxlength="120" autocomplete="off" placeholder="At least two letters"/></label><button type="button" class="btn btn-outline-secondary btn-sm" data-relationship-pov disabled="@(!scene.POVCharacterID.HasValue)">Centre on scene POV</button></div>
<div data-relationship-matches class="context-edit-actions"></div>
<p data-relationship-caption class="small"></p><div class="context-graph-toolbar"><button type="button" class="btn btn-outline-secondary btn-sm" data-graph-zoom="in" aria-label="Zoom in">+</button><button type="button" class="btn btn-outline-secondary btn-sm" data-graph-zoom="out" aria-label="Zoom out">−</button><button type="button" class="btn btn-outline-secondary btn-sm" data-graph-centre>Centre selection</button><button type="button" class="btn btn-outline-secondary btn-sm" data-graph-expand>Explore another generation</button><span data-graph-range class="small"></span></div>

View File

@ -72,3 +72,6 @@ body:has([data-context-workspace])>.writing-window-bar { flex:none; }
.context-graph-legend{display:flex;flex-wrap:wrap;gap:.4rem .8rem;font-size:.78rem;margin-block:.6rem;}.context-graph-legend span:before{content:'';display:inline-block;width:1rem;border-top:3px solid var(--connection-colour);margin-right:.3rem;vertical-align:middle;}
.context-graph-details{padding:.8rem;border:1px solid var(--plotline-line);border-radius:.5rem;margin-block:.7rem;overflow-wrap:anywhere;}.context-graph-details button,.context-graph-details>a{margin:.3rem .4rem .3rem 0;}.context-graph-details:empty{display:none;}
@container(max-width:450px){.context-relationship-graph{height:23rem;}.context-graph-details{padding:.6rem;}}
.context-family-index{margin-block:.6rem;display:flex;flex-wrap:wrap;gap:.35rem;align-items:center;}.context-family-index[hidden]{display:none;}.context-family-index button{max-width:18rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.context-family-index [aria-pressed=true]{font-weight:700;background:var(--pd-selected,var(--plotline-panel));box-shadow:inset 0 -3px var(--plotline-accent);}.context-family-index details{position:relative;}.context-family-index details>div{display:flex;flex-direction:column;gap:.3rem;padding:.4rem;}.context-family-index select{width:100%;min-width:0;}.context-family-compact{display:none;width:100%;}.context-family-branch{cursor:pointer;}.context-family-branch rect{fill:var(--plotline-panel,#fff);stroke:var(--plotline-accent);}.context-family-branch text{fill:var(--plotline-accent);font-size:14px;font-weight:700;pointer-events:none;}.context-family-branch:focus{outline:3px solid var(--plotline-accent);}
@container(max-width:560px){.context-family-index>.context-family-tabs{display:none;}.context-family-compact{display:block;}.context-family-index{display:block;}}

View File

@ -2,14 +2,15 @@
(() => {
const W=180,H=66,GAP=42,STEP=145;
const clean=s=>(s||'').toLowerCase().replace(/[-_]/g,' ').replace(/\s+/g,' ').trim();
function role(link){const t=clean(link.type),reverse=['child','son','daughter','grandchild','grandson','granddaughter','great grandchild'].includes(t),parent=['parent','mother','father','biological parent','adoptive parent','step parent','grandparent','grandmother','grandfather','great grandparent'].includes(t);
if(parent||reverse){if(link.reciprocal)return {kind:'other',ambiguous:true};return {kind:'parent',from:reverse?link.b:link.a,to:reverse?link.a:link.b,delta:t.startsWith('great ')?3:t.startsWith('grand')?2:1,style:t.includes('adoptive')?'adoptive':t.includes('step ')?'step':t.includes('biological')?'biological':'parent'};}
function role(link){const t=clean(link.type),reverse=['child','son','daughter','biological child','adopted child','adoptive child','step child','stepchild','grandchild','grandson','granddaughter','great grandchild'].includes(t),parent=['parent','mother','father','biological parent','adoptive parent','step parent','grandparent','grandmother','grandfather','great grandparent'].includes(t);
if(parent||reverse){if(link.reciprocal)return {kind:'other',ambiguous:true};return {kind:'parent',from:reverse?link.b:link.a,to:reverse?link.a:link.b,delta:t.startsWith('great ')?3:t.startsWith('grand')?2:1,style:(t.includes('adoptive')||t.includes('adopted'))?'adoptive':t.startsWith('step')?'step':t.includes('biological')?'biological':'parent'};}
if(['spouse','partner','ex spouse','former spouse','romantic partner'].includes(t))return {kind:'partner',style:'partner'};
if(['sibling','half sibling','sister','brother'].includes(t))return {kind:'sibling',style:t==='half sibling'?'half':'sibling'};
return {kind:'other',style:'other'};
}
function signature(nodes,links){return JSON.stringify([nodes.map(n=>[n.id,n.birthDate||'']).sort((a,b)=>a[0]-b[0]),links.map(l=>[l.id,l.a,l.b,l.type,l.reciprocal]).sort((a,b)=>a[0]-b[0])]);}
function family(nodes,links){const byId=new Map(nodes.map(n=>[n.id,n])),valid=links.filter(l=>byId.has(l.a)&&byId.has(l.b)),roles=new Map(valid.map(l=>[l.id,role(l)])),warnings=[];if(valid.length!==links.length)warnings.push('A connection has an unavailable identity; no replacement person was invented.');if([...roles.values()].some(r=>r.ambiguous))warnings.push('A reciprocal parent/child record has ambiguous direction. It is shown without inferred parentage; correct it in the editor.');
if([...roles.values()].some(r=>r.kind==='other'&&!r.ambiguous))warnings.push('Some recorded kinship has no explicit parentage; its connector does not establish missing ancestors or exact generations.');
const children=new Map(nodes.map(n=>[n.id,[]]));for(const l of valid){const r=roles.get(l.id);if(r.kind==='parent')children.get(r.from).push(r.to);}
const reachCache=new Map();function reaches(a,b){const key=a+':'+b;if(reachCache.has(key))return reachCache.get(key);const todo=[a],seen=new Set();let found=false;while(todo.length){const n=todo.pop();if(seen.has(n))continue;seen.add(n);for(const c of children.get(n)||[]){if(c===b){found=true;break;}todo.push(c);}if(found)break;}reachCache.set(key,found);return found;}
const uf=new Map(nodes.map(n=>[n.id,n.id]));function find(id){if(uf.get(id)!==id)uf.set(id,find(uf.get(id)));return uf.get(id);}function merge(a,b){const aa=nodes.filter(n=>find(n.id)===find(a)),bb=nodes.filter(n=>find(n.id)===find(b));if(aa.some(x=>bb.some(y=>reaches(x.id,y.id)||reaches(y.id,x.id))))return false;uf.set(find(b),find(a));return true;}
@ -31,11 +32,27 @@
for(const n of g.people){positions[n.id]={x,y:rank*STEP};x+=W+GAP;}x+=24;
}rowWidths.set(rank,Math.max(W,x-GAP));}
const width=Math.max(W,...rowWidths.values())+200;for(const n of nodes){const p=positions[n.id],rank=groups.get(find(n.id)).rank;p.x+=100+(width-200-rowWidths.get(rank))/2;p.y+=100;}
const routes=valid.map((l,i)=>{const a=positions[l.a],b=positions[l.b],r=roles.get(l.id);let d,kind=r.style||'other';if(r.kind==='parent'){const from=positions[r.from],to=positions[r.to];if(to.y>from.y){const y=to.y-28-(i%3)*18;d=`M ${from.x+W/2} ${from.y+H} V ${y} H ${to.x+W/2} V ${to.y}`;}else{kind='other';const lane=Math.min(a.y,b.y)-24-(i%5)*8;d=`M ${a.x+W/2} ${a.y} V ${lane} H ${b.x+W/2} V ${b.y}`;}}
else if(a.y===b.y){const lane=a.y-22-(i%6)*8;d=`M ${a.x+W/2} ${a.y} V ${lane} H ${b.x+W/2} V ${b.y}`;}
else{const x=Math.min(a.x,b.x)-32-(i%4)*8;d=`M ${a.x} ${a.y+H/2} C ${x} ${a.y+H/2}, ${x} ${b.y+H/2}, ${b.x} ${b.y+H/2}`;}
// Explicit partnership rails form parental unions only when both recorded parents
// have compatible parentage. Co-parentage alone never creates a union.
const unions=new Map(),junctions=[];
for(const l of valid){if(roles.get(l.id).kind!=='partner')continue;const a=positions[l.a],b=positions[l.b];if(a.y!==b.y)continue;const key=[l.a,l.b].sort((a,b)=>a-b).join(':'),y=a.y+H+14+(l.id%3)*8;unions.set(key,{x:(a.x+b.x+W)/2,y,a:l.a,b:l.b});}
const routes=valid.map((l,i)=>{const a=positions[l.a],b=positions[l.b],r=roles.get(l.id);let d,kind=r.style||'other';
if(r.kind==='parent'){
const from=positions[r.from],to=positions[r.to];
if(to.y>from.y){
const peer=valid.find(other=>{const rr=roles.get(other.id);return other.id!==l.id&&rr.kind==='parent'&&rr.to===r.to&&rr.delta===1&&r.delta===1&&rr.style===r.style&&unions.has([r.from,rr.from].sort((a,b)=>a-b).join(':'));});
const union=peer&&to.y-from.y===STEP?unions.get([r.from,roles.get(peer.id).from].sort((a,b)=>a-b).join(':')):null;
const bus=to.y-22-(r.to%3)*10;
if(union){d=`M ${from.x+W/2} ${from.y+H} V ${union.y} H ${union.x} V ${bus} H ${to.x+W/2} V ${to.y}`;if(!junctions.some(j=>j.x===union.x&&j.y===union.y))junctions.push({x:union.x,y:union.y});}
else if(to.y-from.y>STEP){const corridor=Math.min(...Object.values(positions).map(p=>p.x))-24-(l.id%5)*8;d=`M ${from.x+W/2} ${from.y+H} V ${from.y+H+14} H ${corridor} V ${bus} H ${to.x+W/2} V ${to.y}`;}
else d=`M ${from.x+W/2} ${from.y+H} V ${bus} H ${to.x+W/2} V ${to.y}`;
}else{kind='other';const lane=Math.min(a.y,b.y)-24-(i%5)*8;d=`M ${a.x+W/2} ${a.y} V ${lane} H ${b.x+W/2} V ${b.y}`;}
}else if(r.kind==='partner'&&a.y===b.y){const union=unions.get([l.a,l.b].sort((a,b)=>a-b).join(':'));d=`M ${a.x+W/2} ${a.y+H} V ${union.y} H ${b.x+W/2} V ${b.y+H}`;}
else if(a.y===b.y){const lane=a.y-22-(i%4)*9;d=`M ${a.x+W/2} ${a.y} V ${lane} H ${b.x+W/2} V ${b.y}`;}
else{const x=Math.min(...Object.values(positions).map(p=>p.x))-24-(i%4)*8;d=`M ${a.x+W/2} ${a.y+H} V ${a.y+H+14} H ${x} V ${b.y-14} H ${b.x+W/2} V ${b.y}`;}
return {id:l.id,d,kind};});
return {positions,routes,width,height:Math.max(H,...Object.values(positions).map(p=>p.y+H))+100,warnings,nodeWidth:W,nodeHeight:H};
return {positions,routes,junctions,width,height:Math.max(H,...Object.values(positions).map(p=>p.y+H))+100,warnings,nodeWidth:W,nodeHeight:H};
}
function story(nodes,links,focusID){const focus=nodes.find(n=>n.id===focusID)||nodes[0],positions={};if(!focus)return {positions,routes:[],warnings:[],width:W,height:H,nodeWidth:W,nodeHeight:H};positions[focus.id]={x:0,y:0};const other=nodes.filter(n=>n!==focus).sort((a,b)=>Number(b.physical)-Number(a.physical)||(a.name||'').localeCompare(b.name||''));const rings=[other.slice(0,10),other.slice(10)];let radiusX=260,radiusY=140;
rings.forEach((ring,index)=>{if(!ring.length)return;radiusX=Math.max(radiusX+index*(W+60),ring.length*(W+60)/(2*Math.PI));radiusY=Math.max(radiusY+index*(H+GAP),ring.length*(H+GAP)/(2*Math.PI));ring.forEach((n,i)=>{const angle=-Math.PI/2+2*Math.PI*i/ring.length;positions[n.id]={x:Math.cos(angle)*radiusX,y:Math.sin(angle)*radiusY};});});

View File

@ -7,14 +7,39 @@
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 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){
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.
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));familyView(matching?.key??id,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;
@ -27,45 +52,64 @@
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);
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){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;}
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}`;}
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);
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);
}
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);}
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=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';
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?'More recorded connections lie outside this view. Expand or centre another person.':null,...layout.warnings].filter(Boolean).join(' ');
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.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');
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{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();}
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',()=>{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(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':''),()=>{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);});
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)});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';}};
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';}};
})();