Add Family and Story Context visual lenses and canonical life status

This commit is contained in:
Nick Beckley 2026-11-22 17:38:55 +00:00
parent 48573298d8
commit 01a7723c5a
44 changed files with 969 additions and 91 deletions

View File

@ -29,3 +29,19 @@ Underlying shared-query correction (migration299): the existing Name Search book
Both live procedure definitions were checked against the previous authoritative migration before applying the new forward-only definitions. Development backup `context-refine-stage2-20261122T163128Z.bak` succeeded and VERIFYONLY passed. Migration299 applied and its procedures were smoke-verified. No canonical data rows were changed by the migration. Disposable qualification added one empty book and one reference-name alias on the existing synthetic character; shared-query acceptance proved used in the character's appearance book and unused in the empty second book.
Stage 2 predeployment qualification: clean solution build, seven direct library/filter/bounded-identity/read-only assertions, 17 existing character/name-edit assertions, stored-procedure architecture guard, actual compiled Razor browser with all filters, 100 candidates, profile/related forms/copy, on-demand identity/correction, pagination, independent panes and full/half/stacked/mobile passed. Touch-emulated 390px browser checks passed. Full Development query-parity acceptance follows installation. Existing open application/Context windows should reload once to acquire the updated tool scripts; no Word navigation is part of that reload.
Stage 2 deployed at `4857329`, release `context-refine-stage2-4857329-20261122T164213Z`. Local/public GET200, informational commit and assembly/assets verified (including the new Names module). Ten actual Development main/Context searches matched exact ordered candidate IDs and used counts, covering empty/uncommon/near-prefix, aliases, used/unused, book/project/accessible-project scopes, all meaningful filters, two active locales and pagination. The alias was used in its appearance book and unused in the empty qualification book. Live focused editing with quiet second-session refresh and existing-main navigation passed again. No physical PWA/device acceptance is claimed.
## Stage 3: Family and Story visual lenses
The previous text list is replaced with two purpose-built SVG views. Both use the canonical relationship records, existing narrative ordering and `RelationshipMapService.BuildAtScene`, existing verified evidence projection, existing focused relationship editing/services, My Windows and shared notifications. No new graph framework or story-state engine. Family defaults to POV, represents author-established structure independently of POV knowledge, keeps historical/archived relatives, and never manufactures missing relatives. Explicit directional parent/child, biological/adoptive/step and ancestor links control generations; spouses/partners align, known siblings group with reliable birth dates, multiple unions and half-siblings are preserved. Ambiguous/cyclic records are labelled rather than guessed. Canonical professional partnerships are not family unions.
Story prioritises explicitly physical participants (a Mentioned Only role overrides a contradictory presence label), preserves direction/reciprocity, uses category colours and a legend, and excludes future starts, later changes and unverified primary evidence. Selected links show current state and at most three established changes. The interface expressly avoids inferred first meetings, mutual trust or viewpoint knowledge. Global death status is excluded from Story DTOs because it has no narrative timestamp. No optional viewpoint-knowledge filter is offered: the available canonical data cannot reliably provide one.
Readers use new authorised stored procedures, bounded at 128 characters, 256 links and three verified events per link. Only canonical ordering metadata is read across the project (20,000-item safety limit); no manuscript or complete relationship histories. Lookup is literal escaped name/alias matching, minimum two characters and 25 results. Family expansion is bounded to six connection steps, with boundary messages and recentering for further exploration. Nodes retain readable size and support mouse/touch pan, pinch/buttons/wheel zoom and keyboard exploration. Per-pane lens/focus/pan/layout state survives switching; structural signatures exclude state-only changes so manuscript notifications do not reposition unchanged families. Recorded-connections disclosure provides accessible disambiguation in complex graphs.
User explicitly approved a canonical deceased-status field in response to the data-model question. `Characters.IsDeceased` is nullable: NULL Unrecorded, false Living, true Deceased. No backfill or inference from archival/imported prose. Family and character reference views label it as global author reference, without death-date/scene/knowledge claims. An existing shared focused modal saves only this field with SQL permission checks and nullable original-value comparison. The main Character form exposes the same optional field; unchanged/legacy saves preserve it. Backup export, stored-field contracts, JSON roundtrip, canonical reads and timeline projections include the field; older backups remain compatible.
Database qualification: migration300 applied after verified backup `context-refine-stage3-20261122T170555Z.bak`. Life-status backup `context-refine-life-20261122T173415Z.bak` succeeded and VERIFYONLY passed. Migration301 installed the nullable field and save/read procedures, then stopped on differently formatted deployed projection headers. Migration302 stopped before projection changes because of a malformed comment. Both attempts are preserved unchanged. Forward303 completed projections, and standalone idempotent **304_CharacterLifeStatusCanonical.sql** consolidates the complete authorised definition for future environments. Use 304 directly for this field, not a blind replay of 301–303. Exact Character_Save preflight matched authoritative previous logic; all projection anchors were checked before applying. Final schema/procedure smoke passed. Transactional tests proved nullable CAS rejects stale saves, legacy full saves preserve status, explicit full-editor saves update it, and rollback leaves all canonical statuses unrecorded. No real manuscript records changed.
Stage 3 qualification: solution build zero warnings/errors; 10 visual-domain assertions, 12 focused relationship assertions and 21 character/name/life-status assertions passed. Layout tests cover four generations, multiple spouses, half-siblings, adoption/step/Child reversal, unknown/cyclic/cross-generation records, reliable birth order and 120 nonoverlapping nodes; Story sizes 1–128 are checked for nonoverlap. Actual compiled Razor browser passed SVG hit selection, source-specific modal, 120-node family, dense 45-edge network, scene changes, independent panes, full/half/stacked/mobile, keyboard pan/zoom, read-only controls, and zero family layout recalculations on state-only notification. Family death indicator and Story omission are tested. Full integration and actual Development persistence follow installation.

View File

@ -7,14 +7,20 @@ const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('nod
async function open(field){if(!await p.locator(row).evaluate(n=>n.open))await p.locator(row+' summary').click();await p.locator(row+` [data-context-edit="${field}"]`).click();await p.waitForSelector('[data-context-edit-form]');}
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);}
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]');}
step='names alias add and persisted spelling';await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-names]');await lookupIdentity('Synthetic Context person one');await p.locator(`[data-context-edit="alias-add"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');const alias='Synthetic alias '+Date.now();await p.locator('[name=Value]').fill(alias);await save();await p.waitForSelector('[data-context-names]');await lookupIdentity(alias);assert.match(await p.locator('[data-name-identity-fragment]').innerText(),new RegExp(alias));
step='live inline validation retains failed draft';await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');await p.locator('[name=Value]').fill('');await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForSelector('.validation-summary-errors');assert(await p.locator('[data-context-edit-dialog]').isVisible());assert.equal(await p.locator('[name=Value]').inputValue(),'');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');
if(process.env.PD_CONTEXT_RELATIONSHIPS==='1'){
step='live one-relationship create and correction';await p.selectOption('[data-context-tab]','relationships');await remote.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await remote.waitForSelector('[data-context-relationships]');
const existing=p.locator('[data-context-relationship]');if(await existing.count()===0){await p.locator('[data-context-relationship-edit="scene"]').last().click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(s.characters[0]));await p.selectOption('[name=TargetID]',String(s.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&!n.textContent.includes('Family'))?.value);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic relationship evidence');await save();}
await p.waitForSelector('[data-context-relationship]');const rr=p.locator('[data-context-relationship]').first();if(!await rr.evaluate(n=>n.open))await rr.locator('summary').first().click();await rr.locator('[data-context-relationship-edit="scene"]').click();await p.waitForSelector('[data-context-edit-form]');const note='Synthetic relationship correction '+Date.now();await p.locator('[name=Notes]').fill(note);await save();await remote.waitForFunction(note=>document.querySelector('[data-context-relationships]').textContent.includes(note),note);assert.equal(await remote.evaluate(()=>successes),0);
await p.locator('[data-relationship-lens="story"]').click();await remote.locator('[data-relationship-lens="story"]').click();await p.waitForSelector('[data-graph-node]');
const existing=p.locator('[data-graph-edge]');if(await existing.count()===0){await p.locator('[data-relationship-add]').click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(s.characters[0]));await p.selectOption('[name=TargetID]',String(s.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&!n.textContent.includes('Family'))?.value);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic relationship evidence');await save();}
async function selectConnection(page){await page.locator(`[data-graph-node="${id}"]`).click();await page.locator('[data-relationship-details] details summary').click();await page.locator('[data-inspect-connection]').first().click();}
await p.waitForSelector('[data-graph-edge]');await remote.waitForSelector('[data-graph-edge]');await selectConnection(p);await selectConnection(remote);await p.locator('[data-relationship-details] [data-context-relationship-edit="scene"]').click();await p.waitForSelector('[data-context-edit-form]');const note='Synthetic relationship correction '+Date.now();await p.locator('[name=Notes]').fill(note);await save();await remote.waitForFunction(note=>document.querySelector('[data-context-relationships]').textContent.includes(note),note);assert.equal(await remote.evaluate(()=>successes),0);
}
assert(counts.every(c=>c.word===0&&c.hub===1));console.log('PASS Development canonical editing: focused persisted values, cancel/unsaved protection, alias add, failed inline name draft retained, one local success/quiet second authenticated session, one connection each, no Word navigation'+(process.env.PD_CONTEXT_RELATIONSHIPS==='1'?', relationship create/correct persisted through existing services':''));
} catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await browser.close();}})();

View File

@ -1,13 +1,13 @@
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'})}));
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 ['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-context-relationship="9"] summary').first().click();await p.locator('[data-context-relationship="9"] [data-context-relationship-edit="scene"]').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]');
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]');
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='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);
step='unsaved main form can decline navigation';await main.waitForTimeout(500);const beforeDirty=main.url();await main.evaluate(()=>{const f=document.createElement('form');f.method='post';f.innerHTML='<input name="SyntheticDraft">';document.body.append(f);});await main.locator('[name=SyntheticDraft]').fill('Unsaved draft');main.once('dialog',d=>d.dismiss());await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(700);assert.equal(main.url(),beforeDirty);assert.equal(c.pages().length,originalPages);
step='missing main opens only one named fallback';await main.close();const popupPromise=p.waitForEvent('popup');await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();const popup=await popupPromise;await popup.waitForURL(/Characters\?projectId=7/);await popup.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected',{},{timeout:7000}).catch(async e=>{const info=await popup.evaluate(()=>({user:document.body.dataset.pdUserId,books:document.body.dataset.pdBookIds,env:window.PlotDirectorContextEnvironment,state:window.PlotDirectorPresenceConnection?.state,ready:document.readyState,title:document.title}));throw Error(e.message+JSON.stringify(info));});await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(600);assert.equal(c.pages().length,originalPages);
assert.deepEqual(errors,[]);console.log('PASS shared Context refinement: all eight character/name modal variants full-width at desktop/mobile, one Save/Cancel, Escape; real registry/main shell reuses native connection and existing main window, repeated navigation creates no popup.');
assert.deepEqual(errors,[]);console.log('PASS shared Context refinement: all nine character/name modal variants full-width at desktop/mobile, one Save/Cancel, Escape; real registry/main shell reuses native connection and existing main window, repeated navigation creates no popup.');
} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,8 @@
const vm=require('node:vm'),fs=require('node:fs'),assert=require('node:assert/strict');const sandbox={window:{}};vm.runInNewContext(fs.readFileSync('PlotLine/wwwroot/js/context-relationship-layout.js','utf8'),sandbox);const L=sandbox.window.PlotDirectorContextRelationshipLayout;
const nodes=Array.from({length:16},(_,i)=>({id:i+1,name:'A deliberately long canonical relative name '+(i+1),birthDate:i===6?'2000-01-01':i===7?'2002-01-01':null,archived:i===5}));let id=0;const link=(a,b,type,reciprocal=false)=>({id:++id,a,b,type,reciprocal,category:'Family'});const links=[link(1,2,'Spouse',true),link(1,3,'Parent'),link(2,3,'Parent'),link(3,4,'Spouse',true),link(3,5,'Parent'),link(4,5,'Parent'),link(5,6,'Spouse',true),link(5,10,'Spouse',true),link(5,7,'Biological Parent'),link(6,7,'Biological Parent'),link(5,8,'Parent'),link(6,8,'Parent'),link(5,9,'Parent'),link(10,9,'Parent'),link(7,8,'Sibling',true),link(7,9,'Half-sibling',true),link(11,7,'Adoptive Parent'),link(12,7,'Step Parent'),link(13,14,'Child'),link(12,9,'Guardian'),link(15,16,'Parent',true)];
function noOverlap(layout,people){for(let i=0;i<people.length;i++)for(let j=i+1;j<people.length;j++){const a=layout.positions[people[i].id],b=layout.positions[people[j].id];assert(Math.abs(a.x-b.x)>=layout.nodeWidth||Math.abs(a.y-b.y)>=layout.nodeHeight,`nodes overlap ${people[i].id}/${people[j].id}`);}}
const f=L.family(nodes,links);assert.equal(Object.keys(f.positions).length,nodes.length);for(const l of links){const r=L.role(l);if(r.kind==='parent')assert(f.positions[r.from].y<f.positions[r.to].y,'ancestor above descendant');}for(const l of links.filter(l=>l.type==='Spouse'))assert.equal(f.positions[l.a].y,f.positions[l.b].y);assert.equal(f.positions[7].y-f.positions[11].y,145,'adoptive parent is aligned one generation above child');assert.equal(f.positions[7].y-f.positions[12].y,145,'step parent generation');assert(f.positions[7].x<f.positions[8].x,'recorded sibling birth order');assert(f.warnings.some(w=>w.includes('reciprocal')));noOverlap(f,nodes);assert.equal(L.signature(nodes,links),L.signature(nodes,links.map(l=>({...l,state:'Changed note',notes:'New note'}))));
const cycleNodes=[{id:1,name:'One'},{id:2,name:'Two'}],cycle=L.family(cycleNodes,[link(1,2,'Parent'),link(2,1,'Parent')]);assert(cycle.warnings.some(w=>w.includes('cycle')));noOverlap(cycle,cycleNodes);
const crossing=L.family(nodes,[...links,link(1,7,'Spouse')]);assert(crossing.positions[1].y<crossing.positions[7].y,'cross-generation partnership never flattens ancestry');
const big=Array.from({length:120},(_,i)=>({id:i+1,name:'Long canonical person '+i,birthDate:i%3?'1900-01-01':null,physical:i<12})),tree=[];for(let i=2;i<=120;i++)tree.push(link(Math.floor(i/2),i,'Parent'));const start=performance.now();const b=L.family(big,tree);noOverlap(b,big);assert.equal(Object.keys(b.positions).length,120);assert(performance.now()-start<1000,'bounded family layout performance');const dense=[];for(let i=1;i<24;i++)for(let j=i+1;j<=24;j++)dense.push(link(i,j,'Friend'));const story=L.story(big,dense,1);noOverlap(story,big);assert.equal(story.routes.length,dense.length);for(let count=1;count<=128;count++){const people=Array.from({length:count},(_,i)=>({id:i+1,name:'Person '+i,physical:i<12}));noOverlap(L.story(people,[],1),people);}
console.log('PASS family/network layout: four generations, multiple partners, half-siblings, adoptive/step/explicit Child reversal, archived identity retained, unknown relatives not invented, birth order, ambiguous/cyclic/cross-generation records, 120 nonoverlapping nodes and dense edges; stable signature ignores state-only changes.');

View File

@ -1,15 +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 browser=await chromium.launch();let step='setup';try{
const context=await browser.newContext({viewport:{width:1366,height:768}});let posts=0,fail=true;
await context.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 context.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}}));
await context.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 context.route('**/Writing/Context/EditCharacter*',async r=>{const post=r.request().method()==='POST';if(post)posts++;if(post&&!fail)return r.fulfill({json:{saved:true,bookId:12}});const response=await r.fetch({url:base+'/context-edit-fixture?field=description'+(post?'&invalid=true':''),method:'GET'});await r.fulfill({status:post?422:200,contentType:'text/html',body:await response.text()});});
await context.route('**/Writing/Context/EditRelationship*',async r=>{if(r.request().method()==='POST')posts++;await r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture',method:'GET'})});});
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/Writing/Context');await page.selectOption('[data-context-tab]','characters');await page.waitForSelector('[data-character-explorer]');
step='family and narrative split';await page.selectOption('[data-context-tab]','relationships');await page.waitForSelector('[data-context-relationships]');assert.match(await page.locator('[data-context-relationships]').textContent(),/Family connections[\s\S]*Parent[\s\S]*Narrative connections[\s\S]*Friend/);assert.equal(await page.locator('[data-context-relationship]:visible').count(),2);await page.locator('[data-context-relationship="9"] summary').first().click();assert.match(await page.locator('[data-context-relationship="9"]').innerText(),/Directional connection/);assert.match(await page.locator('[data-context-relationship="9"]').innerText(),/no structured marker/);
step='focused relationship modal';await page.locator('[data-context-relationship="9"] [data-context-relationship-edit="scene"]').click();await page.waitForSelector('[data-context-edit-form]');assert.equal(await page.locator('[name=Notes]').inputValue(),'Saved scene note');await page.click('[data-context-edit-cancel]');assert.equal(posts,0);
step='independent filtering and responsive layouts';await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','relationships');await page.locator('[data-context-pane="1"] [data-relationship-filter]').fill('Friend');assert.equal(await page.locator('[data-context-pane="1"] [data-context-relationship]:visible').count(),1);assert.equal(await page.locator('[data-context-pane="0"] [data-context-relationship]:visible').count(),2);for(const width of [1366,760,390]){await page.setViewportSize({width,height:800});for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(40);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}}
assert.deepEqual(errors,[]);console.log('PASS Relationships browser: family/narrative categories, direction, explicit evidence limits, focused saved-value modal/cancel, independent filters and full/half/stacked/mobile layouts');
} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await browser.close();}})();
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 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='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='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.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -1,2 +1,2 @@
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});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'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));await c.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{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})});});const p=await c.newPage();await p.goto(base+'/Writing/Context');for(const tool of ['characters','names','relationships']){await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');const first=tool==='names'?p.locator('[data-context-name-id] details').first():p.locator('.context-character-row').first();await first.locator('summary').first().tap();await first.locator('summary').first().tap();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.screenshot({path:'/tmp/context-enhancement-'+tool+'-touch.png'});}console.log('PASS touch-emulated Chromium: all three tools, long names, summary tap and no horizontal overflow at 390px. Physical touch/PWA installation not exercised.');}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exitCode=1;});
(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});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'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));await c.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{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/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();await p.goto(base+'/Writing/Context');for(const tool of ['characters','names','relationships']){await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');if(tool==='relationships'){await p.locator('[data-graph-node="5"]').tap();await p.locator('[data-graph-zoom="in"]').tap();await p.locator('[data-relationship-lens="story"]').tap();await p.locator('[data-graph-node="5"]').tap();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.screenshot({path:'/tmp/context-refinement-relationships-touch.png'});continue;}const first=tool==='names'?p.locator('[data-context-name-id] details').first():p.locator('.context-character-row').first();await first.locator('summary').first().tap();await first.locator('summary').first().tap();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.screenshot({path:'/tmp/context-enhancement-'+tool+'-touch.png'});}console.log('PASS touch-emulated Chromium: all three tools, long names, summary tap and no horizontal overflow at 390px. Physical touch/PWA installation not exercised.');}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exitCode=1;});

View File

@ -24,9 +24,12 @@ internal static class ContextCharacterTests
var role="Owner";var writes=0;SceneCharacterEditViewModel? savedAppearance=null;
var service=NativeWorkflowTests.Proxy<ICharacterService>((name,args)=>name switch{
"GetEditCharacterAsync"=>Task.FromResult<CharacterEditViewModel?>(JsonSerializer.Deserialize<CharacterEditViewModel>(JsonSerializer.Serialize(character))),
"GetReferenceCharacterAsync"=>Task.FromResult<Character?>(new(){CharacterID=5,ProjectID=7,CharacterName=character.CharacterName,IsDeceased=character.IsDeceased,IsArchived=true}),
"SaveLifeStatusAsync"=>SaveLife((bool?)args![1],(bool?)args[2]),
"SaveCharacterAsync"=>Save((CharacterEditViewModel)args![0]!),
"UpdateSceneCharacterAsync"=>SaveAppearance((SceneCharacterEditViewModel)args![0]!),_=>throw new Exception(name)});
Task<CharacterSaveResult> Save(CharacterEditViewModel input){writes++;character=input;return Task.FromResult(new CharacterSaveResult(5));}
Task SaveLife(bool? value,bool? expected){Check(expected==character.IsDeceased,"life-status correction passes the original canonical value for atomic comparison");writes++;character.IsDeceased=value;return Task.CompletedTask;}
Task<int> SaveAppearance(SceneCharacterEditViewModel input){writes++;savedAppearance=input;return Task.FromResult(8);}
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var aliases=new List<CharacterAlias>{new(){CharacterAliasID=11,CharacterID=5,Alias="Kept alias",SortOrder=10}};
@ -55,6 +58,8 @@ internal static class ContextCharacterTests
var nameRows=ContextNames.Compose([new(){CharacterID=5,CharacterName="Éva"},new(){CharacterID=6,CharacterName="Another"}],[new(){CharacterID=5,Alias="Éva"},new(){CharacterID=6,Alias="E\u0301VA"}]);
Check(nameRows.All(r=>r.SharedSpellings.Any()),"existing Unicode normalisation detects cross-character shared spellings including aliases");
Check(ContextNames.Compose([new(){CharacterID=5,CharacterName="Person"}],[new(){CharacterID=5,Alias="PERSON"}]).Single().SharedSpellings.Count==0,"legitimate aliases of one identity are not duplicate identities");
var life=await edit.Read(12,22,5,"life-status");Check(life.Value==null&&life.Options.Count==3,"archived relatives retain unrecorded life status and three explicit choices");life.Value="true";var beforeLife=writes;await edit.Save(life);Check(character.IsDeceased==true&&writes==beforeLife+1&&character.CharacterName=="New canonical","life-status uses a single-field save without a hydrated full-character write");
var encoded=JsonSerializer.Serialize(new Character{CharacterID=5,IsDeceased=true});Check(JsonSerializer.Deserialize<Character>(encoded)!.IsDeceased==true&&JsonSerializer.Deserialize<Character>("{\"CharacterID\":5}")!.IsDeceased==null,"canonical deceased status roundtrips and older backups remain unrecorded");
role="Viewer";var before=writes;try{await edit.Read(12,22,5,"description");throw new Exception("Viewer permitted");}catch(UnauthorizedAccessException){Check(writes==before,"read-only account cannot load an editing form or write");}
}
}

View File

@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Http;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class ContextRelationshipBrowserFixture
{
public static ContextLensGraph Graph(HttpContext context){var family=context.Request.Query["lens"]!="story";var large=context.Request.Query["large"]=="true";var scene=int.TryParse(context.Request.Query["sceneId"],out var sid)?sid:22;var focus=int.TryParse(context.Request.Query["focusId"],out var fid)?fid:5;var nodes=Enumerable.Range(1,large?120:24).Select(i=>new ContextLensNode(i,i==5?"Fixture participant":"An established relative with a deliberately long name "+i,i is 7 or 8?new DateTime(2000+(i-7)*2,1,1):null,i==6,i is 5 or 6 or 7,null,family&&i==6?true:null)).ToList();var links=new List<ContextLensLink>();int id=0;
void Add(int a,int b,string type,string category="Family",bool mutual=false)=>links.Add(new(++id,a,b,type,category,scene==23?"Later established":"Established",mutual,true,null,null,scene,"Explicit recorded connection notes",[new(){SceneID=scene,Label="Source scene "+scene,StateName=scene==23?"Later established":"Established",Notes="Recorded development"}]));
if(family){Add(1,2,"Spouse","Romantic / Sexual",true);Add(1,3,"Parent");Add(2,3,"Parent");Add(3,4,"Spouse","Romantic / Sexual",true);Add(3,5,"Parent");Add(4,5,"Parent");Add(5,6,"Spouse","Romantic / Sexual",true);Add(5,10,"Spouse","Romantic / Sexual",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(7,8,"Sibling","Family",true);Add(7,9,"Half-sibling","Family",true);Add(11,7,"Adoptive Parent");Add(12,7,"Step Parent");Add(13,14,"Child");Add(12,9,"Guardian");if(large)for(int i=25;i<=120;i++)Add(i/2,i,"Parent");}
else{nodes=nodes.Select(n=>n with{Physical=n.ID is 5 or 6}).ToList();for(int a=5;a<=14;a++)for(int b=a+1;b<=14;b++)Add(a,b,(a+b)%2==0?"Friend":"Rival",(a+b)%2==0?"Friendship":"Hostile / Conflict",(a+b)%3==0);}
return new(family?"family":"story",focus,5,scene,"Fixture scene "+scene,context.Request.Query["readonly"]!="true",false,nodes,links);
}
}

View File

@ -0,0 +1,22 @@
using PlotLine.Data;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class ContextRelationshipLensTests
{
public static async Task Run(){void Check(bool p,string m){if(!p)throw new Exception(m);Console.WriteLine("PASS Context visual lenses: "+m);}
var scene=new SceneEditViewModel{SceneID=22,ChapterID=10,SceneTitle="Current point",POVCharacterID=5,SceneCharacters=[new(){CharacterID=5,PresenceTypeName="Present"},new(){CharacterID=7,PresenceTypeName="Present",RoleInSceneTypeName="Mentioned Only"}]};
var data=new RelationshipMapData{Books=[new(){BookID=12,SortOrder=1}],Chapters=[new(){ChapterID=10,BookID=12,SortOrder=1}],Scenes=[new(){SceneID=90,ChapterID=10,SceneNumber=1},new(){SceneID=22,ChapterID=10,SceneNumber=2},new(){SceneID=2,ChapterID=10,SceneNumber=3}],Characters=[new(){CharacterID=5,ProjectID=7,CharacterName="Focus",IsDeceased=true,BirthDate=new(1950,1,1)},new(){CharacterID=6,ProjectID=7,CharacterName="Archived relative",IsArchived=true},new(){CharacterID=7,ProjectID=7,CharacterName="Mentioned identity"}],Relationships=[new(){CharacterRelationshipID=9,ProjectID=7,CharacterAID=5,CharacterBID=6,RelationshipTypeName="Parent",RelationshipCategoryName="Family",IsInitialRelationship=true,InitialRelationshipStateName="Before"},new(){CharacterRelationshipID=10,ProjectID=7,CharacterAID=5,CharacterBID=7,RelationshipTypeName="Acquaintance",RelationshipCategoryName="Professional / Social",IsInitialRelationship=true,InitialRelationshipStateName="Known of"},new(){CharacterRelationshipID=11,ProjectID=7,CharacterAID=6,CharacterBID=7,RelationshipTypeName="Child",RelationshipCategoryName="Family",StartSceneID=2}],RelationshipEvents=[new(){RelationshipEventID=1,CharacterRelationshipID=9,SceneID=22,RelationshipStateName="Now",Description="Recorded present change"},new(){RelationshipEventID=2,CharacterRelationshipID=9,SceneID=2,RelationshipStateName="Later",Description="Future evidence"}]};
var read=new ContextLensRead(data,5,false);var story=ContextRelationshipLenses.Compose(read,"story",scene,true);
Check(story.Links.Single(r=>r.ID==9).State=="Now"&&!story.Links.Any(r=>r.ID==11),"Story uses canonical scene order and excludes future-start relationships");
Check(story.Links.Single(r=>r.ID==9).Recent.All(e=>e.SceneID!=2)&&story.Links.Single(r=>r.ID==9).Notes=="Recorded present change","future events cannot leak into current details or recent changes");
Check(!story.Nodes.Single(n=>n.ID==7).Physical&&story.Nodes.Single(n=>n.ID==5).Physical,"mentioned-only role overrides a contradictory physical presence label");
var family=ContextRelationshipLenses.Compose(read,"family",scene,false);Check(family.Links.Any(r=>r.ID==11)&&family.Nodes.Any(n=>n.ID==6&&n.Archived)&&!family.CanEdit,"Family author truth retains recorded future structure and archived identities, explicitly outside POV knowledge");
Check(family.Links.All(r=>r.Category=="Family")&&ContextRelationshipLenses.Family("Romantic / Sexual","Spouse")&&!ContextRelationshipLenses.Family("Professional / Social","Partner"),"family spouse semantics do not turn professional partners into kinship");
Check(story.Links.Single(r=>r.ID==10).State=="Known of"&&!story.Links.Single(r=>r.ID==9).Reciprocal,"explicit states and directional connections are preserved without inferred meeting or symmetry");
Check(family.Nodes.Single(n=>n.ID==5).IsDeceased==true&&family.Nodes.Single(n=>n.ID==6).IsDeceased==null&&story.Nodes.All(n=>n.IsDeceased==null),"canonical death status is Family author reference only; archival does not imply death and Story cannot leak a global future death");
int[]? observedPhysical=null;bool? narrative=null;var role="Viewer";
var reader=NativeWorkflowTests.Proxy<IContextRelationshipReader>((n,a)=>{observedPhysical=((IReadOnlyList<int>)a![6]!).ToArray();return Task.FromResult(read);});
var lens=new ContextRelationshipLenses(reader,NativeWorkflowTests.Proxy<ICharacterRepository>((n,a)=>Task.FromResult<Character?>(new(){CharacterID=(int)a![0]!,ProjectID=(int)a[0]! ==99?8:7})),NativeWorkflowTests.Proxy<IWordCompanionRepository>((n,a)=>Task.FromResult<WordCompanionBookStructureResponse?>((int)a![0]! ==12?new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]}:null)),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>{narrative=(bool)a![4]!;return Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=scene});}));
var actual=await lens.Graph(12,22,"story",null,3);Check(observedPhysical!.SequenceEqual([5])&&narrative==false&&!actual.CanEdit,"visual reads use bounded reader and thin scene context without loading narrative histories; viewers remain read-only");
try{await lens.Graph(12,22,"family",99,3);throw new Exception("foreign focus accepted");}catch(UnauthorizedAccessException){Check(true,"cross-project focus rejected before graph read");}
try{await lens.Graph(12,999,"family",5,3);throw new Exception("foreign scene accepted");}catch(UnauthorizedAccessException){Check(true,"cross-book scene rejected");}
}
}

View File

@ -11,7 +11,7 @@ internal static class ContextRelationshipTests
RelationshipMapData Data()=>new(){Characters=[new(){CharacterID=5,CharacterName="From"},new(){CharacterID=6,CharacterName="To"}],Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10,SceneNumber=1},new(){SceneID=23,ChapterID=10,SceneNumber=2}],Relationships=[r],RelationshipEvents=events};
var point=RelationshipMapService.BuildAtScene(Data(),new Dictionary<int,int>{{22,0},{23,1}},22).Single();Check(point.CurrentStateName=="Changed"&&point.RelationshipCategoryName=="Family"&&!point.IsReciprocal,"canonical story-point state excludes future events, preserves Family and direction");
var role="Owner";RelationshipEventCreateViewModel? saved=null;InitialRelationshipEditViewModel? initial=null;
var repository=NativeWorkflowTests.Proxy<ICharacterRepository>((name,_)=>name switch{"GetRelationshipMapAsync"=>Task.FromResult(Data()),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData{RelationshipTypes=[new(){RelationshipTypeID=1,TypeName="Parent",IsActive=true}],RelationshipStates=[new(){RelationshipStateID=1,StateName="Established",IsActive=true},new(){RelationshipStateID=2,StateName="Changed",IsActive=true}]}),_=>throw new Exception(name)});
var repository=NativeWorkflowTests.Proxy<ICharacterRepository>((name,_)=>name switch{"GetRelationshipMapAsync"=>Task.FromResult(Data()),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData{RelationshipTypes=[new(){RelationshipTypeID=1,TypeName="Parent",RelationshipCategoryName="Family",IsActive=true}],RelationshipStates=[new(){RelationshipStateID=1,StateName="Established",IsActive=true},new(){RelationshipStateID=2,StateName="Changed",IsActive=true}]}),_=>throw new Exception(name)});
var service=NativeWorkflowTests.Proxy<ICharacterService>((name,args)=>{if(name=="UpdateRelationshipEventAsync"){saved=(RelationshipEventCreateViewModel)args![0]!;return Task.FromResult(10);}if(name=="SaveInitialRelationshipAsync"){initial=(InitialRelationshipEditViewModel)args![0]!;return Task.FromResult(9);}throw new Exception(name);});
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var edit=new ContextRelationshipEditing(repository,service,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})),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance));
@ -22,6 +22,8 @@ internal static class ContextRelationshipTests
var start=await edit.Read(12,22,9,"initial");start.Notes="Initial correction";await edit.Save(start);Check(initial?.CharacterRelationshipID==9&&initial.InitialRelationshipStateID==1&&initial.CharacterID==5&&initial.RelatedCharacterID==6,"focused initial correction reuses existing initial relationship service");
try{await edit.Read(12,22,999,"scene");throw new Exception("foreign ID accepted");}catch(UnauthorizedAccessException){Check(true,"unowned relationship ID rejected");}
try{await edit.Read(12,999,9,"scene");throw new Exception("foreign scene accepted");}catch(UnauthorizedAccessException){Check(true,"cross-book scene rejected");}
r.StartSceneID=23;var author=await edit.Read(12,22,9,"initial","family");Check(author.ReferenceLens=="family"&&author.Types.Any(t=>t.Value=="1"),"Family initial corrections use explicit author truth without treating a future source as current POV knowledge");
r.RelationshipCategoryName="Professional / Social";r.RelationshipTypeName="Colleague";try{await edit.Read(12,22,9,"initial","family");throw new Exception("nonfamily accepted");}catch(ArgumentException){Check(true,"Family reference mode cannot relabel a nonfamily connection");}r.RelationshipCategoryName="Family";r.RelationshipTypeName="Parent";r.StartSceneID=null;
role="Viewer";try{await edit.Read(12,22,9,"scene");throw new Exception("viewer accepted");}catch(UnauthorizedAccessException){Check(true,"read-only relationship correction rejected");}
}
}

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-lenses")){await ContextRelationshipLensTests.Run();return;}
if(args.Contains("--context-names")){await ContextNamesTests.Run();return;}
if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;}
if(args.Contains("--context-characters")){await ContextCharacterTests.Run();return;}
@ -189,6 +190,7 @@ if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;}
var tests = new (string Name, Action Test)[]
{
("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()),
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),

View File

@ -143,7 +143,7 @@ internal static class ToolbarBrowserHost
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddSingleton(FixtureProxy<IWordCompanionRepository>((name,args)=>Task.FromResult<WordCompanionBookStructureResponse?>((int)args![0]! is 12 or 13?new(){BookId=(int)args[0]!,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]},new(){ChapterId=11,Scenes=[new(){SceneId=23}]}]}:null)));
builder.Services.AddSingleton(FixtureProxy<ICharacterRepository>((name,args)=>name=="GetCharacterAsync"?Task.FromResult<Character?>((int)args![0]! ==5?new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant"}:null):throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<ICharacterRepository>((name,args)=>name switch{"GetCharacterAsync"=>Task.FromResult<Character?>((int)args![0]! is >=1 and <=120?new(){CharacterID=(int)args[0]!,ProjectID=7,CharacterName="Fixture participant"}:null),"GetRelationshipAsync"=>Task.FromResult<CharacterRelationship?>((int)args![0]! is >=1 and <=300?new(){CharacterRelationshipID=(int)args[0]!,ProjectID=7}:null),_=>throw new NotSupportedException(name)}));
builder.Services.AddSingleton(FixtureProxy<ILocationRepository>((name,args)=>name=="GetAsync"?Task.FromResult<LocationItem?>((int)args![0]! ==77?new(){LocationID=77,ProjectID=7,LocationName="Saved room"}:null):throw new NotSupportedException(name)));
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
@ -398,6 +398,7 @@ internal static class ToolbarBrowserHost
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"};
if(model.Field=="life-status"){model.Value=null;model.Options=[new("Unrecorded",""),new("Living","false"),new("Deceased","true")];}
if(model.Field is "classification" or "location")model.Options=[new("Recorded option","Saved value"),new("Other option","Other")];
using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};
if(context.Request.Query["invalid"]=="true"){data.ModelState.AddModelError("Value","Synthetic validation: draft retained.");model.Value="Entered draft";}
@ -408,6 +409,8 @@ internal static class ToolbarBrowserHost
var model=new PlotLine.Services.Context.ContextRelationshipForm{BookID=12,SceneID=22,RelationshipID=9,Mode="scene",SourceID=5,TargetID=6,TypeID=1,StateID=1,Label="Relationship development at selected scene",Notes="Saved scene note",Fingerprint="fixture",Characters=[new("Fixture participant","5"),new("Other character","6")],Types=[new("Family · Parent","1")],States=[new("Established","1")]};
using var writer=new StringWriter();await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
});
app.MapGet("/context-lenses-fixture",(HttpContext context)=>Results.Json(ContextRelationshipBrowserFixture.Graph(context)));
app.MapGet("/context-lenses-lookup-fixture",()=>Results.Json(new[]{new{id=7,name="An established relative with a deliberately long name 7",archived=false}}));
app.MapGet("/context-names-fixture/{part}",ContextNamesBrowserFixture.Render);
app.MapGet("/context-tab-fixture/{tool}",async context=>
{
@ -425,6 +428,7 @@ internal static class ToolbarBrowserHost
var appearances=scene.SceneCharacters.Concat(new SceneCharacter[]{new(){CharacterID=5,SceneID=21,PresenceTypeName="Present",LocationID=78},new(){CharacterID=5,SceneID=23,PresenceTypeName="Present",LocationID=79}}).ToList();
model.CharacterExplorer=PlotLine.Services.Context.ContextCharacterPanels.Compose(model,catalogue,appearances,[new(){LocationID=77,LocationName="Saved room"},new(){LocationID=78,LocationName="Earlier hall"},new(){LocationID=79,LocationName="Following garden"}],true);
model.ContextRelationshipCanEdit=true;
model.RelationshipMap=new(){Relationships=[new(){CharacterRelationshipID=9,CharacterAID=5,CharacterBID=6,CharacterAName="Fixture participant",CharacterBName="A long established character name 6",RelationshipCategoryName="Family",RelationshipTypeName="Parent",CurrentStateName="Established",InitialStateEditable=true,Notes="Explicit recorded family note",History=[new(){SceneID=22,Label="Current scene",StateName="Established",Notes="An explicit development"}]},new(){CharacterRelationshipID=10,CharacterAID=5,CharacterBID=7,CharacterAName="Fixture participant",CharacterBName="Another character",RelationshipCategoryName="Social",RelationshipTypeName="Friend",CurrentStateName="Trusting",IsReciprocal=true}]};
model.NamePanel=ContextNamesBrowserFixture.Panel();
var action=new ActionContext(context,new RouteData(),new ActionDescriptor());

View File

@ -68,6 +68,7 @@ public sealed class CharactersController(ICharacterService characters) : Control
{
saveResult = await characters.SaveCharacterAsync(model);
}
catch(UnauthorizedAccessException){return Forbid();}
catch (SubscriptionLimitException ex) when (model.CharacterID == 0)
{
ModelState.AddModelError(string.Empty, ex.Message);
@ -216,6 +217,7 @@ public sealed class CharactersController(ICharacterService characters) : Control
target.Sex = source.Sex;
target.CustomSex = source.CustomSex;
target.BirthDate = source.BirthDate;
target.IsDeceased=source.IsDeceased;target.OriginalIsDeceased=source.OriginalIsDeceased;target.LifeStatusProvided=source.LifeStatusProvided;
target.AgeAtSeriesStart = source.AgeAtSeriesStart;
target.Height = source.Height;
target.EyeColour = source.EyeColour;

View File

@ -0,0 +1,12 @@
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
{
[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("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

@ -20,8 +20,8 @@ public sealed class ContextToolsController(ContextCharacterEditing editing,Conte
catch(Microsoft.Data.SqlClient.SqlException){return await Invalid(model,"The correction could not be saved. Your draft is retained; retry when the connection recovers.");}
}
[HttpGet("EditRelationship")]
public async Task<IActionResult> EditRelationship(int bookId,int sceneId,int relationshipId=0,string mode="scene")
{try{return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",await relationships.Read(bookId,sceneId,relationshipId,mode));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}}
public async Task<IActionResult> EditRelationship(int bookId,int sceneId,int relationshipId=0,string mode="scene",string referenceLens="story")
{try{return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",await relationships.Read(bookId,sceneId,relationshipId,mode,referenceLens));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}}
[HttpPost("EditRelationship"),ValidateAntiForgeryToken]
public async Task<IActionResult> SaveRelationship(ContextRelationshipForm model)
{
@ -33,7 +33,7 @@ public sealed class ContextToolsController(ContextCharacterEditing editing,Conte
private async Task<IActionResult> InvalidRelationship(ContextRelationshipForm input,string error)
{
ContextRelationshipForm frame;
try{frame=await relationships.Read(input.BookID,input.SceneID,input.RelationshipID,input.Mode);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}
try{frame=await relationships.Read(input.BookID,input.SceneID,input.RelationshipID,input.Mode,input.ReferenceLens);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}
frame.SourceID=input.SourceID;frame.TargetID=input.TargetID;frame.TypeID=input.TypeID;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Mutual=input.Mutual;frame.Known=input.Known;frame.Notes=input.Notes;frame.Fingerprint=input.Fingerprint;
ModelState.AddModelError("",error);Response.StatusCode=422;return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",frame);
}

View File

@ -18,7 +18,7 @@ public sealed class WritingController(
IStoryContextService storyContext,
IRelationshipMapService relationshipMap,
IFloorPlanService floorPlans,
ILogger<WritingController> logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null,PlotLine.Services.Context.ContextNames? contextNames=null) : Controller
ILogger<WritingController> logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null,PlotLine.Services.Context.ContextNames? contextNames=null,PlotLine.Services.Context.ContextRelationshipLenses? relationshipLenses=null) : Controller
{
[HttpGet("Context")]
public async Task<IActionResult> Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null)
@ -126,12 +126,17 @@ public sealed class WritingController(
var target = nativeRequest ? await NativeTarget(bookId, instanceId, sessionId) : null;
if (nativeRequest && (target == null || target.SceneId != sceneId || (chapterId.HasValue && target.ChapterId != chapterId)))
return Conflict(new { message = "Word position changed or is awaiting verification." });
var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene");
WritingContextDisplayViewModel? model;
if(partial=="_ContextRelationships"&&relationshipLenses!=null&&bookId.HasValue){
try{var scope=await relationshipLenses.Scope(bookId.Value,sceneId.Value);if(projectId.HasValue&&projectId!=scope.Book.ProjectID||chapterId.HasValue&&chapterId!=scope.Scene.ChapterID)return BadRequest();
model=new(){Context=new(){Position=new(scope.Book.ProjectID,scope.Book.BookID,scope.Scene.ChapterID,sceneId),Scene=scope.Scene},ContextRelationshipCanEdit=scope.CanEdit};
}catch(UnauthorizedAccessException){return Forbid();}
}else model=await BuildDisplayAsync(projectId,bookId,chapterId,sceneId,"Saved scene");
if (nativeRequest && !SameNativeTarget(target, await NativeTarget(bookId, instanceId, sessionId)))
return Conflict(new { message = "Word position changed while context was loading." });
if (model?.HasScene != true) return NotFound();
if (projectAccess == null || !await projectAccess.CanAccessProjectAsync(model.Context!.Position.ProjectId)) return Forbid();
if((partial=="_WritingContextPeople"||partial=="_ContextRelationships")&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model);
if(partial=="_WritingContextPeople"&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model);
ViewData["ContextTabPartial"] = partial;
return PartialView("_ContextTab", model);
}

View File

@ -0,0 +1,24 @@
using System.Data;using System.Text.Json;using Dapper;using PlotLine.Models;using PlotLine.Services;
namespace PlotLine.Data;
public sealed record ContextLensRead(RelationshipMapData Data,int? FocusCharacterID,bool Truncated);
public interface IContextRelationshipReader
{
Task<ContextLensRead> Read(int project,int user,int scene,int? focus,string lens,int depth,IReadOnlyList<int> physical,CancellationToken cancellationToken=default);
Task<IReadOnlyList<Character>> Lookup(int project,int user,string search,CancellationToken cancellationToken=default);
}
public sealed class ContextRelationshipReader(ISqlConnectionFactory connectionFactory,IConfiguration configuration):IContextRelationshipReader
{
private sealed record Boundary(int? FocusCharacterID,bool Truncated);
public async Task<ContextLensRead> Read(int project,int user,int scene,int? focus,string lens,int depth,IReadOnlyList<int> physical,CancellationToken cancellationToken=default)
{
using var db=connectionFactory.CreateConnection();IReadOnlyList<Book> books;IReadOnlyList<Chapter> chapters;IReadOnlyList<Scene> scenes;IReadOnlyList<Character> people;IReadOnlyList<CharacterRelationship> links;Boundary boundary;
using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextRelationshipLens_Read",new{ProjectID=project,UserID=user,FocusCharacterID=focus,Lens=lens,Depth=depth,PhysicalIDs=JsonSerializer.Serialize(physical)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))){books=(await grid.ReadAsync<Book>()).ToList();chapters=(await grid.ReadAsync<Chapter>()).ToList();scenes=(await grid.ReadAsync<Scene>()).ToList();people=(await grid.ReadAsync<Character>()).ToList();links=(await grid.ReadAsync<CharacterRelationship>()).ToList();boundary=await grid.ReadSingleAsync<Boundary>();}
if(books.Count>20000||chapters.Count>20000||scenes.Count>20000)throw new ArgumentException("This project exceeds the Context narrative-order limit. Use the full Relationships Editor.");
var order=StoryStateService.OrderScenes(new(){Books=books,Chapters=chapters,Scenes=scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var at=lens=="family"?order.Count-1:order.FirstOrDefault(s=>s.SceneID==scene)?.Ordinal??-1;
var changes=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(links.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=at},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();
await ParagraphEvidenceProjection.Apply(db,configuration,changes);
return new(new(){Books=books,Chapters=chapters,Scenes=scenes,Characters=people,Relationships=links,RelationshipEvents=changes},boundary.FocusCharacterID,boundary.Truncated);
}
public async Task<IReadOnlyList<Character>> Lookup(int project,int user,string search,CancellationToken cancellationToken=default)
{using var db=connectionFactory.CreateConnection();return (await db.QueryAsync<Character>(new CommandDefinition("dbo.ContextCharacter_Lookup",new{ProjectID=project,UserID=user,Search=search},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();}
}

View File

@ -215,7 +215,9 @@ public interface ICharacterRepository
Task<CharacterLookupData> GetLookupsAsync(int? projectId = null);
Task<IReadOnlyList<Character>> ListCharactersAsync(int projectId);
Task<Character?> GetCharacterAsync(int characterId);
Task<int> SaveCharacterAsync(Character character);
Task<int> SaveCharacterAsync(Character character,bool updateLifeStatus=false,bool? expectedIsDeceased=null,int? userId=null);
Task<Character?> GetReferenceCharacterAsync(int characterId,int userId);
Task SaveLifeStatusAsync(int characterId,int userId,bool? isDeceased,bool? expectedIsDeceased);
Task<IReadOnlyList<CharacterAlias>> ListAliasesAsync(int characterId);
Task<IReadOnlyList<CharacterAlias>> ListProjectAliasesAsync(int projectId,int userId);
Task<int> AddAliasAsync(int characterId, string alias, int? sortOrder);
@ -3746,7 +3748,7 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory,
return await connection.QuerySingleOrDefaultAsync<Character>("dbo.Character_Get", new { CharacterID = characterId }, commandType: CommandType.StoredProcedure);
}
public async Task<int> SaveCharacterAsync(Character character)
public async Task<int> SaveCharacterAsync(Character character,bool updateLifeStatus=false,bool? expectedIsDeceased=null,int? userId=null)
{
using var connection = connectionFactory.CreateConnection();
return await connection.QuerySingleAsync<int>(
@ -3768,11 +3770,17 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory,
character.ShowInQuickAddBar,
character.DefaultDescription,
character.ImagePath,
character.ThumbnailPath
character.ThumbnailPath,
character.IsDeceased,UpdateLifeStatus=updateLifeStatus,ExpectedIsDeceased=expectedIsDeceased,UserID=userId
},
commandType: CommandType.StoredProcedure);
}
public async Task<Character?> GetReferenceCharacterAsync(int characterId,int userId)
{using var db=connectionFactory.CreateConnection();return await db.QuerySingleOrDefaultAsync<Character>("dbo.Character_GetReferenceForUser",new{CharacterID=characterId,UserID=userId},commandType:CommandType.StoredProcedure);}
public async Task SaveLifeStatusAsync(int characterId,int userId,bool? isDeceased,bool? expectedIsDeceased)
{using var db=connectionFactory.CreateConnection();await db.ExecuteAsync("dbo.Character_LifeStatus_Save",new{CharacterID=characterId,UserID=userId,IsDeceased=isDeceased,ExpectedIsDeceased=expectedIsDeceased},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<CharacterAlias>> ListProjectAliasesAsync(int projectId,int userId)
{
using var connection=connectionFactory.CreateConnection();

View File

@ -1037,6 +1037,8 @@ public sealed class Character
public int? SexValueID { get; set; }
public string? Sex { get; set; }
public DateTime? BirthDate { get; set; }
[System.Text.Json.Serialization.JsonIgnore(Condition=System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public bool? IsDeceased {get;set;}
public int? AgeAtSeriesStart { get; set; }
public int? AgeReferenceSceneID { get; set; }
public string? Height { get; set; }

View File

@ -294,6 +294,8 @@ public class Program
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterPanels>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextNames>();
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.Services.Context.ContextCharacterEditing>();
builder.Services.AddSingleton<IManuscriptScanPreviewStore, ManuscriptScanPreviewStore>();
builder.Services.AddSingleton<IOnboardingStoryIntelligenceBatchStore, OnboardingStoryIntelligenceBatchStore>();

View File

@ -30,11 +30,12 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException();
var project=await projects.GetForUserAsync(book.ProjectID,author);
if(!ContextEditPolicy.CanEdit(project))throw new UnauthorizedAccessException();
var character=await characters.GetEditCharacterAsync(characterId)??throw new UnauthorizedAccessException();
var reference=field=="life-status"?await characters.GetReferenceCharacterAsync(characterId):null;
var character=field=="life-status"?(reference==null?throw new UnauthorizedAccessException():new CharacterEditViewModel{CharacterID=reference.CharacterID,ProjectID=reference.ProjectID,CharacterName=reference.CharacterName,IsDeceased=reference.IsDeceased,OriginalIsDeceased=reference.IsDeceased,LifeStatusProvided=true}):await characters.GetEditCharacterAsync(characterId)??throw new UnauthorizedAccessException();
if(character.ProjectID!=book.ProjectID)throw new UnauthorizedAccessException();
SceneEditViewModel? scene=null;PlotLine.Models.SceneCharacter? appearance=null;
var labels=new Dictionary<string,string>{{"classification","Character classification"},{"description","Character description"},{"emotion","Emotional state in this scene"},{"condition","Physical condition in this scene"},{"location","Recorded location in this scene"}};
var aliases=await repository.ListAliasesAsync(characterId);
var labels=new Dictionary<string,string>{{"life-status","Life status · global author reference"},{"classification","Character classification"},{"description","Character description"},{"emotion","Emotional state in this scene"},{"condition","Physical condition in this scene"},{"location","Recorded location in this scene"}};
IReadOnlyList<PlotLine.Models.CharacterAlias> aliases=field=="life-status"?[]:await repository.ListAliasesAsync(characterId);
var selectedAlias=field.StartsWith("alias:")&&int.TryParse(field[6..],out var aliasId)?aliases.SingleOrDefault(a=>a.CharacterAliasID==aliasId):null;
labels["name"]="Canonical name (previous spelling retained as an alias)";labels["alias-add"]="Add one alias";
if(selectedAlias!=null)labels[field]="Correct alias (clear to remove this alias)";
@ -44,14 +45,15 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
scene=(await stories.GetForSceneAsync(sceneId,book.ProjectID,bookId,forWriting:true,includeNarrative:false))?.Scene??throw new UnauthorizedAccessException();
appearance=scene.SceneCharacters.SingleOrDefault(a=>a.CharacterID==characterId)??throw new UnauthorizedAccessException();
}
var value=field switch{"classification"=>character.CharacterImportance?.ToString(),"description"=>character.DefaultDescription,"emotion"=>appearance?.EmotionalState,"condition"=>appearance?.PhysicalCondition,"location"=>appearance?.LocationID?.ToString(),"name"=>character.CharacterName,"alias-add"=>"",_=>selectedAlias?.Alias};
var value=field switch{"classification"=>character.CharacterImportance?.ToString(),"description"=>character.DefaultDescription,"emotion"=>appearance?.EmotionalState,"condition"=>appearance?.PhysicalCondition,"location"=>appearance?.LocationID?.ToString(),"life-status"=>character.IsDeceased?.ToString().ToLowerInvariant(),"name"=>character.CharacterName,"alias-add"=>"",_=>selectedAlias?.Alias};
IReadOnlyList<SelectListItem> options=[];
if(field=="life-status")options=[new("Unrecorded",""),new("Living · author reference","false"),new("Deceased · author reference","true")];
if(field=="classification"){
var choices=new List<SelectListItem>{new("Unclassified",""),new("Major · author choice","10"),new("Supporting","6"),new("Minor","2")};
if(value!=null&&choices.All(c=>c.Value!=value))choices.Add(new("Current recorded classification ("+value+")",value));options=choices;
}
if(field=="location")options=[new("No recorded location",""),..scene!.LocationOptions];
var hash=appearance!=null?Hash(new{appearance.SceneCharacterID,appearance.SceneID,appearance.CharacterID,appearance.RoleInSceneTypeID,appearance.PresenceTypeID,appearance.LocationID,appearance.EntryLocationID,appearance.ExitLocationID,appearance.AppearanceNotes,appearance.OutfitDescription,appearance.EmotionalState,appearance.PhysicalCondition,appearance.KnowledgeNotes}):Hash(new{character.CharacterID,character.CharacterName,character.Aliases,character.CharacterImportance,character.DefaultDescription,character.SexValueID,character.Sex,character.BirthDate,character.AgeAtSeriesStart,character.Height,character.EyeColour,character.ShowInQuickAddBar,character.ImagePath,character.ThumbnailPath,AliasRecords=aliases});
var hash=appearance!=null?Hash(new{appearance.SceneCharacterID,appearance.SceneID,appearance.CharacterID,appearance.RoleInSceneTypeID,appearance.PresenceTypeID,appearance.LocationID,appearance.EntryLocationID,appearance.ExitLocationID,appearance.AppearanceNotes,appearance.OutfitDescription,appearance.EmotionalState,appearance.PhysicalCondition,appearance.KnowledgeNotes}):Hash(new{character.CharacterID,character.CharacterName,character.Aliases,character.CharacterImportance,character.DefaultDescription,character.SexValueID,character.Sex,character.BirthDate,character.IsDeceased,character.AgeAtSeriesStart,character.Height,character.EyeColour,character.ShowInQuickAddBar,character.ImagePath,character.ThumbnailPath,AliasRecords=aliases});
return new(new(){BookID=bookId,SceneID=sceneId,CharacterID=characterId,Field=field,Value=value,Label=labels[field],CharacterName=character.CharacterName,Fingerprint=hash,Options=options},character,scene,appearance);
}
public async Task Save(ContextCharacterEditForm input)
@ -88,6 +90,9 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
}else if(input.Field=="classification"){
int? importance=null;if(!string.IsNullOrWhiteSpace(input.Value)){if(!int.TryParse(input.Value,out var parsed)||(!new[]{2,6,10}.Contains(parsed)&&parsed!=frame.Character.CharacterImportance))throw new ArgumentException("Choose a recorded classification.");importance=parsed;}
frame.Character.CharacterImportance=importance;await characters.SaveCharacterAsync(frame.Character);
}else if(input.Field=="life-status"){
if(!frame.Form.Options.Any(o=>o.Value==(input.Value??"")))throw new ArgumentException("Choose Unrecorded, Living or Deceased.");
await characters.SaveLifeStatusAsync(input.CharacterID,string.IsNullOrEmpty(input.Value)?null:bool.Parse(input.Value),frame.Character.IsDeceased);
}else if(input.Field=="description"){frame.Character.DefaultDescription=input.Value;await characters.SaveCharacterAsync(frame.Character);}
else{
var a=frame.Appearance!;var edit=new SceneCharacterEditViewModel{SceneCharacterID=a.SceneCharacterID,SceneID=a.SceneID,CharacterID=a.CharacterID,RoleInSceneTypeID=a.RoleInSceneTypeID,PresenceTypeID=a.PresenceTypeID,LocationID=a.LocationID,EntryLocationID=a.EntryLocationID,ExitLocationID=a.ExitLocationID,AppearanceNotes=a.AppearanceNotes,OutfitDescription=a.OutfitDescription,PhysicalCondition=a.PhysicalCondition,EmotionalState=a.EmotionalState,KnowledgeNotes=a.KnowledgeNotes};

View File

@ -9,7 +9,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Services.Context;
public sealed class ContextRelationshipForm
{
public int BookID{get;set;}public int SceneID{get;set;}public int RelationshipID{get;set;}public string Mode{get;set;}="scene";public string Fingerprint{get;set;}="";
public int BookID{get;set;}public int SceneID{get;set;}public int RelationshipID{get;set;}public string Mode{get;set;}="scene";public string Fingerprint{get;set;}="";public string ReferenceLens{get;set;}="story";
public int SourceID{get;set;}public int TargetID{get;set;}public int TypeID{get;set;}public int StateID{get;set;}
[Range(1,10)]public int? Intensity{get;set;}public bool Mutual{get;set;}public bool Known{get;set;}[StringLength(4000)]public string? Notes{get;set;}
public string Label{get;set;}="";public IReadOnlyList<SelectListItem> Characters{get;set;}=[];public IReadOnlyList<SelectListItem> Types{get;set;}=[];public IReadOnlyList<SelectListItem> States{get;set;}=[];
@ -19,9 +19,10 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
{
private static readonly SemaphoreSlim[] Locks=Enumerable.Range(0,64).Select(_=>new SemaphoreSlim(1,1)).ToArray();
private sealed record Frame(ContextRelationshipForm Form,RelationshipMapData Data,CharacterRelationship? Relationship,RelationshipEvent? Event,CharacterLookupData Lookups,int ProjectID);
public async Task<ContextRelationshipForm> Read(int bookId,int sceneId,int relationshipId,string mode)=>(await Load(bookId,sceneId,relationshipId,mode)).Form;
private async Task<Frame> Load(int bookId,int sceneId,int relationshipId,string mode)
public async Task<ContextRelationshipForm> Read(int bookId,int sceneId,int relationshipId,string mode,string referenceLens="story")=>(await Load(bookId,sceneId,relationshipId,mode,referenceLens)).Form;
private async Task<Frame> Load(int bookId,int sceneId,int relationshipId,string mode,string referenceLens)
{
if(referenceLens is not ("family" or "story"))throw new ArgumentException("Choose a supported reference lens.");
var author=user.UserId??throw new UnauthorizedAccessException();var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException();
if(!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))throw new UnauthorizedAccessException();
var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException();if(!ContextEditPolicy.CanEdit(await projects.GetForUserAsync(book.ProjectID,author)))throw new UnauthorizedAccessException();
@ -29,19 +30,20 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
var data=await repository.GetRelationshipMapAsync(book.ProjectID);var lookups=await repository.GetLookupsAsync(book.ProjectID);
var relation=relationshipId>0?data.Relationships.SingleOrDefault(r=>r.CharacterRelationshipID==relationshipId&&!r.IsArchived):null;
if(relationshipId>0&&(relation==null||relation.ProjectID!=book.ProjectID))throw new UnauthorizedAccessException();
if(referenceLens=="family"&&relation!=null&&!ContextRelationshipLenses.Family(relation.RelationshipCategoryName,relation.RelationshipTypeName))throw new ArgumentException("Choose an established family connection.");
if(mode=="initial"&&relation!=null&&!relation.IsInitialRelationship)throw new ArgumentException("This relationship starts in a scene. Correct its development rather than adding an earlier initial state.");
var events=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==relationshipId&&e.SceneID==sceneId).ToList();
if(mode=="scene"&&(events.Count>1||events.Any(e=>e.EvidenceState!="Verified")))throw new ArgumentException("Review multiple or unverified scene events in the full Relationships Editor before correcting this relationship.");
var change=mode=="scene"?events.SingleOrDefault():null;
var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i);
var projected=RelationshipMapService.BuildAtScene(data,order,sceneId).SingleOrDefault(r=>r.CharacterRelationshipID==relationshipId);
if(relation!=null&&projected==null)throw new ArgumentException("This relationship is not established at the selected story point.");
if(relation!=null&&projected==null&&!(referenceLens=="family"&&mode=="initial"))throw new ArgumentException("This relationship is not established at the selected story point.");
var state=mode=="initial"?relation?.InitialRelationshipStateID:change?.RelationshipStateID??lookups.RelationshipStates.FirstOrDefault(s=>s.StateName==projected?.CurrentStateName)?.RelationshipStateID;
var form=new ContextRelationshipForm{BookID=bookId,SceneID=sceneId,RelationshipID=relationshipId,Mode=mode,SourceID=relation?.CharacterAID??0,TargetID=relation?.CharacterBID??0,TypeID=relation?.RelationshipTypeID??0,StateID=state??0,
var form=new ContextRelationshipForm{BookID=bookId,SceneID=sceneId,RelationshipID=relationshipId,Mode=mode,ReferenceLens=referenceLens,SourceID=relation?.CharacterAID??0,TargetID=relation?.CharacterBID??0,TypeID=relation?.RelationshipTypeID??0,StateID=state??0,
Intensity=mode=="initial"?relation?.InitialIntensity:change?.Intensity??projected?.CurrentIntensity,Mutual=relation?.IsReciprocal??false,Known=mode=="initial"?relation?.ReaderInitiallyKnows??false:change?.IsKnownToOtherCharacter??false,
Notes=mode=="initial"?relation?.Notes:change?.Description,Label=mode=="initial"?"Initial relationship (before scene developments)":"Relationship development at the selected scene",
Notes=mode=="initial"?relation?.Notes:change?.Description,Label=mode=="initial"?(referenceLens=="family"?"Author-established initial family connection":"Initial relationship (before scene developments)"):"Relationship development at "+(data.Scenes.FirstOrDefault(s=>s.SceneID==sceneId)?.SceneTitle??"the selected scene"),
Characters=data.Characters.Where(c=>!c.IsArchived).OrderBy(c=>c.CharacterName).Select(c=>new SelectListItem(c.CharacterName,c.CharacterID.ToString())).ToList(),
Types=lookups.RelationshipTypes.Where(t=>t.IsActive||t.RelationshipTypeID==relation?.RelationshipTypeID).Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToList(),
Types=lookups.RelationshipTypes.Where(t=>(t.IsActive||t.RelationshipTypeID==relation?.RelationshipTypeID)&&(referenceLens!="family"||ContextRelationshipLenses.Family(t.RelationshipCategoryName,t.TypeName))).Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToList(),
States=lookups.RelationshipStates.Where(s=>s.IsActive||s.RelationshipStateID==state).Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToList()};
form.Fingerprint=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new{relation,Events=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==relationshipId).ToList(),Matches=data.Relationships.Select(r=>new{r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID,r.RelationshipTypeID,r.IsReciprocal,r.IsArchived})}))));
return new(form,data,relation,change,lookups,book.ProjectID);
@ -49,7 +51,7 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
public async Task Save(ContextRelationshipForm input)
{
var mutex=Locks[(input.BookID&int.MaxValue)%Locks.Length];await mutex.WaitAsync();try{
var frame=await Load(input.BookID,input.SceneID,input.RelationshipID,input.Mode);var f=frame.Form;var r=frame.Relationship;
var frame=await Load(input.BookID,input.SceneID,input.RelationshipID,input.Mode,input.ReferenceLens);var f=frame.Form;var r=frame.Relationship;
if(f.Fingerprint!=input.Fingerprint)throw new InvalidOperationException("Relationships changed in another window. Your draft is retained; cancel and reopen current values.");
if(input.SourceID==input.TargetID||!f.Characters.Any(c=>c.Value==input.SourceID.ToString())||!f.Characters.Any(c=>c.Value==input.TargetID.ToString())||!f.Types.Any(t=>t.Value==input.TypeID.ToString())||!f.States.Any(s=>s.Value==input.StateID.ToString()))throw new ArgumentException("Choose two different project characters and a recorded relationship type and state.");
if(input.Intensity is <1 or >10||input.Notes?.Length>4000)throw new ArgumentException("Intensity must be 1–10 and notes at most 4,000 characters.");

View File

@ -0,0 +1,45 @@
using PlotLine.Data;using PlotLine.Models;using PlotLine.ViewModels;
namespace PlotLine.Services.Context;
public sealed record ContextLensNode(int ID,string Name,DateTime? BirthDate,bool Archived,bool Physical,string? Avatar,bool? IsDeceased=null);
public sealed record ContextLensLink(int ID,int A,int B,string Type,string Category,string State,bool Reciprocal,bool Initial,int? StartSceneID,int? EndSceneID,int? EditSceneID,string? Notes,IReadOnlyList<RelationshipMapHistoryItemViewModel> Recent);
public sealed record ContextLensGraph(string Lens,int? FocusID,int? PovID,int SceneID,string SceneTitle,bool CanEdit,bool Truncated,IReadOnlyList<ContextLensNode> Nodes,IReadOnlyList<ContextLensLink> Links);
public sealed class ContextRelationshipLenses(IContextRelationshipReader reader,ICharacterRepository characters,IWordCompanionRepository access,IBookRepository books,IProjectRepository projects,ICurrentUserService user,IStoryContextService stories)
{
public static bool Physical(SceneCharacter c)=>c.RoleInSceneTypeName!="Mentioned Only"&&c.PresenceTypeName is "Present" or "Arrives" or "Leaves" or "Nearby" or "Hidden" or "Overhearing";
public static bool Family(string category,string type)=>category=="Family"||category=="Romantic / Sexual"&&type is "Spouse" or "Partner" or "Ex-spouse" or "Former spouse" or "Romantic Partner";
public async Task<(Book Book,SceneEditViewModel Scene,bool CanEdit)> Scope(int bookId,int sceneId)
{
var author=user.UserId??throw new UnauthorizedAccessException();var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException();
if(!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))throw new UnauthorizedAccessException();var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException();var project=await projects.GetForUserAsync(book.ProjectID,author)??throw new UnauthorizedAccessException();
var scene=(await stories.GetForSceneAsync(sceneId,book.ProjectID,bookId,forWriting:true,includeNarrative:false))?.Scene??throw new UnauthorizedAccessException();return(book,scene,ContextEditPolicy.CanEdit(project));
}
public async Task<ContextLensGraph> Graph(int bookId,int sceneId,string lens,int? focus,int depth,CancellationToken cancellationToken=default)
{
if(lens is not ("family" or "story")||depth is <1 or >6)throw new ArgumentException("Choose Family or Story and a depth from 1 to 6.");var scope=await Scope(bookId,sceneId);
var physical=scope.Scene.SceneCharacters.Where(Physical).OrderByDescending(c=>c.CharacterID==scope.Scene.POVCharacterID).Select(c=>c.CharacterID).Distinct().Take(32).ToArray();
focus??=lens=="family"?scope.Scene.POVCharacterID:physical.FirstOrDefault() is >0?physical.First():scope.Scene.POVCharacterID;
if(!focus.HasValue&&scope.Scene.SceneCharacters.FirstOrDefault() is {} participant)focus=participant.CharacterID;
if(lens=="story"&&!focus.HasValue)return new(lens,null,scope.Scene.POVCharacterID,sceneId,scope.Scene.SceneTitle,scope.CanEdit,false,[],[]);
if(focus.HasValue&&(await characters.GetReferenceCharacterAsync(focus.Value,user.UserId!.Value))?.ProjectID!=scope.Book.ProjectID)throw new UnauthorizedAccessException();
var read=await reader.Read(scope.Book.ProjectID,user.UserId!.Value,sceneId,focus,lens,depth,physical,cancellationToken);
return Compose(read,lens,scope.Scene,scope.CanEdit);
}
public static ContextLensGraph Compose(ContextLensRead read,string lens,SceneEditViewModel scene,bool canEdit)
{
var data=read.Data;var physical=scene.SceneCharacters.Where(Physical).Select(c=>c.CharacterID).ToHashSet();var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i);
var projected=lens=="story"?RelationshipMapService.BuildAtScene(data,order,scene.SceneID):[];
var projectedById=projected.ToDictionary(r=>r.CharacterRelationshipID);var links=new List<ContextLensLink>();
foreach(var r in data.Relationships){if(lens=="family"&&!Family(r.RelationshipCategoryName,r.RelationshipTypeName))continue;if(lens=="story"&&!projectedById.ContainsKey(r.CharacterRelationshipID))continue;
var p=projectedById.GetValueOrDefault(r.CharacterRelationshipID);var recent=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==r.CharacterRelationshipID&&e.EvidenceState=="Verified"&&(lens=="family"||order.GetValueOrDefault(e.SceneID,int.MaxValue)<=order.GetValueOrDefault(scene.SceneID,-1))).OrderByDescending(e=>order.GetValueOrDefault(e.SceneID,-1)).ThenByDescending(e=>e.CreatedDate).ThenByDescending(e=>e.RelationshipEventID).Take(3).ToList();
var history=recent.Select(e=>new RelationshipMapHistoryItemViewModel{SceneID=e.SceneID,Label=$"{e.BookDisplayTitle} · Ch {e.ChapterNumber} · Scene {e.SceneNumber}: {e.SceneTitle}",StateName=e.RelationshipStateName,Notes=e.Description,Intensity=e.Intensity}).ToList();
var editScene=r.IsInitialRelationship?scene.SceneID:r.StartSceneID;
var activeBook=data.Chapters.FirstOrDefault(c=>c.ChapterID==scene.ChapterID)?.BookID;
if(editScene.HasValue&&data.Chapters.FirstOrDefault(c=>c.ChapterID==data.Scenes.FirstOrDefault(s=>s.SceneID==editScene)?.ChapterID)?.BookID!=activeBook)editScene=null;
links.Add(new(r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID,r.RelationshipTypeName,r.RelationshipCategoryName,p?.CurrentStateName??recent.FirstOrDefault()?.RelationshipStateName??r.InitialRelationshipStateName??r.RelationshipTypeName,r.IsReciprocal,r.IsInitialRelationship,r.StartSceneID,r.EndSceneID,editScene,p?.Notes??recent.FirstOrDefault()?.Description??r.Notes,history));
}
var visible=links.SelectMany(r=>new[]{r.A,r.B}).Concat(physical).Append(read.FocusCharacterID??0).ToHashSet();
var nodes=data.Characters.Where(c=>visible.Contains(c.CharacterID)).Select(c=>new ContextLensNode(c.CharacterID,c.CharacterName,c.BirthDate,c.IsArchived,physical.Contains(c.CharacterID),c.AvatarThumbnailPath??c.AvatarImagePath,lens=="family"?c.IsDeceased:null)).ToList();
return new(lens,read.FocusCharacterID,scene.POVCharacterID,scene.SceneID,scene.SceneTitle,canEdit,read.Truncated,nodes,links);
}
public async Task<IReadOnlyList<Character>> Lookup(int bookId,int sceneId,string search,CancellationToken cancellationToken=default){if(search.Length is <2 or >120)return [];var scope=await Scope(bookId,sceneId);return await reader.Lookup(scope.Book.ProjectID,user.UserId!.Value,search,cancellationToken);}
}

View File

@ -278,6 +278,8 @@ public interface ICharacterService
Task<CharacterMergeViewModel?> GetMergeAsync(int sourceCharacterId);
Task<CharacterAvatarCropViewModel?> GetAvatarCropAsync(int characterImageId);
Task<CharacterSaveResult> SaveCharacterAsync(CharacterEditViewModel model);
Task<Character?> GetReferenceCharacterAsync(int characterId);
Task SaveLifeStatusAsync(int characterId,bool? isDeceased,bool? expectedIsDeceased);
Task<CharacterEnrichmentRun?> QueueCharacterReanalysisAsync(int characterId);
Task SetPreferredNameAsync(int characterId, string preferredName);
Task<CharacterMergeResult?> MergeAsync(CharacterMergeForm form);
@ -9635,7 +9637,7 @@ public sealed class CharacterService(
var project = await projects.GetAsync(projectId);
return project is null
? null
: await PopulateCharacterEditOptionsAsync(new CharacterEditViewModel { ProjectID = projectId, Project = project, CharacterImportance = 6 });
: await PopulateCharacterEditOptionsAsync(new CharacterEditViewModel { ProjectID = projectId, Project = project, CharacterImportance = 6,LifeStatusProvided=true });
}
public async Task<CharacterEditViewModel?> GetEditCharacterAsync(int characterId)
@ -9654,7 +9656,7 @@ public sealed class CharacterService(
Aliases = (await characters.ListAliasesAsync(character.CharacterID)).Select(x => x.Alias).ToList(),
SexValueID = character.SexValueID,
Sex = character.Sex,
BirthDate = character.BirthDate,
BirthDate = character.BirthDate,IsDeceased=character.IsDeceased,OriginalIsDeceased=character.IsDeceased,LifeStatusProvided=true,
AgeAtSeriesStart = character.AgeAtSeriesStart,
Height = character.Height,
EyeColour = character.EyeColour,
@ -9819,6 +9821,13 @@ public sealed class CharacterService(
};
}
public Task<Character?> GetReferenceCharacterAsync(int characterId)=>characters.GetReferenceCharacterAsync(characterId,currentUser.UserId??throw new UnauthorizedAccessException());
public async Task SaveLifeStatusAsync(int characterId,bool? isDeceased,bool? expectedIsDeceased)
{try{await characters.SaveLifeStatusAsync(characterId,currentUser.UserId??throw new UnauthorizedAccessException(),isDeceased,expectedIsDeceased);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51010){throw new UnauthorizedAccessException();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51011){throw new InvalidOperationException("Life status changed in another window. Reload the current value before correcting it.");}}
private async Task<int> SaveCanonicalCharacter(Character character,bool updateLifeStatus,bool? expected,int? author)
{try{return await characters.SaveCharacterAsync(character,updateLifeStatus,expected,author);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51010){throw new UnauthorizedAccessException();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51011){throw new InvalidOperationException("Life status changed in another window. Reload the current value before correcting it.");}}
public async Task<CharacterSaveResult> SaveCharacterAsync(CharacterEditViewModel model)
{
if (model.CharacterID == 0)
@ -9829,7 +9838,7 @@ public sealed class CharacterService(
var isNew = model.CharacterID == 0;
var existing = isNew ? null : await characters.GetCharacterAsync(model.CharacterID);
var sex = await ResolveCharacterSexAsync(model.ProjectID, model.SexValueID, model.CustomSex, model.Sex);
var characterId = await characters.SaveCharacterAsync(new Character
var characterId = await SaveCanonicalCharacter(new Character
{
CharacterID = model.CharacterID,
ProjectID = model.ProjectID,
@ -9837,7 +9846,7 @@ public sealed class CharacterService(
ShortName = existing?.ShortName,
SexValueID = sex.SexValueID,
Sex = sex.SexName,
BirthDate = model.BirthDate?.Date,
BirthDate = model.BirthDate?.Date,IsDeceased=model.IsDeceased,
AgeAtSeriesStart = model.AgeAtSeriesStart,
AgeReferenceSceneID = existing?.AgeReferenceSceneID,
Height = model.Height,
@ -9847,7 +9856,7 @@ public sealed class CharacterService(
DefaultDescription = model.DefaultDescription,
ImagePath = model.ImagePath ?? existing?.ImagePath,
ThumbnailPath = model.ThumbnailPath ?? existing?.ThumbnailPath
});
},model.LifeStatusProvided&&model.IsDeceased!=model.OriginalIsDeceased,model.OriginalIsDeceased,currentUser.UserId);
await SyncCharacterAliasesAsync(characterId, model.Aliases, model.CharacterName);
var imageHost = existing ?? new Character { CharacterID = characterId, ProjectID = model.ProjectID };
imageHost.CharacterID = characterId;

View File

@ -27,7 +27,7 @@ internal static partial class ProjectBackupStoredFieldContract
["CharacterIntelligenceProfiles"]=("CharacterIntelligenceProfileID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","NarrativeImportance,LastUpdatedSceneResultID"),
["CharacterKnowledge"]=("CharacterKnowledgeID,CharacterID,StoryAssetID,PlotThreadID,SceneID,KnowledgeStateID,SourceEventID,Description,CreatedDate,UpdatedDate,SourceReviewKey","StoryAssetID,PlotThreadID,SourceEventID,Description,SourceReviewKey"),
["CharacterRelationships"]=("CharacterRelationshipID,ProjectID,CharacterAID,CharacterBID,RelationshipTypeID,IsPermanent,StartSceneID,EndSceneID,IsKnownToReader,Notes,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,IsInitialRelationship,InitialBookID,ReaderInitiallyKnows,InitialRelationshipStateID,InitialIntensity,IsReciprocal,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","StartSceneID,EndSceneID,Notes,ArchivedDate,ArchivedReason,InitialBookID,InitialRelationshipStateID,InitialIntensity,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["Characters"]=("CharacterID,ProjectID,CharacterName,ShortName,Sex,BirthDate,AgeAtSeriesStart,AgeReferenceSceneID,Height,EyeColour,CharacterImportance,DefaultDescription,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,ShowInQuickAddBar,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath,AvatarSourceCharacterImageID,AvatarImagePath,AvatarThumbnailPath,SexValueID","ShortName,Sex,BirthDate,AgeAtSeriesStart,AgeReferenceSceneID,Height,EyeColour,CharacterImportance,DefaultDescription,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath,AvatarSourceCharacterImageID,AvatarImagePath,AvatarThumbnailPath,SexValueID"),
["Characters"]=("CharacterID,ProjectID,CharacterName,ShortName,Sex,BirthDate,IsDeceased,AgeAtSeriesStart,AgeReferenceSceneID,Height,EyeColour,CharacterImportance,DefaultDescription,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,ShowInQuickAddBar,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath,AvatarSourceCharacterImageID,AvatarImagePath,AvatarThumbnailPath,SexValueID","ShortName,Sex,BirthDate,IsDeceased,AgeAtSeriesStart,AgeReferenceSceneID,Height,EyeColour,CharacterImportance,DefaultDescription,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath,AvatarSourceCharacterImageID,AvatarImagePath,AvatarThumbnailPath,SexValueID"),
["ContinuityWarningAcknowledgements"]=("ContinuityWarningAcknowledgementID,ProjectID,WarningType,SceneID,CharacterID,AssetID,AcknowledgedDate,AcknowledgedByUserID,Notes","SceneID,CharacterID,AssetID,AcknowledgedByUserID,Notes"),
["ContinuityWarnings"]=("ContinuityWarningID,ValidationRunID,ProjectID,BookID,ChapterID,SceneID,EntityType,EntityID,WarningTypeID,WarningSeverityID,Message,Details,IsDismissed,IsIntentional,CreatedDate,LastDetectedDate","ValidationRunID,BookID,ChapterID,SceneID,EntityID,Details"),
["CoreImportBasicLocationCandidates"]=("CoreImportBasicLocationCandidateID,CoreImportBasicLocationReviewID,StableKey,ProposedName,PreferredName,KnownNamesJson,ParentLocationID,ParentCandidateKey,ExistingLocationID,Action,SameAsLocationID,SameAsCandidateKey,ResultLocationID,FirstChapterNumber,FirstSceneNumber,FirstOccurrenceIndex,ObservationCount,SortOrder,CreatedUtc,UpdatedUtc","ParentLocationID,ParentCandidateKey,ExistingLocationID,SameAsLocationID,SameAsCandidateKey,ResultLocationID"),

View File

@ -0,0 +1,81 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Read-only, bounded lens data over existing canonical identities and relationships.
CREATE OR ALTER PROCEDURE dbo.ContextRelationshipLens_Read
@ProjectID int,@UserID int,@FocusCharacterID int=NULL,@Lens nvarchar(12)=N'story',@Depth int=3,@PhysicalIDs nvarchar(max)=N'[]'
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND p.IsArchived=0) THROW 51000,'Project unavailable',1;
SET @Depth=CASE WHEN @Depth BETWEEN 1 AND 6 THEN @Depth ELSE 3 END;
IF @FocusCharacterID IS NULL SELECT TOP(1) @FocusCharacterID=CharacterID FROM dbo.Characters WHERE ProjectID=@ProjectID AND IsArchived=0 ORDER BY CharacterName,CharacterID;
IF @FocusCharacterID IS NULL SELECT TOP(1) @FocusCharacterID=CharacterID FROM dbo.Characters WHERE ProjectID=@ProjectID ORDER BY CharacterName,CharacterID;
IF @FocusCharacterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE ProjectID=@ProjectID AND CharacterID=@FocusCharacterID) THROW 51000,'Character unavailable',1;
DECLARE @people table(CharacterID int PRIMARY KEY,Distance int);
DECLARE @physical table(CharacterID int PRIMARY KEY);
INSERT @physical SELECT DISTINCT TOP(32) c.CharacterID FROM OPENJSON(@PhysicalIDs) j JOIN dbo.Characters c ON c.CharacterID=TRY_CONVERT(int,j.value) AND c.ProjectID=@ProjectID ORDER BY c.CharacterID;
IF @FocusCharacterID IS NOT NULL INSERT @people VALUES(@FocusCharacterID,0);
DECLARE @links table(RelationshipID int PRIMARY KEY,A int,B int);
DECLARE @truncated bit=0;
IF @Lens=N'family'
BEGIN
INSERT @links SELECT r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID FROM dbo.CharacterRelationships r JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID
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')));
DECLARE @level int=0;
WHILE @level<@Depth AND (SELECT COUNT(*) FROM @people)<128
BEGIN
DECLARE @remaining int=128-(SELECT COUNT(*) FROM @people);
INSERT @people SELECT DISTINCT TOP(@remaining) x.ID,@level+1 FROM @links l CROSS APPLY(VALUES(l.A),(l.B)) x(ID)
WHERE (EXISTS(SELECT 1 FROM @people n WHERE n.CharacterID=l.A AND n.Distance=@level) OR EXISTS(SELECT 1 FROM @people n WHERE n.CharacterID=l.B AND n.Distance=@level)) AND NOT EXISTS(SELECT 1 FROM @people n WHERE n.CharacterID=x.ID)
AND EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=x.ID AND c.ProjectID=@ProjectID) ORDER BY x.ID;
SET @level+=1;
END;
IF EXISTS(SELECT 1 FROM @links l WHERE (EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.A) AND NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.B)) OR (EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.B) AND NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.A))) SET @truncated=1;
DELETE l FROM @links l WHERE NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.A) OR NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.B);
END
ELSE
BEGIN
INSERT @people SELECT p.CharacterID,0 FROM @physical p WHERE NOT EXISTS(SELECT 1 FROM @people n WHERE n.CharacterID=p.CharacterID);
INSERT @links SELECT TOP(257) r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID FROM dbo.CharacterRelationships r WHERE r.ProjectID=@ProjectID AND r.IsArchived=0 AND (r.CharacterAID=@FocusCharacterID OR r.CharacterBID=@FocusCharacterID OR (EXISTS(SELECT 1 FROM @physical p WHERE p.CharacterID=r.CharacterAID) AND EXISTS(SELECT 1 FROM @physical p WHERE p.CharacterID=r.CharacterBID)))
ORDER BY CASE WHEN EXISTS(SELECT 1 FROM @physical p WHERE p.CharacterID=r.CharacterAID) AND EXISTS(SELECT 1 FROM @physical p WHERE p.CharacterID=r.CharacterBID) THEN 0 ELSE 1 END,r.CharacterRelationshipID;
IF (SELECT COUNT(*) FROM @links)>256 SET @truncated=1;
DECLARE @available int=128-(SELECT COUNT(*) FROM @people);
INSERT @people SELECT DISTINCT TOP(@available) x.ID,1 FROM @links l CROSS APPLY(VALUES(l.A),(l.B)) x(ID) WHERE NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=x.ID) AND EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=x.ID AND c.ProjectID=@ProjectID) ORDER BY x.ID;
IF EXISTS(SELECT 1 FROM @links l WHERE NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.A) OR NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.B)) SET @truncated=1;
DELETE l FROM @links l WHERE NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.A) OR NOT EXISTS(SELECT 1 FROM @people p WHERE p.CharacterID=l.B);
END;
IF (SELECT COUNT(*) FROM @links)>256 SET @truncated=1;
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.AvatarImagePath,c.AvatarThumbnailPath FROM dbo.Characters c JOIN @people p ON p.CharacterID=c.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY p.Distance,c.CharacterName;
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 @links l JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=l.RelationshipID JOIN dbo.Characters a ON a.CharacterID=r.CharacterAID JOIN dbo.Characters b ON b.CharacterID=r.CharacterBID 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 ORDER BY r.CharacterRelationshipID;
SELECT @FocusCharacterID AS FocusCharacterID,@truncated AS Truncated;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextRelationshipLens_Events
@ProjectID int,@UserID int,@RelationshipIDs nvarchar(max),@SceneOrder nvarchar(max),@AtOrdinal int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND p.IsArchived=0) THROW 51000,'Project unavailable',1;
IF LEN(@RelationshipIDs)>10000 OR LEN(@SceneOrder)>1500000 THROW 51000,'Lens request too large',1;
;WITH Ordinals AS(SELECT SceneID,Ordinal FROM OPENJSON(@SceneOrder) WITH(SceneID int '$.SceneID',Ordinal int '$.Ordinal')),
Ranked AS(SELECT e.RelationshipEventID,ROW_NUMBER() OVER(PARTITION BY e.CharacterRelationshipID ORDER BY o.Ordinal DESC,e.CreatedDate DESC,e.RelationshipEventID DESC) AS RowNumber
FROM dbo.RelationshipEvents e JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=e.CharacterRelationshipID JOIN Ordinals o ON o.SceneID=e.SceneID JOIN OPENJSON(@RelationshipIDs) ids ON TRY_CONVERT(int,ids.value)=e.CharacterRelationshipID
WHERE r.ProjectID=@ProjectID AND r.IsArchived=0 AND o.Ordinal<=@AtOrdinal AND NOT EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex evidence WHERE evidence.EventKind=N'Relationship' AND evidence.EventID=e.RelationshipEventID AND evidence.IsPrimary=1 AND evidence.EvidenceState<>N'Verified'))
SELECT e.*,r.ProjectID,rs.StateName AS RelationshipStateName,s.SceneTitle,s.SceneNumber,ch.ChapterNumber,b.BookTitle,b.Subtitle AS BookSubtitle FROM Ranked n JOIN dbo.RelationshipEvents e ON e.RelationshipEventID=n.RelationshipEventID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=e.CharacterRelationshipID JOIN dbo.RelationshipStates rs ON rs.RelationshipStateID=e.RelationshipStateID JOIN dbo.Scenes s ON s.SceneID=e.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE n.RowNumber<=3 ORDER BY e.CharacterRelationshipID,n.RowNumber;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextCharacter_Lookup @ProjectID int,@UserID int,@Search nvarchar(120)
AS
BEGIN
SET NOCOUNT ON;
IF LEN(LTRIM(RTRIM(@Search)))<2 RETURN;
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND p.IsArchived=0) RETURN;
DECLARE @term nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%';
SELECT TOP(25) c.CharacterID,c.CharacterName,c.BirthDate,c.IsArchived FROM dbo.Characters c WHERE c.ProjectID=@ProjectID AND (c.CharacterName LIKE @term ESCAPE N'~' OR EXISTS(SELECT 1 FROM dbo.CharacterAliases a WHERE a.CharacterID=c.CharacterID AND a.Alias LIKE @term ESCAPE N'~')) ORDER BY c.CharacterName,c.CharacterID;
END;
GO

View File

@ -0,0 +1,150 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Explicitly authorised canonical author-reference field. Existing rows stay unknown (NULL).
IF COL_LENGTH(N'dbo.Characters',N'IsDeceased') IS NULL ALTER TABLE dbo.Characters ADD IsDeceased bit NULL;
GO
CREATE OR ALTER PROCEDURE dbo.Character_Save
@CharacterID int = NULL,
@ProjectID int,
@CharacterName nvarchar(200),
@ShortName nvarchar(100) = NULL,
@SexValueID int = NULL,
@Sex nvarchar(100) = NULL,
@BirthDate date = NULL,
@AgeAtSeriesStart int = NULL,
@AgeReferenceSceneID int = NULL,
@Height nvarchar(50) = NULL,
@EyeColour nvarchar(50) = NULL,
@CharacterImportance int = NULL,
@ShowInQuickAddBar bit = 0,
@DefaultDescription nvarchar(max) = NULL,
@ImagePath nvarchar(500) = NULL,
@ThumbnailPath nvarchar(500) = NULL,
@IsDeceased bit=NULL,
@UpdateLifeStatus bit=0,
@ExpectedIsDeceased bit=NULL,
@UserID int=NULL
AS
BEGIN
SET NOCOUNT ON;
IF @UpdateLifeStatus=1 AND NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') AND p.IsArchived=0 AND (ISNULL(@CharacterID,0)=0 OR EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=@CharacterID AND c.ProjectID=@ProjectID))) THROW 51010,'Life status editing unavailable',1;
SET @CharacterName = LTRIM(RTRIM(@CharacterName));
IF @CharacterID IS NULL OR @CharacterID = 0
BEGIN
INSERT dbo.Characters (ProjectID, CharacterName, ShortName, SexValueID, Sex, BirthDate, AgeAtSeriesStart, AgeReferenceSceneID, Height, EyeColour, CharacterImportance, ShowInQuickAddBar, DefaultDescription, ImagePath, ThumbnailPath, IsDeceased)
VALUES (@ProjectID, @CharacterName, @ShortName, @SexValueID, @Sex, @BirthDate, @AgeAtSeriesStart, @AgeReferenceSceneID, @Height, @EyeColour, @CharacterImportance, @ShowInQuickAddBar, @DefaultDescription, @ImagePath, @ThumbnailPath, CASE WHEN @UpdateLifeStatus=1 THEN @IsDeceased ELSE NULL END);
SET @CharacterID = CAST(SCOPE_IDENTITY() AS int);
END
ELSE
BEGIN
UPDATE dbo.Characters
SET CharacterName = @CharacterName, ShortName = @ShortName, SexValueID = @SexValueID, Sex = @Sex, BirthDate = @BirthDate,
AgeAtSeriesStart = @AgeAtSeriesStart, AgeReferenceSceneID = @AgeReferenceSceneID,
Height = @Height, EyeColour = @EyeColour, CharacterImportance = @CharacterImportance,
ShowInQuickAddBar = @ShowInQuickAddBar, DefaultDescription = @DefaultDescription,
ImagePath = @ImagePath, ThumbnailPath = @ThumbnailPath,
IsDeceased=CASE WHEN @UpdateLifeStatus=1 THEN @IsDeceased ELSE IsDeceased END,
UpdatedDate = SYSUTCDATETIME()
WHERE CharacterID = @CharacterID AND (@UpdateLifeStatus=0 OR ((IsDeceased=@ExpectedIsDeceased OR (IsDeceased IS NULL AND @ExpectedIsDeceased IS NULL)) AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') AND p.IsArchived=0)));
IF @@ROWCOUNT=0 AND @UpdateLifeStatus=1 THROW 51011,'Life status changed; reload current values',1;
END
IF NULLIF(@CharacterName, N'') IS NOT NULL
AND NOT EXISTS
(
SELECT 1
FROM dbo.CharacterAliases
WHERE CharacterID = @CharacterID
AND UPPER(LTRIM(RTRIM(Alias))) = UPPER(@CharacterName)
)
BEGIN
INSERT dbo.CharacterAliases (CharacterID, Alias, SortOrder)
SELECT @CharacterID,
@CharacterName,
ISNULL(MAX(SortOrder), 0) + 10
FROM dbo.CharacterAliases
WHERE CharacterID = @CharacterID;
END
SELECT @CharacterID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Character_GetReferenceForUser @CharacterID int,@UserID int
AS
BEGIN
SET NOCOUNT ON;
SELECT c.* FROM dbo.Characters c
JOIN dbo.Projects p ON p.ProjectID=c.ProjectID AND p.IsArchived=0
WHERE c.CharacterID=@CharacterID AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1);
END;
GO
CREATE OR ALTER PROCEDURE dbo.Character_LifeStatus_Save @CharacterID int,@UserID int,@IsDeceased bit=NULL,@ExpectedIsDeceased bit=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Life status editing unavailable',1;
UPDATE c SET IsDeceased=@IsDeceased,UpdatedDate=SYSUTCDATETIME() FROM dbo.Characters c
WHERE c.CharacterID=@CharacterID AND (c.IsDeceased=@ExpectedIsDeceased OR (c.IsDeceased IS NULL AND @ExpectedIsDeceased IS NULL))
AND EXISTS(SELECT 1 FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.ProjectID=c.ProjectID AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator'));
IF @@ROWCOUNT<>1 THROW 51011,'Life status changed; reload current values',1;
END;
GO
-- Preserve deployed procedure additions while extending their explicit character projections.
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_Get'));
IF @definition IS NULL THROW 51000,'Missing Character_Get',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_Get projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
SET @definition=REPLACE(REPLACE(@definition,N'CREATE OR ALTER PROCEDURE',N'ALTER PROCEDURE'),N'CREATE PROCEDURE',N'ALTER PROCEDURE');
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_ListByProject'));
IF @definition IS NULL THROW 51000,'Missing Character_ListByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_ListByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
SET @definition=REPLACE(REPLACE(@definition,N'CREATE OR ALTER PROCEDURE',N'ALTER PROCEDURE'),N'CREATE PROCEDURE',N'ALTER PROCEDURE');
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.CharacterTimeline_GetByProject'));
IF @definition IS NULL THROW 51000,'Missing CharacterTimeline_GetByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'BirthDate date NULL,',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'BirthDate date NULL,',N'BirthDate date NULL,
IsDeceased bit NULL,');
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
SET @definition=REPLACE(REPLACE(@definition,N'CREATE OR ALTER PROCEDURE',N'ALTER PROCEDURE'),N'CREATE PROCEDURE',N'ALTER PROCEDURE');
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_Export'));
IF @definition IS NULL THROW 51000,'Missing ProjectBackup_Export',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'ShortName, Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected ProjectBackup_Export projection',1;
SET @definition=REPLACE(@definition,N'ShortName, Sex, BirthDate, AgeAtSeriesStart',N'ShortName, Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
SET @definition=REPLACE(REPLACE(@definition,N'CREATE OR ALTER PROCEDURE',N'ALTER PROCEDURE'),N'CREATE PROCEDURE',N'ALTER PROCEDURE');
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ContextRelationshipLens_Read'));
IF @definition IS NULL THROW 51000,'Missing ContextRelationshipLens_Read',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'c.BirthDate,c.IsArchived',@definition)=0 THROW 51000,'Unexpected ContextRelationshipLens_Read projection',1;
SET @definition=REPLACE(@definition,N'c.BirthDate,c.IsArchived',N'c.BirthDate,c.IsDeceased,c.IsArchived');
SET @definition=REPLACE(REPLACE(@definition,N'CREATE OR ALTER PROCEDURE',N'ALTER PROCEDURE'),N'CREATE PROCEDURE',N'ALTER PROCEDURE');
EXEC sys.sp_executesql @definition;
END;
GO

View File

@ -0,0 +1,84 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Complete 301 projections using the existing deployed procedure header formatting.
while extending their explicit character projections.
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_Get'));
IF @definition IS NULL THROW 51000,'Missing Character_Get',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_Get projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_ListByProject'));
IF @definition IS NULL THROW 51000,'Missing Character_ListByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_ListByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.CharacterTimeline_GetByProject'));
IF @definition IS NULL THROW 51000,'Missing CharacterTimeline_GetByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'BirthDate date NULL,',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'BirthDate date NULL,',N'BirthDate date NULL,
IsDeceased bit NULL,');
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_Export'));
IF @definition IS NULL THROW 51000,'Missing ProjectBackup_Export',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'ShortName, Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected ProjectBackup_Export projection',1;
SET @definition=REPLACE(@definition,N'ShortName, Sex, BirthDate, AgeAtSeriesStart',N'ShortName, Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ContextRelationshipLens_Read'));
IF @definition IS NULL THROW 51000,'Missing ContextRelationshipLens_Read',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'c.BirthDate,c.IsArchived',@definition)=0 THROW 51000,'Unexpected ContextRelationshipLens_Read projection',1;
SET @definition=REPLACE(@definition,N'c.BirthDate,c.IsArchived',N'c.BirthDate,c.IsDeceased,c.IsArchived');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO

View File

@ -0,0 +1,83 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Complete 301 projections; 302 stopped before any projection change due to a malformed comment.
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_Get'));
IF @definition IS NULL THROW 51000,'Missing Character_Get',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_Get projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_ListByProject'));
IF @definition IS NULL THROW 51000,'Missing Character_ListByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_ListByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.CharacterTimeline_GetByProject'));
IF @definition IS NULL THROW 51000,'Missing CharacterTimeline_GetByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'BirthDate date NULL,',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'BirthDate date NULL,',N'BirthDate date NULL,
IsDeceased bit NULL,');
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_Export'));
IF @definition IS NULL THROW 51000,'Missing ProjectBackup_Export',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'ShortName, Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected ProjectBackup_Export projection',1;
SET @definition=REPLACE(@definition,N'ShortName, Sex, BirthDate, AgeAtSeriesStart',N'ShortName, Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ContextRelationshipLens_Read'));
IF @definition IS NULL THROW 51000,'Missing ContextRelationshipLens_Read',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'c.BirthDate,c.IsArchived',@definition)=0 THROW 51000,'Unexpected ContextRelationshipLens_Read projection',1;
SET @definition=REPLACE(@definition,N'c.BirthDate,c.IsArchived',N'c.BirthDate,c.IsDeceased,c.IsArchived');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO

View File

@ -0,0 +1,176 @@
-- Standalone forward definition for new environments and idempotent qualification.
-- Supersedes the partial 301 and failed 302 attempts; do not replay those scripts.
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Explicitly authorised canonical author-reference field. Existing rows stay unknown (NULL).
IF COL_LENGTH(N'dbo.Characters',N'IsDeceased') IS NULL ALTER TABLE dbo.Characters ADD IsDeceased bit NULL;
GO
CREATE OR ALTER PROCEDURE dbo.Character_Save
@CharacterID int = NULL,
@ProjectID int,
@CharacterName nvarchar(200),
@ShortName nvarchar(100) = NULL,
@SexValueID int = NULL,
@Sex nvarchar(100) = NULL,
@BirthDate date = NULL,
@AgeAtSeriesStart int = NULL,
@AgeReferenceSceneID int = NULL,
@Height nvarchar(50) = NULL,
@EyeColour nvarchar(50) = NULL,
@CharacterImportance int = NULL,
@ShowInQuickAddBar bit = 0,
@DefaultDescription nvarchar(max) = NULL,
@ImagePath nvarchar(500) = NULL,
@ThumbnailPath nvarchar(500) = NULL,
@IsDeceased bit=NULL,
@UpdateLifeStatus bit=0,
@ExpectedIsDeceased bit=NULL,
@UserID int=NULL
AS
BEGIN
SET NOCOUNT ON;
IF @UpdateLifeStatus=1 AND NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') AND p.IsArchived=0 AND (ISNULL(@CharacterID,0)=0 OR EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=@CharacterID AND c.ProjectID=@ProjectID))) THROW 51010,'Life status editing unavailable',1;
SET @CharacterName = LTRIM(RTRIM(@CharacterName));
IF @CharacterID IS NULL OR @CharacterID = 0
BEGIN
INSERT dbo.Characters (ProjectID, CharacterName, ShortName, SexValueID, Sex, BirthDate, AgeAtSeriesStart, AgeReferenceSceneID, Height, EyeColour, CharacterImportance, ShowInQuickAddBar, DefaultDescription, ImagePath, ThumbnailPath, IsDeceased)
VALUES (@ProjectID, @CharacterName, @ShortName, @SexValueID, @Sex, @BirthDate, @AgeAtSeriesStart, @AgeReferenceSceneID, @Height, @EyeColour, @CharacterImportance, @ShowInQuickAddBar, @DefaultDescription, @ImagePath, @ThumbnailPath, CASE WHEN @UpdateLifeStatus=1 THEN @IsDeceased ELSE NULL END);
SET @CharacterID = CAST(SCOPE_IDENTITY() AS int);
END
ELSE
BEGIN
UPDATE dbo.Characters
SET CharacterName = @CharacterName, ShortName = @ShortName, SexValueID = @SexValueID, Sex = @Sex, BirthDate = @BirthDate,
AgeAtSeriesStart = @AgeAtSeriesStart, AgeReferenceSceneID = @AgeReferenceSceneID,
Height = @Height, EyeColour = @EyeColour, CharacterImportance = @CharacterImportance,
ShowInQuickAddBar = @ShowInQuickAddBar, DefaultDescription = @DefaultDescription,
ImagePath = @ImagePath, ThumbnailPath = @ThumbnailPath,
IsDeceased=CASE WHEN @UpdateLifeStatus=1 THEN @IsDeceased ELSE IsDeceased END,
UpdatedDate = SYSUTCDATETIME()
WHERE CharacterID = @CharacterID AND (@UpdateLifeStatus=0 OR ((IsDeceased=@ExpectedIsDeceased OR (IsDeceased IS NULL AND @ExpectedIsDeceased IS NULL)) AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') AND p.IsArchived=0)));
IF @@ROWCOUNT=0 AND @UpdateLifeStatus=1 THROW 51011,'Life status changed; reload current values',1;
END
IF NULLIF(@CharacterName, N'') IS NOT NULL
AND NOT EXISTS
(
SELECT 1
FROM dbo.CharacterAliases
WHERE CharacterID = @CharacterID
AND UPPER(LTRIM(RTRIM(Alias))) = UPPER(@CharacterName)
)
BEGIN
INSERT dbo.CharacterAliases (CharacterID, Alias, SortOrder)
SELECT @CharacterID,
@CharacterName,
ISNULL(MAX(SortOrder), 0) + 10
FROM dbo.CharacterAliases
WHERE CharacterID = @CharacterID;
END
SELECT @CharacterID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Character_GetReferenceForUser @CharacterID int,@UserID int
AS
BEGIN
SET NOCOUNT ON;
SELECT c.* FROM dbo.Characters c
JOIN dbo.Projects p ON p.ProjectID=c.ProjectID AND p.IsArchived=0
WHERE c.CharacterID=@CharacterID AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1);
END;
GO
CREATE OR ALTER PROCEDURE dbo.Character_LifeStatus_Save @CharacterID int,@UserID int,@IsDeceased bit=NULL,@ExpectedIsDeceased bit=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Life status editing unavailable',1;
UPDATE c SET IsDeceased=@IsDeceased,UpdatedDate=SYSUTCDATETIME() FROM dbo.Characters c
WHERE c.CharacterID=@CharacterID AND (c.IsDeceased=@ExpectedIsDeceased OR (c.IsDeceased IS NULL AND @ExpectedIsDeceased IS NULL))
AND EXISTS(SELECT 1 FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.ProjectID=c.ProjectID AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator'));
IF @@ROWCOUNT<>1 THROW 51011,'Life status changed; reload current values',1;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_Get'));
IF @definition IS NULL THROW 51000,'Missing Character_Get',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_Get projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Character_ListByProject'));
IF @definition IS NULL THROW 51000,'Missing Character_ListByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected Character_ListByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.CharacterTimeline_GetByProject'));
IF @definition IS NULL THROW 51000,'Missing CharacterTimeline_GetByProject',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'BirthDate date NULL,',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'BirthDate date NULL,',N'BirthDate date NULL,
IsDeceased bit NULL,');
IF CHARINDEX(N'Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected CharacterTimeline_GetByProject projection',1;
SET @definition=REPLACE(@definition,N'Sex, BirthDate, AgeAtSeriesStart',N'Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_Export'));
IF @definition IS NULL THROW 51000,'Missing ProjectBackup_Export',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'ShortName, Sex, BirthDate, AgeAtSeriesStart',@definition)=0 THROW 51000,'Unexpected ProjectBackup_Export projection',1;
SET @definition=REPLACE(@definition,N'ShortName, Sex, BirthDate, AgeAtSeriesStart',N'ShortName, Sex, BirthDate, IsDeceased, AgeAtSeriesStart');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO
DECLARE @definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ContextRelationshipLens_Read'));
IF @definition IS NULL THROW 51000,'Missing ContextRelationshipLens_Read',1;
IF @definition NOT LIKE N'%IsDeceased%'
BEGIN
IF CHARINDEX(N'c.BirthDate,c.IsArchived',@definition)=0 THROW 51000,'Unexpected ContextRelationshipLens_Read projection',1;
SET @definition=REPLACE(@definition,N'c.BirthDate,c.IsArchived',N'c.BirthDate,c.IsDeceased,c.IsArchived');
DECLARE @start int=PATINDEX(N'%CREATE%',UPPER(@definition));
IF @start=0 AND PATINDEX(N'%ALTER%',UPPER(@definition))=0 THROW 51000,'Unexpected procedure header',1;
IF @start>0 BEGIN
SET @definition=STUFF(@definition,@start,6,N'ALTER');
SET @definition=REPLACE(@definition,N'ALTER OR ALTER',N'ALTER');
END;
EXEC sys.sp_executesql @definition;
END;
GO

View File

@ -478,6 +478,7 @@ public sealed class WritingContextPageViewModel
public sealed class WritingContextDisplayViewModel
{
public bool ContextRelationshipCanEdit {get;set;}
public PlotLine.Services.Context.ContextNamePanel? NamePanel{get;set;}
public PlotLine.Services.Context.ContextCharacterExplorer? CharacterExplorer {get;set;}
public StoryPointSnapshot? AtPoint => Context?.Narrative?.Snapshot;
@ -1933,6 +1934,9 @@ public sealed class CharacterEditViewModel
[Display(Name = "Birth date")]
[DataType(DataType.Date)]
public DateTime? BirthDate { get; set; }
public bool? IsDeceased {get;set;}
public bool? OriginalIsDeceased {get;set;}
public bool LifeStatusProvided {get;set;}
[Display(Name = "Age at series start")]
public int? AgeAtSeriesStart { get; set; }

View File

@ -105,6 +105,7 @@
<article class="plain-card" data-character-analysis-panel data-character-id="@Model.Character.CharacterID" data-book-id="@analysis.BookID" data-analysis-run-id="@analysis.CharacterEnrichmentRunID" data-analysis-status="@analysis.Status">
<h2>Profile</h2>
<p><strong>Preferred name:</strong> @Model.Character.CharacterName</p>
<p><strong>Life status:</strong> @(Model.Character.IsDeceased == true ? "Deceased" : Model.Character.IsDeceased == false ? "Living" : "Unrecorded") <small class="d-block muted">Global author reference; no death scene is implied.</small></p>
<p><strong>Sex:</strong> @Model.Character.Sex</p>
<p><strong>Date of birth:</strong> <span data-character-birth-date>@(Model.Character.BirthDate?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) ?? "Not recorded")</span></p>
<p><strong>Age:</strong> <span data-character-profile-age>@Model.DisplayAge</span>

View File

@ -17,6 +17,7 @@
}
<form asp-action="Save" method="post" class="edit-panel pd-record-form" enctype="multipart/form-data">
<input asp-for="OriginalIsDeceased" type="hidden"/><input asp-for="LifeStatusProvided" type="hidden"/>
<input asp-for="CharacterID" type="hidden" />
<input asp-for="ProjectID" type="hidden" />
<input asp-for="ImagePath" type="hidden" />
@ -65,8 +66,9 @@
<label asp-for="BirthDate" class="form-label"></label>
<input asp-for="BirthDate" type="date" asp-format="{0:yyyy-MM-dd}" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
<div class="form-text">Optional. Enter a date only; no birth time is needed.</div>
<div class="form-text">Optional. Enter a date only; no birth time is needed.</div>
</div>
<div class="col-md-4 pd-record-span-3"><label class="form-label" asp-for="IsDeceased">Life status · author reference</label><select asp-for="IsDeceased" class="form-select"><option value="">Unrecorded</option><option value="false">Living</option><option value="true">Deceased</option></select><p class="small text-muted">Global author reference, independent of archival. No death date, scene or viewpoint knowledge is inferred.</p></div>
<div class="col-md-4 pd-record-span-3">
<label asp-for="AgeAtSeriesStart" class="form-label"></label>
<input asp-for="AgeAtSeriesStart" class="form-control pd-record-number" />

View File

@ -56,6 +56,8 @@
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-tools.js" asp-append-version="true"></script>
<script src="~/js/context-names.js" asp-append-version="true"></script>
<script src="~/js/context-relationship-layout.js" asp-append-version="true"></script>
<script src="~/js/context-relationships.js" asp-append-version="true"></script>
<script src="~/js/context-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-environment.js" asp-append-version="true"></script>
<script src="~/js/context-windows.js" asp-append-version="true"></script>

View File

@ -8,10 +8,10 @@
else{<span>@(item.Item1=="Now"?(row.Participation=="Mentioned only"?"Mentioned only · no physical presence implied":row.Participation=="Unknown"?"Location unknown (recorded presence state)":row.Participation=="Off-screen"?"Off-screen · location not recorded":"No recorded location here"):"No recorded location")</span>}</div>
}
</div>
<dl class="writing-context-facts"><dt>Emotional state</dt><dd>@(string.IsNullOrWhiteSpace(row.Emotion)?"Not recorded in this scene":row.Emotion)</dd><dt>Physical condition</dt><dd>@(string.IsNullOrWhiteSpace(row.Condition)?"Not recorded in this scene":row.Condition)</dd><dt>Reference</dt><dd>@(string.IsNullOrWhiteSpace(row.Character.DefaultDescription)?"No character description recorded":row.Character.DefaultDescription)</dd></dl>
<dl class="writing-context-facts"><dt>Emotional state</dt><dd>@(string.IsNullOrWhiteSpace(row.Emotion)?"Not recorded in this scene":row.Emotion)</dd><dt>Physical condition</dt><dd>@(string.IsNullOrWhiteSpace(row.Condition)?"Not recorded in this scene":row.Condition)</dd><dt>Life status · author reference</dt><dd>@(row.Character.IsDeceased==true?"Deceased":row.Character.IsDeceased==false?"Living":"Unrecorded"). Global status, not evaluated at this scene.</dd><dt>Reference</dt><dd>@(string.IsNullOrWhiteSpace(row.Character.DefaultDescription)?"No character description recorded":row.Character.DefaultDescription)</dd></dl>
@if(row.Knowledge.Any()){<p class="small">@(row.IsPov?"Verified viewpoint knowledge at this point":"Author reference: this character’s established knowledge; not necessarily viewpoint knowledge")</p><ul>@foreach(var fact in row.Knowledge.Take(4)){<li>@fact.KnowledgeStateName: @fact.Description <a href="/Scenes/Edit/@fact.SceneID" data-context-workspace-target="scene" data-context-entity="@fact.SceneID" target="_blank" rel="noopener">Source</a></li>}</ul>}
@if(explorer.CanEdit){<div class="context-edit-actions">
@foreach(var field in new[]{("classification","Classification"),("description","Description")}){<button class="btn btn-outline-secondary btn-sm" type="button" data-context-edit="@field.Item1" data-character-id="@row.Character.CharacterID">Correct @field.Item2</button>}
@foreach(var field in new[]{("classification","Classification"),("description","Description"),("life-status","Life status")}){<button class="btn btn-outline-secondary btn-sm" type="button" data-context-edit="@field.Item1" data-character-id="@row.Character.CharacterID">Correct @field.Item2</button>}
@if(row.Appearance!=null){@foreach(var field in new[]{("emotion","Emotional state"),("condition","Physical condition"),("location","Current location")}){<button class="btn btn-outline-secondary btn-sm" type="button" data-context-edit="@field.Item1" data-character-id="@row.Character.CharacterID">Correct @field.Item2</button>}}
</div>}else{<p class="small">Read-only reference.</p>}
<a href="/Characters/Details/@row.Character.CharacterID" data-context-workspace-target="characters" data-context-entity="@row.Character.CharacterID" target="_blank" rel="noopener">Open character workspace</a>

View File

@ -1,7 +1,7 @@
@model PlotLine.Services.Context.ContextRelationshipForm
<form action="/Writing/Context/EditRelationship" method="post" data-context-edit-form>
@Html.AntiForgeryToken()
<input asp-for="BookID" type="hidden"/><input asp-for="SceneID" type="hidden"/><input asp-for="RelationshipID" type="hidden"/><input asp-for="Mode" type="hidden"/><input asp-for="Fingerprint" type="hidden"/>
<input asp-for="BookID" type="hidden"/><input asp-for="SceneID" type="hidden"/><input asp-for="RelationshipID" type="hidden"/><input asp-for="Mode" type="hidden"/><input asp-for="ReferenceLens" type="hidden"/><input asp-for="Fingerprint" type="hidden"/>
<p><strong>@Model.Label</strong></p><div asp-validation-summary="All" class="text-danger" role="alert"></div>
@if(Model.RelationshipID>0){<p>@Model.Characters.FirstOrDefault(c=>c.Value==Model.SourceID.ToString())?.Text @(Model.Mutual?"↔":"→") @Model.Characters.FirstOrDefault(c=>c.Value==Model.TargetID.ToString())?.Text · @Model.Types.FirstOrDefault(t=>t.Value==Model.TypeID.ToString())?.Text</p><input asp-for="SourceID" type="hidden"/><input asp-for="TargetID" type="hidden"/><input asp-for="TypeID" type="hidden"/><input asp-for="Mutual" type="hidden"/>}
else{
@ -13,6 +13,6 @@ else{
<label>Intensity (optional, 1–10) <input asp-for="Intensity" type="number" min="1" max="10" class="form-control"/></label>
<label><input asp-for="Known"/> @(Model.Mode=="initial"?"Reader initially knows":"Known to the other character (recorded event flag)")</label>
<label>Author notes / explicit meeting evidence <textarea asp-for="Notes" maxlength="4000" rows="4" class="form-control"></textarea></label>
<p class="small">Scene developments apply at this selected narrative point. Knowledge flags do not establish viewpoint knowledge. Notes are retained as author evidence; no first meeting is inferred.</p>
<p class="small">From → To retains the canonical direction (for example, From is Parent of To). Scene developments apply at this selected narrative point. Knowledge flags do not establish viewpoint knowledge. Notes are retained as author evidence; no first meeting is inferred.</p>
<button type="submit" class="btn btn-primary">Save correction</button><button type="button" class="btn btn-outline-secondary" data-context-edit-cancel>Cancel</button>
</form>

View File

@ -1,23 +1,13 @@
@model WritingContextDisplayViewModel
@{var position=Model.Context!.Position;var participants=Model.Context.Scene!.SceneCharacters.Select(c=>c.CharacterID).ToHashSet();if(Model.Context.Scene.POVCharacterID is int pov)participants.Add(pov);
var rows=(Model.AtPoint?.Relationships??Model.RelationshipMap?.Relationships??[]).OrderByDescending(r=>participants.Contains(r.CharacterAID)&&participants.Contains(r.CharacterBID)).ThenBy(r=>r.CharacterAName).ToList();var canEdit=Model.CharacterExplorer?.CanEdit==true;}
<div data-context-relationships>
<div class="context-explorer-controls"><label>Find a connection <input type="search" data-relationship-filter class="form-control form-control-sm"/></label><label>Show <select data-relationship-scope class="form-select form-select-sm"><option value="scene">Involving scene participants</option><option value="all">All established at this point</option></select></label></div>
<p class="small">Verified author reference at this scene. Reader and other-character flags are recorded separately by the underlying system; neither proves what the viewpoint character knows. Unverified claims are excluded from this state.</p>
@foreach(var family in new[]{true,false}){
<section class="context-relationship-group"><h3 class="h6">@(family?"Family connections":"Narrative connections")</h3>
@foreach(var r in rows.Where(r=>string.Equals(r.RelationshipCategoryName,"Family",StringComparison.OrdinalIgnoreCase)==family)){
<details class="context-character-row" data-context-relationship="@r.CharacterRelationshipID" data-relevant="@((participants.Contains(r.CharacterAID)||participants.Contains(r.CharacterBID)).ToString().ToLowerInvariant())" data-filter-name="@(r.CharacterAName+" "+r.CharacterBName+" "+r.RelationshipTypeName)" tabindex="-1">
<summary><strong>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName</strong><span>@r.RelationshipTypeName · @r.CurrentStateName</span></summary>
<div class="context-character-detail"><p>@r.RelationshipCategoryName · @(r.IsReciprocal?"Reciprocal connection":"Directional connection: From → To") @if(r.CurrentIntensity.HasValue){<span>· Intensity @r.CurrentIntensity / 10</span>}</p>
@if(!string.IsNullOrWhiteSpace(r.Notes)){<p>Recorded notes: @r.Notes</p>}else{<p>No author notes recorded for this state.</p>}
<p class="small">First meeting: no structured marker is available. Explicit meeting evidence, if recorded, remains in the notes and developments below; earliest co-occurrence is never treated as a meeting.</p>
<details><summary>Latest recorded developments (@r.History.Count)</summary><ul>@foreach(var item in r.History.OrderBy(h=>h.SceneID.HasValue?(Model.Context.Narrative?.Scenes.ToList().FindIndex(s=>s.SceneID==h.SceneID)??-1):-1).Reverse().Take(3)){<li>@item.Label · @item.StateName @item.Notes @if(item.SceneID.HasValue){<a href="/Scenes/Edit/@item.SceneID" data-context-workspace-target="scene" data-context-entity="@item.SceneID" target="_blank" rel="noopener">Source scene</a>}</li>}</ul></details>
@if(canEdit){<div class="context-edit-actions"><button type="button" class="btn btn-outline-secondary btn-sm" data-context-relationship-edit="scene" data-relationship-id="@r.CharacterRelationshipID">Record / correct this scene’s development</button>@if(r.InitialStateEditable){<button type="button" class="btn btn-outline-secondary btn-sm" data-context-relationship-edit="initial" data-relationship-id="@r.CharacterRelationshipID">Correct initial state</button>}</div>}
<a href="/RelationshipMap?projectId=@position.ProjectId&bookId=@position.BookId&sceneId=@position.SceneId&focusCharacterId=@r.CharacterAID" data-context-workspace-target="relationships" data-context-entity="@r.CharacterRelationshipID" target="_blank" rel="noopener">Open in Relationships Editor</a>
</div></details>}
</section>}
<p data-relationship-empty hidden>No matching established relationships. Missing records do not imply that characters have never met or are unrelated.</p>
@if(canEdit){<div class="context-edit-actions"><button type="button" class="btn btn-outline-primary btn-sm" data-context-relationship-edit="scene">Add one scene relationship</button><button type="button" class="btn btn-outline-secondary btn-sm" data-context-relationship-edit="initial">Add one initial relationship</button></div>}
<p data-context-interaction-status role="status"></p><a href="/RelationshipMap?projectId=@position.ProjectId&bookId=@position.BookId&sceneId=@position.SceneId" data-context-workspace-target="relationships" target="_blank" rel="noopener">Open in Relationships Editor</a>
@{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>
<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>
<div class="context-relationship-graph"><svg data-relationship-svg role="group" tabindex="0" aria-label="Family and Story relationship diagram. Drag to pan, use zoom buttons or pinch. Arrow keys pan; plus and minus zoom; Home centres."><g data-relationship-viewport></g></svg></div>
<div data-relationship-legend class="context-graph-legend" aria-label="Connection legend"></div><p data-relationship-status role="status"></p>
<section data-relationship-details class="context-graph-details" aria-label="Selected person or connection" tabindex="-1"></section>
@if(Model.ContextRelationshipCanEdit){<button type="button" class="btn btn-outline-primary btn-sm" data-context-relationship-edit="initial" data-relationship-reference="family" data-relationship-add>Add one family connection</button>}
<p data-context-interaction-status role="status"></p><a href="/RelationshipMap?projectId=@point.ProjectId&bookId=@point.BookId&sceneId=@scene.SceneID" data-context-workspace-target="relationships" data-relationship-editor target="_blank" rel="noopener">Open in Relationships Editor</a>
</div>

View File

@ -63,3 +63,12 @@ body:has([data-context-workspace])>.writing-window-bar { flex:none; }
.context-name-result header{display:flex;gap:.6rem;align-items:center;flex-wrap:wrap;}.context-name-result header strong{flex:1;min-width:8rem;}.context-name-result .writing-context-facts{margin-top:.6rem;}
@container(max-width:650px){.context-name-primary,.context-name-filters{grid-template-columns:repeat(2,minmax(0,1fr));}.context-name-primary>label:first-child{grid-column:1/-1;}}
@container(max-width:400px){.context-name-primary,.context-name-filters{grid-template-columns:minmax(0,1fr);}}
.context-lens-selector,.context-graph-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:.45rem;margin-block:.6rem;}.context-lens-selector [aria-pressed=true]{background:var(--pd-selected,var(--plotline-panel));color:var(--pd-accent,var(--plotline-accent));font-weight:700;box-shadow:inset 0 -3px var(--plotline-accent);}
.context-relationship-graph{height:clamp(20rem,48vh,34rem);width:100%;min-width:0;border:1px solid var(--plotline-line);border-radius:.5rem;background:var(--plotline-surface);overflow:hidden;}
[data-relationship-svg]{width:100%;height:100%;touch-action:none;cursor:grab;user-select:none;}[data-relationship-svg]:active{cursor:grabbing;}
[data-graph-node]{cursor:pointer;}[data-graph-node] rect{fill:var(--plotline-surface,#fff);stroke:var(--plotline-muted,#777);stroke-width:1.5;}[data-graph-node] rect.is-physical{stroke:#2d805c;stroke-width:2.5;}[data-graph-node].is-selected rect,[data-graph-node]:focus rect{stroke:var(--plotline-accent,#805078);stroke-width:4;}
.context-graph-name{font-size:13px;fill:var(--plotline-ink,#222);font-weight:600;}.context-graph-meta{font-size:10px;fill:var(--plotline-muted,#666);}
[data-graph-edge].is-selected>path:first-child{stroke-width:4;}[data-graph-connection]{cursor:pointer;}[data-graph-connection]:focus{outline:none;stroke:var(--plotline-accent);stroke-opacity:.25;}
.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;}}

View File

@ -5,7 +5,7 @@
function install(html){const doc=new DOMParser().parseFromString(html,'text/html');const form=doc.querySelector('[data-context-edit-form]');if(!form||doc.querySelector('html>head>title')||/<!doctype/i.test(html))throw Error('Sign in again before editing.');host.replaceChildren(form);dialog.querySelector('[data-context-edit-close]').hidden=true;form.querySelector('input:not([type=hidden]),select,textarea')?.focus();}
function close(saved=false){if(busy)return;if(dirty&&!saved&&!confirm('Discard this unsaved correction?'))return;load?.abort();dialog.close();dirty=false;state(saved);pane=null;host.replaceChildren();status.textContent='';originalFocus?.isConnected&&originalFocus.focus({preventScroll:true});}
root.addEventListener('click',async event=>{const button=event.target.closest('[data-context-edit],[data-context-relationship-edit]');if(!button||dialog.open)return;
pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const relationship=button.hasAttribute('data-context-relationship-edit');const url=new URL(relationship?'/Writing/Context/EditRelationship':'/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',fragment.dataset.sceneId||'0');if(relationship){url.searchParams.set('relationshipId',button.dataset.relationshipId||'0');url.searchParams.set('mode',button.dataset.contextRelationshipEdit);}else{url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit);}
pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const relationship=button.hasAttribute('data-context-relationship-edit');const url=new URL(relationship?'/Writing/Context/EditRelationship':'/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',button.dataset.contextEditScene||fragment.dataset.sceneId||'0');if(relationship){url.searchParams.set('relationshipId',button.dataset.relationshipId||'0');url.searchParams.set('mode',button.dataset.contextRelationshipEdit);if(button.dataset.relationshipReference)url.searchParams.set('referenceLens',button.dataset.relationshipReference);}else{url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit);}
dialog.querySelector('[data-context-edit-close]').hidden=true;dialog.showModal();dirty=false;busy=true;state();status.textContent='Loading current saved values…';host.replaceChildren();load=new AbortController();
try{const response=await fetch(url,{signal:load.signal,cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error('This correction is unavailable. Check sign-in and editing permission.');install(await response.text());status.textContent='';}
catch(error){if(error.name!=='AbortError'){status.textContent=error.message;dialog.querySelector('[data-context-edit-close]').hidden=false;window.PlotDirector?.toast?.error(error.message);}}

View File

@ -7,7 +7,7 @@
connection.on('ContextInteractionResult',r=>{if(!sending)return;receipts.set(r.commandID,r.status);waiters.get(r.commandID)?.(r.status);});
document.addEventListener('click',async event=>{
const link=event.target.closest('a[data-context-workspace-target]');if(!link||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;event.preventDefault();if(sending)return;sending=true;
const fragment=link.closest('[data-context-tab-fragment]'),bookID=Number(fragment?.dataset.bookId||controller.announcement.bookID),tool=link.dataset.contextWorkspaceTarget,entityID=Number(link.dataset.contextEntity)||null,sceneID=Number(fragment?.dataset.sceneId||controller.position.sceneId)||null;
const fragment=link.closest('[data-context-tab-fragment]'),bookID=Number(fragment?.dataset.bookId||controller.announcement.bookID),tool=link.dataset.contextWorkspaceTarget,entityID=Number(link.dataset.contextEntity)||null,sceneID=link.dataset.contextNarrative==='author'?null:Number(link.dataset.contextOpenScene||fragment?.dataset.sceneId||controller.position.sceneId)||null;
const fallback=()=>{const url=new URL('/Writing/Context/OpenWorkspace',location.origin);url.searchParams.set('bookId',bookID);url.searchParams.set('tool',tool);if(entityID)url.searchParams.set('entityId',entityID);if(sceneID)url.searchParams.set('sceneId',sceneID);const windowRef=window.open(url.href,targetName);if(windowRef){try{windowRef.focus();}catch{}}else{link.href=url.href;link.target=targetName;window.PlotDirector?.toast?.info('Your browser blocked opening the main window. Use this link again to open it.');link.removeAttribute('data-context-workspace-target');}};
try{
if(connection.state!=='Connected'){fallback();return;}

View File

@ -0,0 +1,47 @@
// Small deterministic layouts over canonical IDs. No inferred people, parentage, meetings or knowledge.
(() => {
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'};}
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.');
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;}
const immediate=new Map(nodes.map(n=>[n.id,[]]));for(const l of valid){const r=roles.get(l.id);if(r.kind==='parent'&&r.delta===1)immediate.get(r.from).push(r.to);}
for(const family of immediate.values()){for(let i=1;i<family.length;i++)merge(family[0],family[i]);}
for(const l of valid){const r=roles.get(l.id);if(r.kind==='partner'||r.kind==='sibling')merge(l.a,l.b);}
const groups=new Map();for(const n of nodes){const id=find(n.id);if(!groups.has(id))groups.set(id,{id,people:[],rank:0,indegree:0,parents:[],children:[]});groups.get(id).people.push(n);}
for(const l of valid){const r=roles.get(l.id);if(r.kind!=='parent')continue;const a=groups.get(find(r.from)),b=groups.get(find(r.to));if(a===b)continue;a.children.push({id:b.id,delta:r.delta});b.parents.push(a.id);b.indegree++;}
const todo=[...groups.values()].filter(g=>g.indegree===0).sort((a,b)=>a.id-b.id),done=new Set(),topology=[];while(todo.length){const a=todo.shift();done.add(a.id);topology.push(a);for(const e of a.children){const b=groups.get(e.id);b.rank=Math.max(b.rank,a.rank+e.delta);if(--b.indegree===0)todo.push(b);}}
if(done.size!==groups.size){warnings.push('An ancestry cycle prevents a generational interpretation for some records. Those connections remain visible without fabricated ancestors.');for(const g of groups.values())if(!done.has(g.id))g.rank=0;}
for(const g of [...topology].reverse()){if(!g.children.length)continue;const bounds=g.children.map(e=>groups.get(e.id).rank-e.delta),limit=Math.min(...bounds);if(limit>g.rank)g.rank=limit;}
const parentsOf=new Map(nodes.map(n=>[n.id,[]]));for(const l of valid){const r=roles.get(l.id);if(r.kind==='parent'&&r.delta===1)parentsOf.get(r.to).push(r.from);}
const positions={},rowWidths=new Map(),orderedGroups=[...groups.values()],rows=[...new Set(orderedGroups.map(g=>g.rank))].sort((a,b)=>a-b);
function birth(a,b){if(a.birthDate&&b.birthDate&&a.birthDate!==b.birthDate)return a.birthDate.localeCompare(b.birthDate);if(a.birthDate&&!b.birthDate)return -1;if(!a.birthDate&&b.birthDate)return 1;return (a.name||'').localeCompare(b.name||'')||a.id-b.id;}
for(const rank of rows){const row=orderedGroups.filter(g=>g.rank===rank);const score=g=>{const p=g.parents.map(id=>groups.get(id)).flatMap(p=>p.people).map(p=>positions[p.id]?.x).filter(Number.isFinite);return p.length?p.reduce((a,b)=>a+b,0)/p.length:Number.MAX_SAFE_INTEGER;};const key=g=>g.people.flatMap(n=>parentsOf.get(n.id)).sort((a,b)=>a-b).join(',');row.sort((a,b)=>score(a)-score(b)||key(a).localeCompare(key(b))||birth(a.people[0],b.people[0]));let x=0;
for(const g of row){g.people.sort(birth);const families=new Map();for(const n of g.people)for(const p of parentsOf.get(n.id)){if(!families.has(p))families.set(p,[]);families.get(p).push(n);}const siblings=[...families.entries()].filter(([_,children])=>children.length>1).sort((a,b)=>b[1].length-a[1].length||a[0]-b[0])[0]?.[1];
if(siblings){const cores=[...siblings].sort(birth),coreIDs=new Set(cores.map(n=>n.id)),used=new Set(),ordered=[];for(const core of cores){if(used.has(core.id))continue;const partners=g.people.filter(n=>!used.has(n.id)&&!coreIDs.has(n.id)&&valid.some(l=>roles.get(l.id).kind==='partner'&&((l.a===core.id&&l.b===n.id)||(l.b===core.id&&l.a===n.id))));const block=[...partners];block.splice(Math.floor(block.length/2),0,core);for(const n of block){ordered.push(n);used.add(n.id);}}g.people=[...ordered,...g.people.filter(n=>!used.has(n.id))];}
else if(g.people.length>2){const degrees=new Map(g.people.map(n=>[n.id,valid.filter(l=>roles.get(l.id).kind==='partner'&&(l.a===n.id||l.b===n.id)).length]));const central=[...g.people].sort((a,b)=>degrees.get(b.id)-degrees.get(a.id)||a.id-b.id)[0];if(degrees.get(central.id)>1){g.people=g.people.filter(n=>n!==central);g.people.splice(Math.floor(g.people.length/2),0,central);}}
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}`;}
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};
}
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};});});
const values=Object.values(positions),minX=Math.min(...values.map(p=>p.x))-100,minY=Math.min(...values.map(p=>p.y))-100;for(const p of values){p.x-=minX;p.y-=minY;}
const routes=links.filter(l=>positions[l.a]&&positions[l.b]).map((l,i)=>{const a=positions[l.a],b=positions[l.b];return {id:l.id,kind:'story',d:`M ${a.x+W/2} ${a.y+H/2} Q ${(a.x+b.x)/2+W/2+(i%3-1)*18} ${(a.y+b.y)/2+H/2-(i%2)*20}, ${b.x+W/2} ${b.y+H/2}`};});
return {positions,routes,width:Math.max(...values.map(p=>p.x+W))+100,height:Math.max(...values.map(p=>p.y+H))+100,warnings:[],nodeWidth:W,nodeHeight:H};
}
window.PlotDirectorContextRelationshipLayout={family,story,role,signature};
})();

View File

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

View File

@ -33,12 +33,3 @@
}
};
})();
(() => {
const saved=new Map(),mounted=new WeakMap();
function apply(node){const q=node.querySelector('[data-relationship-filter]').value.toLocaleLowerCase(),all=node.querySelector('[data-relationship-scope]').value==='all';let count=0;node.querySelectorAll('[data-context-relationship]').forEach(row=>{row.hidden=(!all&&row.dataset.relevant!=='true')||!row.dataset.filterName.toLocaleLowerCase().includes(q);if(!row.hidden)count++;});node.querySelector('[data-relationship-empty]').hidden=count>0;}
window.PlotDirectorContextLifecycles.relationships={
mount(node,{paneId}){const host=node.querySelector('[data-context-relationships]');if(!host)return;const abort=new AbortController();mounted.set(node,{paneId,abort});const prior=saved.get(paneId);if(prior){node.querySelector('[data-relationship-filter]').value=prior.filter;node.querySelector('[data-relationship-scope]').value=prior.scope;node.querySelectorAll('[data-context-relationship]').forEach(row=>row.open=prior.open.includes(row.dataset.contextRelationship));}node.addEventListener('input',()=>apply(node),{signal:abort.signal});node.addEventListener('change',()=>apply(node),{signal:abort.signal});apply(node);},
dispose(node){const state=mounted.get(node);if(state){saved.set(state.paneId,{filter:node.querySelector('[data-relationship-filter]').value,scope:node.querySelector('[data-relationship-scope]').value,open:[...node.querySelectorAll('[data-context-relationship][open]')].map(r=>r.dataset.contextRelationship)});state.abort.abort();mounted.delete(node);}},
onInteraction(node,command){if(command.action!=='relationship.focus')return 'not-visible';if(command.storyPoint?.sceneID&&command.storyPoint.sceneID!==Number(node.dataset.sceneId))return 'not-visible';const row=node.querySelector(`[data-context-relationship="${Number(command.relationshipID)}"]`);if(!row)return 'not-visible';node.querySelector('[data-relationship-filter]').value='';node.querySelector('[data-relationship-scope]').value='all';apply(node);row.open=true;row.classList.add('context-reference-focus');row.scrollIntoView({block:'nearest'});row.focus({preventScroll:true});return 'focused';}
};
})();

View File

@ -19,8 +19,8 @@
if(connection.state!=='Connected'){message.textContent='Context connection is reconnecting. Try again shortly.';return;}
try{render(await connection.invoke('MyContextWindows',controller.announcement.bookID));}catch{message.textContent='Window discovery unavailable for this book.';}}
function fallback(node,command,status){node.textContent=status==='no-handler'?'No visible tool supports this reference. Choose the tool in a pane or open the full workspace.':status==='not-visible'?'The destination cannot show this reference at its current point. Open the full workspace if needed.':status==='busy'?'The destination is editing or busy. Try again after it finishes.':'Reference unavailable. Retry after reconnecting.';
const path=command.characterID?'/Characters/Details/'+Number(command.characterID):command.locationID?'/Locations/Details/'+Number(command.locationID):null;
if(path){const link=document.createElement('a');link.href=path;link.target='_blank';link.rel='noopener';link.textContent=' Open full workspace';node.append(link);}}
const path=command.characterID?'/Characters/Details/'+Number(command.characterID):command.locationID?'/Locations/Details/'+Number(command.locationID):command.relationshipID?'/RelationshipMap?bookId='+controller.announcement.bookID:null;
if(path){const link=document.createElement('a');link.href=path;link.target='_blank';link.rel='noopener';link.textContent=' Open full workspace';if(command.characterID){link.dataset.contextWorkspaceTarget='characters';link.dataset.contextEntity=command.characterID;}else if(command.relationshipID){link.dataset.contextWorkspaceTarget='relationships';link.dataset.contextEntity=command.relationshipID;if(command.storyPoint?.sceneID)link.dataset.contextOpenScene=command.storyPoint.sceneID;}node.append(link);}}
async function send(command,node){if(!connection||connection.state!=='Connected'){fallback(node,command,'unavailable');return;}
const pane=root.querySelector('[data-context-pane]:not([hidden])');command={...command,version:1,bookID:controller.announcement.bookID,originPaneID:command.originPaneID||pane?.dataset.contextPane||'0'};
if(target.value&&dialog.open){const option=target.selectedOptions[0];command.targetWindowID=option.dataset.window;const at=target.value.lastIndexOf('/');command.targetSessionID=target.value.slice(0,at);command.targetPaneID=target.value.slice(at+1);}