Refine Character ribbon, grouped relationships and canonical evolution history

This commit is contained in:
Nick Beckley 2026-11-23 11:21:45 +00:00
parent 5bc339bf9b
commit 7fa095409c
34 changed files with 400 additions and 111 deletions

View File

@ -0,0 +1,57 @@
# Character workspace refinement — 23 November 2026
## Scope and preservation
This is a focused change to the main Character Details workspace and existing dedicated Relationship Evolution route. The five tabs, profile/gallery/aliases, character-level Evolution, appearances/knowledge, canonical Family/Story engines, Context, existing main editor and Timeline remain available. No manuscript-specific production rules or automatic deduplication were introduced.
## Phase 1 — ribbon
The existing Characters navigation remains in the ribbon. The redundant Characters/Timeline/Edit/Actions header controls are removed; the header retains portrait, identity, classification and analysis status. Edit Character and Actions now live in a selected-character ribbon group. Merge, Reanalyse, normal HTML character export, Markdown-format character export and Archive use their original controllers and forms. Markdown remains `Exports.Character(format=markdown)`; it was not reinterpreted. Owner/Collaborator editing checks, anti-forgery and the established Archive confirmation are retained; Viewer has export actions only. Each full character navigation renders the canonical ID into the shared ribbon partial. The dropdown uses Bootstrap with a fixed body portal so the horizontally scrolling ribbon does not clip its menu.
## Phase 2 — grouped relationships
SQL filters before grouping and orders by the other participant display name using case-insensitive `Latin1_General_100_CI_AS`, then canonical character ID. This is independent of A/B direction. Definition order within a group is controlled type name, then canonical definition ID. Queries page 25 character groups. Each group initially reads at most three definitions (75 total); a focused group pages all of its definitions in batches of 25. No client-side full dataset is loaded for sorting. Two identical display names remain separate canonical identities. Reciprocal flags remain one record; separately authored reverse records remain distinct.
Collapsed summaries show name, count, a few recorded types and meaningful states. Expanded groups show distinct definitions, direction/category, selected-point state, notes, initial/scene-established status and start/end links. Family filtering mirrors the existing `ContextFamily_Structure` / `ContextRelationshipLenses.Family` predicate, including canonical partnerships, and never infers family membership from participants or prose. Story filtering selects the other definitions. The graph lenses remain the existing engines. Search, paging and narrative cutoff are retained. Expanded group IDs and selected definition survive ordinary refreshes; empty groups disappear after removal.
## Phase 3 — actions and safe quick editing
Each definition has Edit, History and Remove. Inspect Connection previously only selected/highlighted the diagram; clicking or keyboard-selecting the record now preserves that function, and diagram selection reveals its canonical record. One contextual link replaces repeated full-editor links. History links to the exact existing Dynamics Relationship route; Advanced Evolution and the complete in-page history have been removed.
The focused native dialog reuses the established operation partial/controller, canonical controlled types and `Relationship_Save`. It edits type within the existing category, reverses direction explicitly, changes safe non-Family-category reciprocal representation, permanent status, reader awareness, initial state/intensity/reader awareness, and optional notes. Category is a property of canonical type, not an independent field. The definition ID is retained: no delete/recreate or inverse-record rewriting occurs. Pair identities, narrative boundaries, book and initial/scene-established status remain unchanged.
Structural changes with dependent events, cross-category changes and Family-category reciprocity changes are rejected atomically with an inline explanation and focused route to the full editor. Those operations can reinterpret historical/family semantics and lack canonical coordinated validation here. Notes and supported initial properties remain editable. The full editor deep link selects the requested definition if established at its current point; otherwise it explains why it is unavailable there. The full editor itself was not redesigned.
Removal retains the existing versioned, authorised canonical archive/event-delete operations, explicit scope/dependency confirmation and source-provenance guards. SQL locks and the original definition/history hash protect concurrent changes. Shared toast feedback and existing lightweight Context invalidation are reused; no new SignalR connection is created.
## Phase 4 — dedicated history
Diagnosis: the old graphic was a fixed-height decorative bright gradient, with an unlabelled positional strip. It rendered even with zero/one event, clipped edge markers, and substituted intensity 3 when no intensity was recorded. It did not explain axes or missing data. This was principally sparse-data/rendering/theme design, not missing canonical events.
The existing Dynamics Relationship route is retained. It shows exact names/type/direction/definition ID, canonical book/chapter/scene-ordered events, actual state and optional intensity, notes, evidence/review status, source links and retained continuity warnings. Event editing/removal uses the existing protected operation workflow on this page. Data is paged at 25. Empty/single-event cases get concise explicit presentations. Multiple verified recorded intensities get a compact labelled point plot, with no synthetic intermediate states or values for missing intensity. Narrow charts scroll internally instead of shrinking text or overflowing the page. Theme surfaces and text use existing application tokens. The source of ordering is the established canonical scene-order function; same-scene events sort by canonical event ID. The return link identifies the originating character, selected definition and narrative point, restoring selection/expansion in Relationships. Character-level Evolution remains separate.
## Qualification and Development delivery
Evidence, final regression results and deployed commit are appended after verification. The two pre-existing untracked investigation documents are preserved. Tests use rollback SQL fixtures or explicitly disposable Development browser characters only; no actual manuscript relationship is corrected, merged or removed.
### Database qualification
Forward-only migrations 309–313 were applied only to the verified `PlotDirector_Development` database. Each uses `CREATE OR ALTER` routines; existing applied numbered scripts remain unchanged. The backup `/var/opt/mssql/backup/character-refinement-20261123T105440Z.bak` completed with COPY_ONLY/CHECKSUM and passed `RESTORE VERIFYONLY`; no restore/reset occurred. The quick-edit procedure initially failed compilation because SQL treats parameter/local variable names case-insensitively; the unapplied procedure was corrected before successful application. No dependent application build was deployed during that failure.
The opt-in disposable-scope SQL suite passed and rolled back every case: 28 globally ordered groups, matching/case-varied names with stable identity, direction-independent grouping, 28 definitions in a single group with 25+3 focused pages, combined search/category filters and no deduplication; same-ID family type/direction changes; one-row story reciprocity; rejection of incompatible category, family reciprocity and semantic rewrites with history; canonical archive/restore retaining dependent events and independent reverse facts; one-event editing/removal; stale-history and permission/confirmation checks; source-linked blocking; dedicated canonical history pagination at 25+3 and stable same-scene event order. The final test confirms no fixture character remains from any rollback case.
Read-only real-manuscript acceptance used the actual Dapper readers: bounded explorers, SQL/.NET ordering agreement, selected-point future-knowledge exclusion, canonical management preview mapping and a sparse single-event dedicated history. The real-project relationship checksum was identical before and after; no AI work or manuscript mutation occurred.
### Regression and visual acceptance
`dotnet build PlotLine.slnx -m:1 --disable-build-servers` passes with zero warnings/errors. Single-process compilation avoids an initial CLR/build-server crash on this host. The full executable harness reports **786 PASS** and exits successfully. The 15 focused Character workspace service checks also pass after the final form/ribbon integration adjustments.
The rendered main-workspace Playwright suite passes: lazy tabs and retained profile/gallery/navigation; sorted compact groups with two directional definitions together; Family/Story filters; controlled type modal, inline stale validation, unsaved/Escape handling and full-width controls; selection/expansion after saves and exact-history return; archive refresh; correct relocated ribbon IDs after character navigation, Markdown-format link and anti-forgery forms; unclipped Actions menu at desktop/laptop/tablet/mobile widths; actual touch pan/pinch; stable Native/SI connection counts and Viewer controls. Browser fixture pagination is complemented by actual SQL all-page ordering tests. The dedicated history suite passes empty/single/five-event cases, actual intensity omission rather than fabricated values, canonical order/source navigation, exact return identity, event modal protection and Viewer restrictions. The existing Relationships Editor browser suite passes after the minimal deep-link integration.
Widths 1366, 1024, 768 and 390 pass without page-wide horizontal overflow. The compact chart has a bounded internal scroller on narrow screens. Screenshots `/tmp/character-refinement-grouped-dark.png` and `/tmp/relationship-evolution-dark-desktop.png` were visually inspected in the actual warm-dark theme. The final scoped outline-button adjustment improves contrast without changing the shared application theme.
No additional per-tab/component SignalR connections or complete-dataset broadcasts were added. Physical device/touch and assistive-technology screen-reader acceptance remain manual recommendations; browser tests cover touch emulation, keyboard, modal focus and responsive geometry.
The final dedicated-history browser check also performs a successful event-form save, verifies that the shared success toast remains visible and that only the bounded content is fetched (no document reload), then checks protected-source removal. Main workspace saves restore focus to the selected definition and retain its group. The exact full-editor deep link is tested after saved story-position restoration, in addition to the original editor regression scenarios.
The database suite reports **26 passing checks in 16 fully rolled-back cases**. Build, focused service checks, main-workspace browser, dedicated-history browser and main Relationships Editor browser all pass for the delivered refinements. Deployment evidence follows.

View File

@ -5,8 +5,9 @@ step='new isolated character and Supporting default';await p.goto('https://dev.p
step='five live bounded tabs and empty states';for(const tab of ['relationships','evolution','appearances','knowledge','overview']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}await p.click('[data-character-tab="relationships"]');await p.locator('[data-character-node="'+id+'"]').waitFor({state:'attached'});
step='existing Context peer notifications';const peer=await c.newPage();await peer.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await peer.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController.connection?.state==='Connected');await peer.evaluate(project=>{window.workspaceHints=0;document.querySelector('[data-context-workspace]').contextController.connection.on('ContextInvalidated',hint=>{if(Number(hint.projectId)===project)workspaceHints++});},s.project);
step='initial parent via canonical save';await p.locator('[data-workspace-add]').click();// Resolve the known fixture name from its authenticated shell, without printing it.
const targetShell=await c.request.get('https://dev.plotdirector.com/Characters/Details/'+s.characters[0]);const html=await targetShell.text();const name=await p.evaluate(text=>new DOMParser().parseFromString(text,'text/html').querySelector('h1')?.childNodes[0]?.textContent.trim(),html);assert(name);await p.locator('[data-workspace-target-search]').fill(name.slice(0,50));await p.locator('[data-workspace-target] option[value="'+s.characters[0]+'"]').waitFor({state:'attached'});await p.locator('[data-workspace-target]').selectOption(String(s.characters[0]));const type=await p.locator('[name=RelationshipTypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Parent$/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=RelationshipTypeID]',type);await p.locator('[name=Notes]').fill('Disposable workspace qualification definition');await p.locator('[data-workspace-operation-form] button[type=submit], [data-workspace-operation-form] button:not([type])').first().click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);let row=p.locator('[data-workspace-relationship]').filter({hasText:'Disposable workspace qualification definition'});await row.waitFor();const rid=Number(await row.getAttribute('data-workspace-relationship'));row=p.locator('[data-workspace-relationship="'+rid+'"]');await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'attached'});
step='live edit, dirty main navigation guard and archive preview';await row.locator('[data-workspace-operation="definition"]').click();await p.locator('[name=Notes]').fill('Disposable definition edited');p.once('dialog',d=>d.dismiss());assert.equal(await p.evaluate(()=>window.PlotDirectorCharacterWorkspace.requestLeave(()=>{window.unexpectedLeave=true})),false);assert.equal(await p.evaluate(()=>!!window.unexpectedLeave),false);await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await row.locator('[data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/0 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/underlying relationship definition/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(r=>!document.querySelector('[data-workspace-relationship="'+r+'"]'),rid);await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'detached'});assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);await p.click('[data-character-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-character-graph-status]').textContent!=='Loading recorded relationships…');
const targetShell=await c.request.get('https://dev.plotdirector.com/Characters/Details/'+s.characters[0]);const html=await targetShell.text();const name=await p.evaluate(text=>new DOMParser().parseFromString(text,'text/html').querySelector('h1')?.childNodes[0]?.textContent.trim(),html);assert(name);await p.locator('[data-workspace-target-search]').fill(name.slice(0,50));await p.locator('[data-workspace-target] option[value="'+s.characters[0]+'"]').waitFor({state:'attached'});await p.locator('[data-workspace-target]').selectOption(String(s.characters[0]));const type=await p.locator('[name=RelationshipTypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Parent$/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=RelationshipTypeID]',type);await p.locator('[name=Notes]').fill('Disposable workspace qualification definition');await p.locator('[data-workspace-operation-form] button[type=submit], [data-workspace-operation-form] button:not([type])').first().click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.locator('[data-relationship-group] > summary').first().click();let row=p.locator('[data-workspace-relationship]').filter({hasText:'Disposable workspace qualification definition'});await row.waitFor();const rid=Number(await row.getAttribute('data-workspace-relationship'));row=p.locator('[data-workspace-relationship="'+rid+'"]');await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'attached'});
step='dedicated empty history and exact return';await row.getByRole('link',{name:'History',exact:true}).click();await p.waitForURL(u=>u.pathname==='/Dynamics/Relationship/'+rid);assert.match(await p.locator('main').innerText(),/No recorded events/);assert.equal(await p.locator('.relationship-evolution-chart').count(),0);await p.getByRole('link',{name:'Return to character Relationships'}).click();await p.locator('[data-workspace-relationship="'+rid+'"].is-selected').waitFor();assert.equal(await row.evaluate(n=>n.closest('[data-relationship-group]').open),true);
step='live edit, dirty main navigation guard and archive preview';await row.locator('[data-workspace-operation="definition"]').click();const childType=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Child$/.test(n.textContent))?.value);assert(childType);await p.locator('[name=TypeID]').selectOption(childType);await p.locator('[name=ReverseDirection]').check();await p.locator('[name=Notes]').fill('Disposable definition edited');p.once('dialog',d=>d.dismiss());assert.equal(await p.evaluate(()=>window.PlotDirectorCharacterWorkspace.requestLeave(()=>{window.unexpectedLeave=true})),false);assert.equal(await p.evaluate(()=>!!window.unexpectedLeave),false);await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await row.locator('[data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/0 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/underlying relationship definition/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(r=>!document.querySelector('[data-workspace-relationship="'+r+'"]'),rid);await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'detached'});assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);await p.click('[data-character-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-character-graph-status]').textContent!=='Loading recorded relationships…');
await peer.waitForFunction(()=>workspaceHints===3);await peer.waitForTimeout(400);assert.equal(await peer.evaluate(()=>workspaceHints),3);assert.equal(await peer.locator('[data-context-scene]').inputValue(),String(s.scene));
step='archive only this newly created fixture character';await p.locator('.character-workspace-header .dropdown-toggle').click();await p.locator('.character-workspace-header form[action*="Archive"] button').click();await p.locator('#plotlineConfirmModal [data-confirm-submit]').click();await p.waitForURL(u=>!u.pathname.endsWith('/Details/'+id));assert.deepEqual(errors,[]);console.log('PASS Development live Character workspace: new isolated Supporting fixture; all five tabs; canonical initial Parent add/edit; dirty navigation rejection; explicit dependency preview; direct soft archive and Family/Story refresh; exactly one existing Context peer hint per add/edit/archive; newly created fixture character archived. Existing manuscript and baseline fixture relationships untouched.');
step='archive only this newly created fixture character';await p.locator('[data-character-ribbon] .dropdown-toggle').click();await p.locator('[data-character-actions-for] form[action*="Archive"] button').click();await p.locator('#plotlineConfirmModal [data-confirm-submit]').click();await p.waitForURL(u=>!u.pathname.endsWith('/Details/'+id));assert.deepEqual(errors,[]);console.log('PASS Development live Character workspace: new isolated Supporting fixture; all five tabs and exact dedicated History/return; canonical initial Parent add and same-ID Child/direction edit; dirty navigation rejection; explicit dependency preview; direct soft archive and Family/Story refresh; exactly one existing Context peer hint per add/edit/archive; newly created fixture character archived. Existing manuscript and baseline fixture relationships untouched.');
}catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})();

View File

@ -1,15 +1,16 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let removed=false,notes=null,fail=false,viewer=false,tabReads=[],familyReads=0;for(const [endpoint,fixture]of [['Tab','tab'],['Family','family'],['Operation','operation']])await c.route('**/Characters/Workspace/'+endpoint+'/*',async r=>{const u=new URL(r.request().url());if(endpoint==='Operation'&&r.request().method()==='POST'){if(fail){fail=false;await r.fulfill({response:await r.fetch({method:'GET',url:base+'/character-workspace-operation-fixture?operation=definition&relationshipId=9&invalid=true&notes='+encodeURIComponent('Draft retained')})});return;}if(r.request().postData()?.includes('archive'))removed=true;else notes='Saved fixture definition';await r.fulfill({json:{saved:true,message:removed?'Relationship archived; history retained.':'Relationship saved.'}});return;}if(endpoint==='Tab')tabReads.push(u.searchParams.get('Tab'));if(endpoint==='Family')familyReads++;u.searchParams.set('viewer',String(viewer));u.searchParams.set('removed',String(removed));if(notes)u.searchParams.set('notes',notes);await r.fulfill({response:await r.fetch({url:base+'/character-workspace-'+fixture+'-fixture'+u.search})});});await c.route('**/Characters/Workspace/Lookup/*',r=>r.fulfill({json:[{id:6,name:'Another established character'}]}));await c.route('**/Characters/Workspace/Story/*',r=>r.fulfill({json:{lens:'story',focusID:5,povID:null,sceneID:22,canEdit:!viewer,truncated:false,nodes:[{id:5,name:'Current character'},{id:7,name:'Recorded colleague'}],links:[{id:12,a:5,b:7,type:'Friend',category:'Friendship',state:'Earlier recorded state',reciprocal:false,initial:true,recent:[]}]}}));await c.route('**/Characters/Details/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('id',u.pathname.split('/').at(-1));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-fixture'+u.search})});});const p=await c.newPage(),errors=[];await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async locator=>locator.click());let native=0,si=0;p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))native++;if(r.url().includes('/hubs/story-intelligence/negotiate'))si++;});await p.goto(base+'/character-workspace-fixture');await p.waitForSelector('[data-character-tab-content="overview"]');
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let removed=false,notes=null,fail=false,viewer=false,tabReads=[],familyReads=0;for(const [endpoint,fixture]of [['Tab','tab'],['Family','family'],['Operation','operation']])await c.route('**/Characters/Workspace/'+endpoint+'/*',async r=>{const u=new URL(r.request().url());if(endpoint==='Operation'&&r.request().method()==='POST'){if(fail){fail=false;await r.fulfill({response:await r.fetch({method:'GET',url:base+'/character-workspace-operation-fixture?operation=definition&relationshipId=9&invalid=true&notes='+encodeURIComponent('Draft retained')})});return;}if(r.request().postData()?.includes('archive'))removed=true;else notes='Saved fixture definition';await r.fulfill({json:{saved:true,message:removed?'Relationship archived; history retained.':'Relationship saved.'}});return;}if(endpoint==='Tab'){tabReads.push(u.searchParams.get('Tab'));u.searchParams.set('id',u.pathname.split('/').at(-1));}if(endpoint==='Family')familyReads++;u.searchParams.set('viewer',String(viewer));u.searchParams.set('removed',String(removed));if(notes)u.searchParams.set('notes',notes);await r.fulfill({response:await r.fetch({url:base+'/character-workspace-'+fixture+'-fixture'+u.search})});});await c.route('**/Characters/Workspace/Lookup/*',r=>r.fulfill({json:[{id:6,name:'Another established character'}]}));await c.route('**/Characters/Workspace/Story/*',r=>r.fulfill({json:{lens:'story',focusID:5,povID:null,sceneID:22,canEdit:!viewer,truncated:false,nodes:[{id:5,name:'Current character'},{id:7,name:'Recorded colleague'}],links:[{id:12,a:5,b:7,type:'Friend',category:'Friendship',state:'Earlier recorded state',reciprocal:false,initial:true,recent:[]}]}}));await c.route('**/Characters/Details/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('id',u.pathname.split('/').at(-1));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-fixture'+u.search})});});const p=await c.newPage(),errors=[];await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async locator=>locator.click());let native=0,si=0;p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))native++;if(r.url().includes('/hubs/story-intelligence/negotiate'))si++;});await p.goto(base+'/character-workspace-fixture');await p.waitForSelector('[data-character-tab-content="overview"]');
step='compact shell and lazy Overview';assert.deepEqual(tabReads,['overview']);assert.equal(await p.locator('[data-character-tab-content]').count(),1);assert.equal(await p.locator('[data-character-tab]').count(),5);assert.match(await p.locator('.character-workspace-header').innerText(),/Supporting/);assert.match(await p.locator('.character-dossier').innerText(),/Recorded variant/);assert(await p.locator('.character-workspace-header').evaluate(n=>n.getBoundingClientRect().height<260));assert.equal(await p.locator('[data-workspace-relationship]').count(),0);await p.screenshot({path:'/tmp/character-workspace-overview-desktop.png',fullPage:true});
step='relationships layout, branch and record selection';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node="5"]');assert.equal(await p.locator('[data-workspace-relationship]').count(),3);await p.locator('[data-character-branch="3"]').click();await p.locator('[data-character-node="1"]').waitFor();await p.screenshot({path:'/tmp/character-workspace-family-desktop.png',fullPage:true});await p.click('[data-workspace-select-relationship="9"]');assert(await p.locator('[data-workspace-relationship="9"]').evaluate(n=>n.classList.contains('is-selected')));await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.waitForSelector('[data-workspace-operation-form]');assert(await p.locator('[data-workspace-operation-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));await p.locator('[name=Notes]').fill('Saved fixture definition');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>document.querySelector('[data-workspace-relationship="9"]')?.textContent.includes('Saved fixture definition'));
step='relationships layout, branch and record selection';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node="5"]');assert.equal(await p.locator('[data-workspace-relationship]').count(),4);assert.equal(await p.locator('[data-relationship-group]').count(),3);assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),false);await p.locator('[data-relationship-group="6"] > summary').click();assert.deepEqual(await p.locator('[data-relationship-group] > summary > strong').allTextContents(),['Recorded child','Recorded colleague','Recorded partner']);for(const [category,count]of [['family',2],['story',1],['',3]]){await p.locator('[data-workspace-filter] [name=Category]').selectOption(category);await p.locator('[data-workspace-filter]').getByRole('button',{name:'Apply filters'}).click();await p.waitForFunction(n=>document.querySelectorAll('[data-relationship-group]').length===n,count);}assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);await p.locator('[data-character-branch="3"]').click();await p.locator('[data-character-node="1"]').waitFor();await p.screenshot({path:'/tmp/character-workspace-family-desktop.png',fullPage:true});await p.locator('[data-workspace-relationship="9"] > p').first().click();assert(await p.locator('[data-workspace-relationship="9"]').evaluate(n=>n.classList.contains('is-selected')));await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.waitForSelector('[data-workspace-operation-form]');assert(await p.locator('[data-workspace-operation-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('[name=TypeID]').inputValue(),'1');await p.locator('[name=TypeID]').selectOption('2');await p.locator('[name=Notes]').fill('Saved fixture definition');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>document.querySelector('[data-workspace-relationship="9"]')?.textContent.includes('Saved fixture definition'));
step='inline stale error, Escape and draft protection';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.locator('[name=Notes]').fill('Draft retained');fail=true;await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.locator('.validation-summary-errors').waitFor();assert.equal(await p.locator('[name=Notes]').inputValue(),'Draft retained');p.once('dialog',d=>d.dismiss());await p.keyboard.press('Escape');assert(await p.locator('[data-workspace-dialog]').evaluate(n=>n.open));p.once('dialog',d=>d.accept());await p.locator('[data-workspace-cancel]').click();
step='explicit underlying removal with retained dependent history';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/2 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/1 separately recorded/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>!document.querySelector('[data-workspace-relationship="9"]'));assert(familyReads>1);assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);
step='explicit underlying removal with retained dependent history';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/2 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/1 separately recorded/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>!document.querySelector('[data-workspace-relationship="9"]'));assert(familyReads>1);assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);
step='bounded Evolution, Appearances and Knowledge and cached tabs';for(const tab of ['evolution','appearances','knowledge']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert.equal(await p.locator('[data-workspace-entry]').count(),25);await p.locator('[data-workspace-entry] summary').first().click();assert(await p.locator('[data-workspace-entry] .character-record-detail').first().isVisible());}await p.locator('[data-workspace-page="2"]').click();await p.waitForSelector('[data-character-tab-content][data-page="2"]');assert.equal(await p.locator('[data-workspace-entry]').count(),25);const reads=tabReads.length;await p.click('[data-character-tab="overview"]');await p.waitForSelector('[data-character-tab-content="overview"]');await p.click('[data-character-tab="knowledge"]');await p.waitForSelector('[data-character-tab-content="knowledge"]');assert.equal(tabReads.length,reads+1); // Overview invalidated by the save; Knowledge restores its second page.
step='selected story point and back forward';await p.click('[data-workspace-position]');await p.locator('[data-workspace-dialog] [data-workspace-entry="22"] summary').click();await p.locator('[data-workspace-set-position="22"]').click();await p.waitForSelector('[data-character-tab-content="knowledge"][data-scene="22"]');assert.match(p.url(),/SceneID=22/);await p.goBack();await p.waitForSelector('[data-character-tab-content="knowledge"][data-page="2"]');await p.goForward();await p.waitForSelector('[data-character-tab-content="knowledge"][data-scene="22"]');
step='Story network uses selected point and filters';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node]');await p.click('[data-character-lens="story"]');await p.locator('[data-character-connection="12"]').waitFor({state:'attached'});assert.match(await p.locator('[data-character-graph-selection]').innerText(),/Recorded identity|Current character/);
step='responsive and touch-size geometry';for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});for(const tab of ['overview','relationships','evolution','appearances','knowledge']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+tab);}}await p.screenshot({path:'/tmp/character-workspace-mobile.png',fullPage:true});assert.equal(native,1);assert(si<=2,'existing global/detail SI connections do not grow per tab');
step='direct legacy fragment, remembered character tab and keyboard';await p.goto(base+'/Characters/Details/5#character-gallery');await p.locator('[data-workspace-gallery][open]').waitFor();await p.click('[data-character-tab="knowledge"]');await p.waitForSelector('[data-character-tab-content="knowledge"]');await p.locator('[data-character-switch]').fill('another');await p.locator('[data-character-matches] a').click();await p.waitForURL(/\/Characters\/Details\/6\?tab=knowledge/);await p.locator('[data-character-tab-content="knowledge"]').waitFor();await p.locator('[data-character-tab="knowledge"]').focus();await p.keyboard.press('Home');await p.waitForSelector('[data-character-tab-content="overview"]');
step='event history and protected-source controls';await p.setViewportSize({width:1024,height:1000});await p.click('[data-character-tab="relationships"]');await p.locator('[data-workspace-history="12"]').click();await p.locator('[data-character-history] [data-workspace-entry] summary').first().click();await p.locator('[data-workspace-operation="event-edit"]').first().click();await p.locator('[name=Notes]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/one recorded development/);await p.locator('[data-workspace-cancel]').click();await p.locator('[data-workspace-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/only event #1/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/definition and other events remain/);await p.locator('[data-workspace-cancel]').click();await c.route('**/Characters/Workspace/Operation/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('protected','true');await r.fulfill({response:await r.fetch({url:base+'/character-workspace-operation-fixture'+u.search})});});await p.locator('[data-workspace-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/Direct modification\/removal is blocked/);assert.equal(await p.locator('[data-workspace-operation-form] [type=submit]').count(),0);await p.locator('[data-workspace-cancel]').click();
step='one exact history destination and ribbon targets';await p.setViewportSize({width:1024,height:1000});await p.click('[data-character-tab="relationships"]');assert.equal(await p.locator('[data-workspace-history]').count(),0);assert.equal(await p.locator('[data-character-history]').count(),0);assert.match(await p.locator('[data-workspace-relationship="12"] a').filter({hasText:'History'}).getAttribute('href'),/Dynamics\/Relationship\/12.*returnCharacterId=6/);assert.equal(await p.locator('.character-workspace-header .button-row,.character-workspace-header .dropdown,.character-workspace-header a.btn').count(),0);assert.match(await p.locator('[data-character-ribbon-edit]').getAttribute('href'),/Characters\/Edit\/6/);assert.equal(await p.locator('[data-character-ribbon] form[action*="Archive"] [name=id]').inputValue(),'6');await p.locator('[data-character-ribbon] [data-bs-toggle="dropdown"]').click();const menu=p.locator('[data-character-actions-for="6"]');await menu.waitFor({state:'visible'});assert.match(await menu.getByRole('link',{name:'Markdown',exact:true}).getAttribute('href'),/Exports\/Character\/6.*format=markdown/);assert(await menu.locator('form[action*="Archive"] button').evaluate(n=>{const r=n.getBoundingClientRect();return n.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2));}));await p.keyboard.press('Escape');
step='tablet touch pan and pinch';await p.setViewportSize({width:768,height:1000});await p.locator('[data-character-lens="family"]').click();await p.locator('[data-character-node]').first().waitFor({state:'attached'});await p.locator('[data-character-graph-reset]').click();const host=p.locator('[data-character-graph]');await host.scrollIntoViewIfNeeded();const box=await host.boundingBox(),x=box.x+box.width*.5,y=box.y+box.height*.5,cdp=await c.newCDPSession(p);await cdp.send('Emulation.setTouchEmulationEnabled',{enabled:true,maxTouchPoints:2});const world=p.locator('[data-character-graph] svg > g'),beforePan=await world.getAttribute('transform');await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x,y,id:1}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x+70,y:y+30,id:1}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});assert.notEqual(await world.getAttribute('transform'),beforePan);const beforePinch=await world.getAttribute('transform');await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:x-35,y,id:1},{x:x+35,y,id:2}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x-70,y,id:1},{x:x+70,y,id:2}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});assert.notEqual(await world.getAttribute('transform'),beforePinch);await p.screenshot({path:'/tmp/character-workspace-tablet-family.png',fullPage:false});await cdp.send('Emulation.setTouchEmulationEnabled',{enabled:false});
step='return to exact definition and retained group';removed=false;await p.goto(base+'/Characters/Details/5?tab=relationships&relationshipId=9');await p.waitForSelector('[data-workspace-relationship="9"].is-selected');assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});await p.locator('[data-character-ribbon] [data-bs-toggle="dropdown"]').click();const menu=p.locator('[data-character-actions-for="5"]');await menu.waitFor({state:'visible'});const archive=menu.locator('form[action*="Archive"] button');assert(await archive.evaluate(n=>{const r=n.getBoundingClientRect();return n.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2));}));assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.keyboard.press('Escape');}await p.setViewportSize({width:1366,height:1000});await p.evaluate(()=>{document.documentElement.dataset.appTheme='warm-dark';document.documentElement.dataset.theme='dark';document.documentElement.dataset.bsTheme='dark'});await p.screenshot({path:'/tmp/character-refinement-grouped-dark.png',fullPage:true});
step='read-only workspace';viewer=true;await p.goto(base+'/character-workspace-fixture?viewer=true&tab=relationships');await p.waitForSelector('[data-character-tab-content="relationships"]');assert.equal(await p.locator('[data-workspace-operation]').count(),0);assert.equal(await p.locator('[data-workspace-add]').count(),0);assert.deepEqual(errors,[]);console.log('PASS main Character browser: compact header, five lazy tabs, dossier/aliases/gallery, bounded explorers and pages, Family branches, Story and selected point, diagram/record selection, modal widths/inline error/Escape/unsaved protection, explicit archive consequences, refresh, cache, back/forward, character links, legacy hash, keyboard, desktop/laptop/tablet/mobile, touch pan/pinch, event history/source protection and read-only; connection counts stable across tabs.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,3 @@
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();try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let protectedSource=false;await c.route('**/Characters/Workspace/Operation/*',async r=>{if(r.request().method()==='POST'){await r.fulfill({json:{saved:true,message:'One canonical event saved.'}});return;}const u=new URL(r.request().url());u.searchParams.set('protected',String(protectedSource));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-operation-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async l=>l.click());for(const count of [0,1,5]){await p.setViewportSize({width:1366,height:1000});await p.goto(base+'/relationship-evolution-fixture?count='+count);await p.locator('[data-relationship-evolution="9"]').waitFor();await p.evaluate(()=>{document.documentElement.dataset.appTheme='warm-dark';document.documentElement.dataset.theme='dark';document.documentElement.dataset.bsTheme='dark'});assert.equal(await p.locator('[data-evolution-event]').count(),count);assert.equal(await p.locator('.relationship-evolution-chart').count(),count>1?1:0);assert.equal(await p.locator('.dynamics-timeline').count(),0);if(count===0)assert.match(await p.locator('main').innerText(),/No recorded events/);if(count===1)assert.match(await p.locator('main').innerText(),/One recorded event/);if(count===5){assert.deepEqual(await p.locator('[data-evolution-event]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.evolutionEvent))),[1,2,3,4,5]);assert.equal(await p.locator('.relationship-evolution-chart circle').count(),4);await p.locator('.relationship-evolution-chart a').first().click();assert.match(p.url(),/#event-1/);await p.screenshot({path:'/tmp/relationship-evolution-dark-desktop.png',fullPage:true});}for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}assert.match(await p.getByRole('link',{name:'Return to character Relationships'}).getAttribute('href'),/Characters\/Details\/5.*relationshipId=9/);}
await p.locator('[data-history-operation="event-edit"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-history-dialog]').innerText(),/one recorded development/);await p.locator('[name=Notes]').fill('Unsaved event draft');p.once('dialog',d=>d.dismiss());await p.keyboard.press('Escape');assert(await p.locator('[data-history-dialog]').evaluate(n=>n.open));p.once('dialog',d=>d.accept());await p.locator('[data-workspace-cancel]').click();let refreshes=0,navigations=0;p.on('request',r=>{if(r.url().includes('/relationship-evolution-fixture'))refreshes++;});p.on('load',()=>navigations++);await p.locator('[data-history-operation="event-edit"]').first().click();await p.locator('[name=Notes]').fill('Saved event draft');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-history-dialog]').open);await p.locator('.pd-toast').filter({hasText:'One canonical event saved.'}).waitFor();await p.waitForTimeout(150);assert(refreshes>0);assert.equal(navigations,0);protectedSource=true;await p.locator('[data-history-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-history-dialog]').innerText(),/Direct modification\/removal is blocked/);assert.equal(await p.locator('[data-workspace-operation-form] [type=submit]').count(),0);await p.locator('[data-workspace-cancel]').click();await p.goto(base+'/relationship-evolution-fixture?count=1&viewer=true');assert.equal(await p.locator('[data-history-operation]').count(),0);assert.deepEqual(errors,[]);console.log('PASS relationship Evolution: empty/single/multiple canonical histories, dark theme bounded intensity chart without invented missing values, chronological source links, exact return identity, desktop/laptop/tablet/mobile, event modal draft/Escape/source protection and Viewer permissions.');}finally{await b.close();}})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -174,7 +174,9 @@ const base = 'http://127.0.0.1:5238';
await app.locator('.pd-context-popup').waitFor();
assert.match(await app.locator('.pd-context-popup').innerText(), /Edit character|Add relationship/, 'map context actions remain available after focusing');
await app.keyboard.press('Escape');
await page.goto(base + '/fixture?page=relationships&relationshipId=1');
await page.waitForFunction(()=>window.PlotDirectorRelationshipWorkspace?.selectedRelationship?.characterRelationshipID===1);
assert.deepEqual(errors, []);
console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout and PWA menu');
console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout, exact definition deep link and PWA menu');
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });

View File

@ -5,14 +5,14 @@ using PlotLine.ViewModels;
internal static class CharacterWorkspaceBrowserFixture
{
public static CharacterDetailViewModel Header(int id=5,bool viewer=false)=>new(){Project=new(){ProjectID=7,ProjectName="Character workspace qualification"},Character=new(){CharacterID=id,ProjectID=7,CharacterName=id==5?"A character with a long established canonical name":"Another established character",CharacterImportance=6,Sex="Recorded sex",BirthDate=new(1980,1,1),DefaultDescription=string.Join("\n",Enumerable.Repeat("A long canonical biography with details that must wrap naturally in the dossier.",12)),Height="Recorded height",EyeColour="Recorded eyes"},WorkspaceCanEdit=!viewer,WorkspaceCounts=new(){Relationships=3,Appearances=71,Attributes=44,Knowledge=66,Images=0,FirstSceneID=22},DisplayAge="40 years",AgeContext="At age reference scene",AgeReferenceScene=new(){SceneID=22,SceneTitle="Reference scene"},CharacterAnalysis=new(){CharacterID=id,Status="Completed",Summary="Existing persisted analysis, distinct from the author's profile."},Aliases=[new(){CharacterID=id,Alias="Recorded variant"}]};
public static CharacterRelationship Relationship(int id=9)=>new(){CharacterRelationshipID=id,ProjectID=7,CharacterAID=5,CharacterBID=id==12?7:id==10?8:6,CharacterAName="A character with a long established canonical name",CharacterBName=id==12?"Recorded colleague":id==10?"Recorded partner":"Recorded child",RelationshipTypeName=id==12?"Friend":id==10?"Spouse":"Parent",RelationshipCategoryName=id==12?"Friendship":id==10?"Romantic / Sexual":"Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",Notes="Canonical definition notes",IsReciprocal=id==10};
public static CharacterRelationship Relationship(int id=9)=>new(){RelationshipTypeID=id==12?3:1,WorkspaceDefinitionCount=id==9?2:1,CharacterRelationshipID=id,ProjectID=7,CharacterAID=5,CharacterBID=id==12?7:id==10?8:6,CharacterAName="A character with a long established canonical name",CharacterBName=id==12?"Recorded colleague":id==10?"Recorded partner":"Recorded child",RelationshipTypeName=id==12?"Friend":id==10?"Spouse":"Parent",RelationshipCategoryName=id==12?"Friendship":id==10?"Romantic / Sexual":"Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",Notes="Canonical definition notes",IsReciprocal=id==10};
public static CharacterWorkspacePage Page(int id,CharacterWorkspaceQuery q,bool viewer=false,bool removed=false,string? notes=null)
{
var p=Header(id,viewer);var page=new CharacterWorkspacePage{Profile=p,Query=q,Total=q.Tab=="overview"?0:71,Books=[new("First book","12"),new("Second book","13")],PointLabel=q.SceneID.HasValue?"First book · Ch 1 · Scene 2: Earlier point":null};
if(q.Tab=="relationships"){page.Total=removed?2:3;page.Relationships=new[]{9,10,12}.Where(n=>!removed||n!=9).Where(n=>!q.RelationshipID.HasValue||n==q.RelationshipID).Select(n=>{var r=Relationship(n);if(notes!=null&&n==9)r.Notes=notes;return new CurrentRelationshipViewModel{Relationship=r,LatestEvent=q.SceneID.HasValue?new(){RelationshipStateName="Earlier recorded state",Description="Earlier canonical development"}:null};}).ToArray();return page;}
if(q.Tab=="relationships"){page.Total=3;page.Relationships=new[]{9,10,12,13}.Where(n=>!removed||n!=9).Where(n=>!q.RelationshipID.HasValue||n==q.RelationshipID).Select(n=>{var r=Relationship(n);if(n==13){r.CharacterAID=6;r.CharacterBID=5;r.CharacterAName="Recorded child";r.CharacterBName=p.Character.CharacterName;r.WorkspaceDefinitionCount=2;}if(notes!=null&&n==9)r.Notes=notes;return new CurrentRelationshipViewModel{Relationship=r,LatestEvent=q.SceneID.HasValue?new(){RelationshipStateName="Earlier recorded state",Description="Earlier canonical development"}:null};}).Where(x=>string.IsNullOrEmpty(q.Category)||(q.Category=="family")==ContextRelationshipLenses.Family(x.Relationship.RelationshipCategoryName,x.Relationship.RelationshipTypeName)).OrderBy(x=>x.Relationship.CharacterAID==id?x.Relationship.CharacterBName:x.Relationship.CharacterAName,StringComparer.OrdinalIgnoreCase).ThenBy(x=>x.Relationship.CharacterRelationshipID).ToArray();return page;}
page.Entries=q.Tab is "overview" or "gallery"?[]:Enumerable.Range((q.Page-1)*25+1,Math.Min(25,Math.Max(0,71-(q.Page-1)*25))).Select(i=>new CharacterWorkspaceEntry{ID=i,Kind=q.Tab=="appearances"?"appearances":q.Tab=="knowledge"?"knowledge":q.Tab=="history"?"relationships":q.Tab=="scenes"?"scenes":"attributes",RelationshipID=q.Tab=="history"?q.RelationshipID:null,SceneID=i,BookID=i>35?13:12,BookTitle=i>35?"Second book":"First book",ChapterNumber=(i-1)/10+1,SceneNumber=i,SceneTitle="Recorded source scene "+i,Ordinal=i,Heading=q.Tab=="scenes"?"Source scene "+i:q.Tab=="knowledge"?"Recorded asset or thread":"Recorded change "+i,State=q.Tab=="knowledge"?(i%2==0?"Knows":"Partially Knows"):"New recorded state",Previous=q.Tab=="evolution"?"Previous recorded state":null,Notes="Existing canonical detail and source. "+new string('x',220),EvidenceState=i%7==0?"Needs review":"Verified",IsPov=i%3==0}).Where(e=>string.IsNullOrEmpty(q.Search)||e.Heading!.Contains(q.Search,StringComparison.OrdinalIgnoreCase)).ToArray();return page;
}
public static CharacterWorkspaceOperation Operation(int id,string action,int relationship,int? eventId,bool protectedSource=false,string version="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")=>new(){CharacterID=id,RelationshipID=relationship,EventID=eventId,Action=action,Version=version,Record=new(){Relationship=Relationship(relationship),Version=version,EventCount=2,OtherPairRecords=1},Event=eventId.HasValue?new(){Record=new(){RelationshipEventID=eventId.Value,CharacterRelationshipID=relationship,SceneID=22,RelationshipStateID=1,Description="One event description"},ProtectedSource=protectedSource}:null,Notes=eventId.HasValue?"One event description":"Canonical definition notes",StateID=1,Intensity=5,States=[new("Established","1"),new("Changed","2")]};
public static CharacterWorkspaceOperation Operation(int id,string action,int relationship,int? eventId,bool protectedSource=false,string version="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")=>new(){CharacterID=id,RelationshipID=relationship,EventID=eventId,Action=action,Version=version,TypeID=1,Types=[new("Family · Parent","1"),new("Family · Child","2")],Reciprocal=false,Permanent=true,ReaderKnows=false,Record=new(){Relationship=Relationship(relationship),Version=version,EventCount=action=="definition"?0:2,OtherPairRecords=1},Event=eventId.HasValue?new(){Record=new(){RelationshipEventID=eventId.Value,CharacterRelationshipID=relationship,SceneID=22,RelationshipStateID=1,Description="One event description"},ProtectedSource=protectedSource}:null,Notes=eventId.HasValue?"One event description":"Canonical definition notes",StateID=1,Intensity=5,States=[new("Established","1"),new("Changed","2")]};
public static ContextFamilyTree Family(int focus,int[] expanded,bool removed=false)
{
var links=new List<CharacterRelationship>{Relationship(9),Relationship(10),new(){CharacterRelationshipID=1,CharacterAID=1,CharacterBID=3,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=2,CharacterAID=3,CharacterBID=5,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=3,CharacterAID=4,CharacterBID=5,RelationshipTypeName="Biological Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=4,CharacterAID=6,CharacterBID=11,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=5,CharacterAID=12,CharacterBID=6,RelationshipTypeName="Adoptive Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=6,CharacterAID=13,CharacterBID=6,RelationshipTypeName="Step Parent",RelationshipCategoryName="Family"}}.Where(r=>!removed||r.CharacterRelationshipID!=9).ToArray();

View File

@ -1,3 +1,4 @@
using PlotLine.Models;
using System.Data;using System.Text.Json;using Dapper;using Microsoft.Data.SqlClient;
internal static class CharacterWorkspaceDatabaseTests
@ -17,7 +18,24 @@ async Task Case(string name,Func<SqlTransaction,Task> action){using var tx=db.Be
await Case("parent archive retains history and restores",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);await Event(tx,r);var frame=await Frame(tx,r);Check(frame.Events==2,"preview reports dependent scene events");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsArchived=1",new{r},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE CharacterRelationshipID=@r",new{r},tx)==2,"erroneous parent definition archives reversibly without cascading its two events");await db.ExecuteAsync("dbo.Archive_Restore",new{EntityType="Relationship",EntityID=r},tx,commandType:CommandType.StoredProcedure);Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"existing canonical restore reactivates the same definition and retained history");});
await Case("reciprocal single record and independent reverse",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterAID=@actor AND CharacterBID=@c OR CharacterAID=@c AND CharacterBID=@actor",new{actor,c},tx)==1,"canonical reciprocal flag does not create an extra reverse row");int reverse=await Rel(tx,c,false,childType,true);var frame=await Frame(tx,r);Check(frame.Other==1,"confirmation distinguishes a separately authored reverse fact");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@reverse",new{reverse},tx)==0,"independent reverse fact is retained, not silently cascaded");});
foreach(var type in new[]{parent,friend})await Case("definition edit "+type,async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,type);var frame=await Frame(tx,r);await Change(tx,r,frame.Version,"definition");var row=await db.QuerySingleAsync<(int Type,int A,int B,bool Initial,string Notes)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID,IsInitialRelationship,Notes FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==type&&row.A==actor&&row.B==c&&row.Initial&&row.Notes=="Updated isolated definition","focused definition edit preserves pair/type and family/story meaning");});
await Case("global grouped alphabetical pagination",async tx=>{
string token="Isolated workspace regression Group "+Guid.NewGuid().ToString("N");var expected=new List<(int ID,string Name)>();
for(int i=0;i<28;i++){string name=token+" "+(i==0?"alpha":i==1?"ALPHA":((char)('b'+i%22)).ToString()+i.ToString("00"));int c=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName=name},tx,commandType:CommandType.StoredProcedure);expected.Add((c,name));await Rel(tx,c);}
int focus=expected[0].ID;await Rel(tx,focus,false,friend);await Rel(tx,focus,false,childType,true);for(int i=0;i<25;i++)await Rel(tx,focus);
async Task<(int Total,List<dynamic> Rows)> Read(int page=1,string? category=null,int? other=null,int definitionPage=1){using var grid=await db.QueryMultipleAsync("dbo.CharacterWorkspace_Relationships",new{CharacterID=actor,UserID=owner,Page=page,Search=token,Category=category,OtherCharacterID=other,DefinitionPage=definitionPage},tx,commandType:CommandType.StoredProcedure);int total=await grid.ReadSingleAsync<int>();await grid.ReadAsync<dynamic>();await grid.ReadAsync<dynamic>();await grid.ReadAsync<dynamic>();return(total,(await grid.ReadAsync<dynamic>()).ToList());}
var first=await Read();var second=await Read(2);var actual=first.Rows.Concat(second.Rows).Select(r=>(int)((int)r.CharacterAID==actor?r.CharacterBID:r.CharacterAID)).Distinct().ToArray();var sorted=expected.OrderBy(e=>e.Name,StringComparer.OrdinalIgnoreCase).ThenBy(e=>e.ID).Select(e=>e.ID).ToArray();Check(first.Total==28&&actual.SequenceEqual(sorted),"case-insensitive alphabetical groups span all pages, direction independent and duplicate names stable by identity");
var group=await Read(other:focus);var more=await Read(other:focus,definitionPage:2);Check(group.Total==1&&group.Rows.Count==25&&more.Rows.Count==3,"one character group retains 28 distinct definitions with bounded inner pagination");
var family=await Read(category:"family",other:focus);var story=await Read(category:"story",other:focus);Check(family.Total==1&&story.Total==1&&story.Rows.Count==1&&(string)story.Rows[0].RelationshipTypeName=="Friend","family/story filters classify individual definitions, including one pair in both categories");
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE ProjectID=@project AND (CharacterAID=@focus AND CharacterBID=@actor OR CharacterBID=@focus AND CharacterAID=@actor)",new{project,focus,actor},tx)==28,"grouping and pagination never merge or deduplicate canonical definitions");
});
async Task Structural(SqlTransaction tx,int r,string v,int type,bool reverse=false,bool? reciprocal=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=owner,RelationshipID=r,Version=v,Action="definition",Notes="Structural isolated edit",TypeID=type,ReverseDirection=reverse,Reciprocal=reciprocal},tx,commandType:CommandType.StoredProcedure);
await Case("canonical type and direction edits retain record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,childType,true);var row=await db.QuerySingleAsync<(int Type,int A,int B)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==childType&&row.A==c&&row.B==actor,"canonical family type/direction edit retains exact definition ID without recreating records");});
await Case("story reciprocity edit retains one record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,friend);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,friend,reciprocal:true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsReciprocal=1",new{r},tx)==1,"story reciprocity is one flag on the same canonical definition");});
await Case("incompatible category rejected",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,friend);throw new Exception("Cross-category change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"cross-category type change requires full-editor review");}});
await Case("history prevents semantic rewrite",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,childType);throw new Exception("History reinterpretation accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"dependent history prevents unsafe structural reinterpretation");}});
await Case("family reciprocity cannot manufacture reverse parentage",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,parent,reciprocal:true);throw new Exception("Family reciprocity change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"family reciprocity changes require explicit full-editor review");}});
await Case("single event edit then remove",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);int e=await Event(tx,r),other=await Event(tx,r);var frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-edit",e:e,notes:"Updated one event");Check(await db.ExecuteScalarAsync<string>("SELECT Description FROM dbo.RelationshipEvents WHERE RelationshipEventID=@e",new{e},tx)=="Updated one event","one event changes without rewriting the definition");frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-remove",e:e);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE RelationshipEventID=@other",new{other},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"single-event deletion leaves the other event and definition active");});
await Case("dedicated history canonical order and bounded pages",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);for(int i=0;i<28;i++)await Event(tx,r,"Recorded history "+i);async Task<List<RelationshipProgressionPoint>> Read(int page){using var grid=await db.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution",new{CharacterRelationshipID=r,Page=page},tx,commandType:CommandType.StoredProcedure);await grid.ReadAsync<CharacterRelationship>();var rows=(await grid.ReadAsync<RelationshipProgressionPoint>()).ToList();await grid.ReadAsync<dynamic>();return rows;}var first=await Read(1);var second=await Read(2);Check(first.Count==25&&second.Count==3&&first.All(e=>e.TotalRecords==28),"dedicated history pages 28 actual events as 25 + 3 with no synthetic transitions");Check(first.Concat(second).Select(e=>e.RelationshipEventID).SequenceEqual(first.Concat(second).Select(e=>e.RelationshipEventID).OrderBy(id=>id)),"same-scene developments retain stable canonical event order");});
await Case("stale dependent history",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Event(tx,r);try{await Change(tx,r,frame.Version,"archive");throw new Exception("Stale archive accepted");}catch(SqlException ex)when(ex.Number==51021){Check(true,"new dependent event invalidates the confirmation atomically");}});
await Case("permission enforcement",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",user:-991);throw new Exception("Foreign user accepted");}catch(SqlException ex)when(ex.Number==51020){Check(true,"ungranted user cannot mutate a definition");}});
await Case("missing explicit confirmation",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",false);throw new Exception("Unconfirmed accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"SQL enforces explicit destructive confirmation");}});

View File

@ -1569,7 +1569,7 @@ static void CharacterDetailCanQueueSingleCharacterEnrichment()
var controller = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs"));
var characterService = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs"));
var enrichmentService = File.ReadAllText(Path.Combine(root, "Services/CharacterEnrichmentService.cs"));
var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"));
var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + File.ReadAllText(Path.Combine(root, "Views/Shared/_CharacterRibbonCommands.cshtml"));
Assert(view.Contains("Reanalyse character", StringComparison.Ordinal), "Character detail should expose a discreet reanalyse action.");
Assert(view.Contains("data-character-reanalyse-form", StringComparison.Ordinal), "Character reanalyse action should be script-addressable.");
@ -6236,7 +6236,7 @@ static void CharacterMergeIsReusableStoredProcedureWorkflow()
var repository = File.ReadAllText(Path.Combine(root, "Data/Repositories.cs"));
var services = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs"));
var controller = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs"));
var details = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"));
var details = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + File.ReadAllText(Path.Combine(root, "Views/Shared/_CharacterRibbonCommands.cshtml"));
var merge = File.ReadAllText(Path.Combine(root, "Views/Characters/Merge.cshtml"));
var siCharacters = File.ReadAllText(Path.Combine(root, "Services/StoryIntelligenceCharacterImportService.cs"));
var migration = File.ReadAllText(Path.Combine(root, "Sql/165_Phase26A_PovAndCharacterIdentityFoundation.sql"));

View File

@ -414,6 +414,7 @@ internal static class ToolbarBrowserHost
var graph=PlotLine.Services.Context.ContextRelationshipLenses.Compose(new(new(){Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=fixture.Scene.SceneID,ChapterID=10}],Characters=fixture.Structure.Seeds.Where(c=>visible.People.Contains(c.CharacterID)).ToList(),Relationships=fixture.Structure.Links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).ToList()},focus,visible.Truncated),"family",fixture.Scene,context.Request.Query["readonly"]!="true");
return context.Response.WriteAsJsonAsync(new PlotLine.Services.Context.ContextFamilyTree(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People)));
});
app.MapGet("/relationship-evolution-fixture",async context=>{int count=int.TryParse(context.Request.Query["count"],out var n)?n:1;var model=new RelationshipEvolutionViewModel{Project=new(){ProjectID=7,ProjectName="Evolution fixture"},Relationship=CharacterWorkspaceBrowserFixture.Relationship(),ReturnCharacterID=5,CanEdit=context.Request.Query["viewer"]!="true",Events=Enumerable.Range(1,count).Select(i=>new PlotLine.Models.RelationshipProgressionPoint{RelationshipEventID=i,CharacterRelationshipID=9,SceneID=i,SceneNumber=i,BookTitle="Recorded book",ChapterNumber=1,SceneTitle="Canonical scene "+i,GlobalSceneIndex=i*3,Intensity=i==2?null:Math.Min(10,i+2),RelationshipStateName="Recorded state "+i,Description="Canonical event description",TotalRecords=count}).ToArray()};await RenderFullAsync(context,"Dynamics","Relationship",model);});
app.MapGet("/character-workspace-fixture",async context=>{
var id=int.TryParse(context.Request.Query["id"],out var cid)?cid:5;var profile=CharacterWorkspaceBrowserFixture.Header(id,context.Request.Query["viewer"]=="true");profile.WorkspaceTab=context.Request.Query["tab"].FirstOrDefault();if(profile.WorkspaceTab!=null)profile.WorkspacePage=CharacterWorkspaceBrowserFixture.Page(id,new(){Tab=profile.WorkspaceTab},context.Request.Query["viewer"]=="true");await RenderFullAsync(context,"Characters","Details",profile);
});

View File

@ -26,7 +26,7 @@ public sealed class CharacterWorkspaceController(CharacterWorkspace workspace):C
public async Task<IActionResult> Operation(int id,CharacterWorkspaceOperation input,CancellationToken ct)
{
if(input.CharacterID!=id)return Forbid();try{if(!ModelState.IsValid)throw new ArgumentException("Check the fields below.");await workspace.Change(input,ct);return Ok(new{saved=true,message=input.Action=="archive"?"Relationship removed from active views. History retained; restore is available in Archived Items.":input.Action=="event-remove"?"One relationship event removed.":"Relationship changes saved."});}
catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){var frame=await workspace.Operation(id,input.RelationshipID,input.EventID,input.Action,ct);frame.Version=input.Version;frame.Notes=input.Notes;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Awareness=input.Awareness;frame.Confirmed=input.Confirmed;ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",frame);}
catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){CharacterWorkspaceOperation frame;try{frame=await workspace.Operation(id,input.RelationshipID,input.EventID,input.Action,ct);}catch(UnauthorizedAccessException){return Forbid();}frame.TypeID=input.TypeID??frame.TypeID;frame.ReverseDirection=input.ReverseDirection;frame.Reciprocal=input.Reciprocal??frame.Reciprocal;frame.Permanent=input.Permanent;frame.ReaderKnows=input.ReaderKnows;frame.Version=input.Version;frame.Notes=input.Notes;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Awareness=input.Awareness;frame.Confirmed=input.Confirmed;ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",frame);}
}
[HttpGet("Add/{id:int}")]
public async Task<IActionResult> Add(int id,CancellationToken ct)

View File

@ -19,10 +19,14 @@ public sealed class DynamicsController(IDynamicsService dynamics) : Controller
return model is null ? NotFound() : View(model);
}
public async Task<IActionResult> Relationship(int id)
public async Task<IActionResult> Relationship(int id,[FromServices]CharacterWorkspace workspace,int? returnCharacterId=null,int? returnSceneId=null,int page=1,CancellationToken ct=default)
{
var model = await dynamics.GetRelationshipEvolutionAsync(id);
return model is null ? NotFound() : View(model);
if(page is <1 or >100000)return BadRequest();
var model=await dynamics.GetRelationshipEvolutionAsync(id,page);if(model is null)return NotFound();
var r=model.Relationship;var anchor=returnCharacterId==r.CharacterBID?r.CharacterBID:r.CharacterAID;
try{var scope=await workspace.Scope(anchor);if(scope.Project.ProjectID!=r.ProjectID)return NotFound();model.CanEdit=scope.CanEdit;}catch(UnauthorizedAccessException){return NotFound();}
if(page>1&&model.Events.Count==0){model=await dynamics.GetRelationshipEvolutionAsync(id,1);if(model is null)return NotFound();model.CanEdit=(await workspace.Scope(anchor)).CanEdit;page=1;}
model.ReturnCharacterID=anchor;model.ReturnSceneID=returnSceneId;model.Page=page;return View(model);
}
public async Task<IActionResult> Knowledge(int id)

View File

@ -29,7 +29,7 @@ public sealed class CharacterWorkspaceReader(ISqlConnectionFactory connections,I
public async Task<(int,RelationshipMapData)> Relationships(int character,int project,int user,CharacterWorkspaceQuery q,CancellationToken ct)
{
using var db=connections.CreateConnection();int total;RelationshipMapData data;
using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Relationships",new{CharacterID=character,UserID=user,q.Page,Search=q.Search??"",q.RelationshipID},commandType:CommandType.StoredProcedure,cancellationToken:ct))){total=(await grid.ReadSingleAsync<Count>()).Total;data=new(){Books=(await grid.ReadAsync<Book>()).ToList(),Chapters=(await grid.ReadAsync<Chapter>()).ToList(),Scenes=(await grid.ReadAsync<Scene>()).ToList(),Relationships=(await grid.ReadAsync<CharacterRelationship>()).ToList()};}
using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Relationships",new{CharacterID=character,UserID=user,q.Page,Search=q.Search??"",q.RelationshipID,q.Category,q.OtherCharacterID,q.DefinitionPage},commandType:CommandType.StoredProcedure,cancellationToken:ct))){total=(await grid.ReadSingleAsync<Count>()).Total;data=new(){Books=(await grid.ReadAsync<Book>()).ToList(),Chapters=(await grid.ReadAsync<Chapter>()).ToList(),Scenes=(await grid.ReadAsync<Scene>()).ToList(),Relationships=(await grid.ReadAsync<CharacterRelationship>()).ToList()};}
if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Use the full Relationships Editor for a project beyond the workspace ordering limit.");
var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var maximum=q.SceneID.HasValue?order.SingleOrDefault(s=>s.SceneID==q.SceneID)?.Ordinal??throw new UnauthorizedAccessException():order.Count-1;
var events=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=maximum},commandType:CommandType.StoredProcedure,cancellationToken:ct))).ToList();await ParagraphEvidenceProjection.Apply(db,configuration,events);
@ -44,5 +44,5 @@ public sealed class CharacterWorkspaceReader(ISqlConnectionFactory connections,I
var item=(await grid.ReadAsync<dynamic>()).SingleOrDefault();if(item==null)return(frame,null);json=JsonSerializer.Serialize((object)item);var eventFrame=JsonSerializer.Deserialize<CharacterWorkspaceEvent>(json,options)!;eventFrame.Record=JsonSerializer.Deserialize<RelationshipEvent>(json,options)!;return(frame,eventFrame);
}
public async Task Change(CharacterWorkspaceOperation input,int user,CancellationToken ct)
{using var db=connections.CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=input.CharacterID,UserID=user,RelationshipID=input.RelationshipID,input.Version,input.Action,input.Confirmed,EventID=input.EventID,input.Notes,input.StateID,input.Intensity,input.Awareness},commandType:CommandType.StoredProcedure,cancellationToken:ct));}
{using var db=connections.CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=input.CharacterID,UserID=user,RelationshipID=input.RelationshipID,input.Version,input.Action,input.Confirmed,EventID=input.EventID,input.Notes,input.StateID,input.Intensity,input.Awareness,input.TypeID,input.ReverseDirection,input.Reciprocal,input.Permanent,input.ReaderKnows},commandType:CommandType.StoredProcedure,cancellationToken:ct));}
}

View File

@ -431,7 +431,7 @@ public interface IExportRepository
public interface IDynamicsRepository
{
Task<(Character? Character, IReadOnlyList<CharacterArcPoint> ArcPoints, IReadOnlyList<RelationshipEvent> RelationshipEvents, IReadOnlyList<CharacterKnowledgeItem> KnowledgeEvents, IReadOnlyList<DynamicsIssue> Issues)> GetCharacterArcAsync(int characterId);
Task<(CharacterRelationship? Relationship, IReadOnlyList<RelationshipProgressionPoint> Events, IReadOnlyList<DynamicsIssue> Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId);
Task<(CharacterRelationship? Relationship, IReadOnlyList<RelationshipProgressionPoint> Events, IReadOnlyList<DynamicsIssue> Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1);
Task<(Character? Character, IReadOnlyList<CharacterKnowledgeItem> KnowledgeEvents, IReadOnlyList<DynamicsIssue> Issues)> GetKnowledgeTimelineAsync(int characterId);
Task<(IReadOnlyList<CharacterPairingSummary> Pairings, IReadOnlyList<DynamicsIssue> Issues)> GetStoryDynamicsAsync(int projectId);
Task RunContinuityChecksAsync(int projectId, int? bookId, int? sceneId);
@ -1774,10 +1774,10 @@ public sealed class DynamicsRepository(ISqlConnectionFactory connectionFactory,I
return (character,arc,await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,relationships),await ParagraphEvidenceProjection.Apply(connection,paragraphConfiguration,knowledge),issues);
}
public async Task<(CharacterRelationship? Relationship, IReadOnlyList<RelationshipProgressionPoint> Events, IReadOnlyList<DynamicsIssue> Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId)
public async Task<(CharacterRelationship? Relationship, IReadOnlyList<RelationshipProgressionPoint> Events, IReadOnlyList<DynamicsIssue> Issues)> GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1)
{
using var connection = connectionFactory.CreateConnection();
using var result = await connection.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution", new { CharacterRelationshipID = characterRelationshipId }, commandType: CommandType.StoredProcedure);
using var result = await connection.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution", new { CharacterRelationshipID = characterRelationshipId,Page=page }, commandType: CommandType.StoredProcedure);
return (
await result.ReadSingleOrDefaultAsync<CharacterRelationship>(),
(await result.ReadAsync<RelationshipProgressionPoint>()).ToList(),

View File

@ -1329,6 +1329,7 @@ public sealed class RelationshipState
public sealed class CharacterRelationship
{
public int WorkspaceDefinitionCount {get;set;} = 1;
public int? CreatedByUserID { get; set; }
public int? ModifiedByUserID { get; set; }
public DateTime? CreatedDateUTC { get; set; }
@ -2587,6 +2588,9 @@ public sealed class CharacterArcPoint
public sealed class RelationshipProgressionPoint
{
public int TotalRecords {get;set;}
public string EvidenceState {get;set;}="Verified";
public string? SourceReviewKey {get;set;}
public int RelationshipEventID { get; set; }
public int CharacterRelationshipID { get; set; }
public int SceneID { get; set; }

View File

@ -14,7 +14,7 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR
var author=user.UserId??throw new UnauthorizedAccessException();var character=await characters.GetCharacterAsync(id)??throw new UnauthorizedAccessException();var project=await projects.GetForUserAsync(character.ProjectID,author)??throw new UnauthorizedAccessException();return(character,project,ContextEditPolicy.CanEdit(project));
}
public static void Validate(CharacterWorkspaceQuery q)
{if(!Tabs.Contains(q.Tab)&&q.Tab is not ("history" or "scenes" or "gallery"))throw new ArgumentException("Choose a character workspace tab.");if(q.Page is <1 or >100000||q.Search?.Length>120||q.Category?.Length>100)throw new ArgumentException("Invalid workspace filter.");}
{if(q.Tab=="relationships"&&!string.IsNullOrEmpty(q.Category)&&q.Category is not ("family" or "story"))throw new ArgumentException("Choose Family, Story or all definitions.");if(!Tabs.Contains(q.Tab)&&q.Tab is not ("history" or "scenes" or "gallery"))throw new ArgumentException("Choose a character workspace tab.");if(q.Page is <1 or >100000||q.Search?.Length>120||q.Category?.Length>100||q.DefinitionPage is <1 or >100000)throw new ArgumentException("Invalid workspace filter.");}
public async Task<CharacterDetailViewModel> Header(int id,string? tab,CancellationToken ct)
{
if(tab!=null&&!Tabs.Contains(tab))throw new ArgumentException("Choose a character workspace tab.");var scope=await Scope(id);var summary=await reader.Summary(id,user.UserId!.Value,ct);var age=CharacterAgeDisplayService.GetProfileAge(scope.Character,summary.Ages.Select(r=>r.Scene).ToArray(),summary.Ages.Where(r=>r.IsAppearance).Select(r=>new SceneCharacter{CharacterID=id,SceneID=r.SceneID}).ToArray());
@ -51,7 +51,7 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR
{
var scope=await Scope(id);if(!scope.CanEdit)throw new UnauthorizedAccessException();if(action is not ("definition" or "archive" or "event-edit" or "event-remove"))throw new ArgumentException("Unsupported relationship operation.");
(CharacterRelationshipFrame Relationship,CharacterWorkspaceEvent? Event) frame;try{frame=await reader.Frame(id,user.UserId!.Value,relationship,eventID,ct);}catch(SqlException error)when(error.Number==51020){throw new UnauthorizedAccessException();}if(action.StartsWith("event-")&&frame.Event==null)throw new UnauthorizedAccessException();var r=frame.Relationship.Relationship;var e=frame.Event?.Record;var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);
return new(){CharacterID=id,RelationshipID=relationship,EventID=eventID,Action=action,Version=frame.Relationship.Version,Record=frame.Relationship,Event=frame.Event,Notes=e?.Description??r.Notes,StateID=e?.RelationshipStateID??r.InitialRelationshipStateID,Intensity=e?.Intensity??r.InitialIntensity,Awareness=e?.IsKnownToOtherCharacter??r.ReaderInitiallyKnows,States=lookups.RelationshipStates.Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToArray()};
return new(){TypeID=r.RelationshipTypeID,Reciprocal=r.IsReciprocal,Permanent=r.IsPermanent,ReaderKnows=r.IsKnownToReader,Types=lookups.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray(),CharacterID=id,RelationshipID=relationship,EventID=eventID,Action=action,Version=frame.Relationship.Version,Record=frame.Relationship,Event=frame.Event,Notes=e?.Description??r.Notes,StateID=e?.RelationshipStateID??r.InitialRelationshipStateID,Intensity=e?.Intensity??r.InitialIntensity,Awareness=e?.IsKnownToOtherCharacter??r.ReaderInitiallyKnows,States=lookups.RelationshipStates.Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToArray()};
}
public async Task Change(CharacterWorkspaceOperation input,CancellationToken ct)
{

View File

@ -648,7 +648,7 @@ public interface IExportService
public interface IDynamicsService
{
Task<CharacterArcViewModel?> GetCharacterArcAsync(int characterId);
Task<RelationshipEvolutionViewModel?> GetRelationshipEvolutionAsync(int characterRelationshipId);
Task<RelationshipEvolutionViewModel?> GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1);
Task<KnowledgeTimelineViewModel?> GetKnowledgeTimelineAsync(int characterId);
Task<StoryDynamicsViewModel?> GetStoryDynamicsAsync(int projectId);
Task RunContinuityChecksAsync(int projectId, int? bookId, int? sceneId);
@ -7560,9 +7560,9 @@ public sealed class DynamicsService(IProjectRepository projects, IDynamicsReposi
};
}
public async Task<RelationshipEvolutionViewModel?> GetRelationshipEvolutionAsync(int characterRelationshipId)
public async Task<RelationshipEvolutionViewModel?> GetRelationshipEvolutionAsync(int characterRelationshipId,int page=1)
{
var data = await dynamics.GetRelationshipEvolutionAsync(characterRelationshipId);
var data = await dynamics.GetRelationshipEvolutionAsync(characterRelationshipId,page);
if (data.Relationship is null)
{
return null;

View File

@ -0,0 +1,28 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL,@Category nvarchar(100)=NULL,@OtherCharacterID int=NULL,@DefinitionPage int=1
AS
BEGIN
SET NOCOUNT ON;
DECLARE @project int=(SELECT c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1));
IF @project IS NULL THROW 51020,'Character unavailable',1;
IF @DefinitionPage<1 OR @DefinitionPage>100000 OR @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1;
DECLARE @pattern nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%';
SELECT r.CharacterRelationshipID,other.CharacterID OtherID,other.CharacterName OtherName,t.TypeName INTO #IDs
FROM dbo.CharacterRelationships r JOIN dbo.Characters other ON other.CharacterID=CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID
WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID) AND (@OtherCharacterID IS NULL OR other.CharacterID=@OtherCharacterID)
AND (@Category IS NULL OR @Category=N'' OR (@Category=N'family' AND cat.CategoryName=N'Family') OR (@Category=N'story' AND COALESCE(cat.CategoryName,N'')<>N'Family'))
AND (NULLIF(@Search,N'') IS NULL OR CONCAT(other.CharacterName,N' ',t.TypeName,N' ',r.Notes) LIKE @pattern ESCAPE N'~');
SELECT OtherID,OtherName,COUNT(*) DefinitionCount,ROW_NUMBER() OVER(ORDER BY OtherName COLLATE Latin1_General_100_CI_AS,OtherID) GroupNumber INTO #Groups FROM #IDs GROUP BY OtherID,OtherName;
SELECT COUNT(*) Total FROM #Groups;
SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@project AND IsArchived=0;
SELECT TOP(20001) ch.ChapterID,ch.BookID,ch.ChapterNumber,ch.SortOrder FROM dbo.Chapters ch JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0;
SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0;
;WITH Ranked AS(SELECT i.*,ROW_NUMBER() OVER(PARTITION BY i.OtherID ORDER BY i.TypeName COLLATE Latin1_General_100_CI_AS,i.CharacterRelationshipID) DefinitionNumber FROM #IDs i)
SELECT r.*,g.DefinitionCount WorkspaceDefinitionCount,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName
FROM Ranked x JOIN #Groups g ON g.OtherID=x.OtherID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=x.CharacterRelationshipID 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 st ON st.RelationshipStateID=r.InitialRelationshipStateID
WHERE g.GroupNumber BETWEEN ((@Page-1)*25)+1 AND @Page*25 AND x.DefinitionNumber BETWEEN ((@DefinitionPage-1)*25)+1 AND @DefinitionPage*25
ORDER BY g.GroupNumber,x.DefinitionNumber;
END;
GO

View File

@ -0,0 +1,62 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_ChangeRelationship @CharacterID int,@UserID int,@RelationshipID int,@Version varchar(64),@Action nvarchar(24),@Confirmed bit=0,@EventID int=NULL,@Notes nvarchar(4000)=NULL,@StateID int=NULL,@Intensity int=NULL,@Awareness bit=0,@TypeID int=NULL,@ReverseDirection bit=0,@Reciprocal bit=NULL,@Permanent bit=NULL,@ReaderKnows bit=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @project int,@allowed bit=0;
SELECT @project=c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p WITH(HOLDLOCK) ON p.ProjectID=c.ProjectID JOIN dbo.ProjectUserAccess a WITH(HOLDLOCK) ON a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0;
IF @project IS NULL THROW 51020,'Editing unavailable',1;
DECLARE @current varchar(64);
SELECT @current=CONVERT(varchar(64),HASHBYTES('SHA2_256',CONCAT((SELECT r.* FOR JSON PATH,WITHOUT_ARRAY_WRAPPER),(SELECT e.RelationshipEventID,e.UpdatedDate,e.SceneID,e.RelationshipStateID,e.Description FROM dbo.RelationshipEvents e WITH(UPDLOCK,HOLDLOCK) WHERE e.CharacterRelationshipID=r.CharacterRelationshipID ORDER BY e.RelationshipEventID FOR JSON PATH))),2)
FROM dbo.CharacterRelationships r WITH(UPDLOCK,HOLDLOCK) WHERE r.CharacterRelationshipID=@RelationshipID AND r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID);
IF @current IS NULL THROW 51020,'Relationship unavailable',1;
IF @Version IS NULL OR @current<>@Version THROW 51021,'This relationship or its history changed. Cancel and reopen to review current values.',1;
IF @Action=N'archive'
BEGIN
IF @Confirmed<>1 THROW 51022,'Confirm removal of this underlying relationship.',1;
EXEC dbo.Relationship_Archive @CharacterRelationshipID=@RelationshipID;
END
ELSE IF @Action=N'definition'
BEGIN
IF @Intensity IS NOT NULL AND @Intensity NOT BETWEEN 1 AND 10 THROW 51022,'Intensity must be 1 to 10.',1;
IF @StateID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipStates WHERE RelationshipStateID=@StateID) THROW 51022,'Choose a recorded state',1;
DECLARE @a int,@b int,@type int,@savedPermanent bit,@start int,@end int,@known bit,@initial bit,@book int,@reader bit,@state int,@strength int,@savedReciprocal bit;
SELECT @a=CharacterAID,@b=CharacterBID,@type=RelationshipTypeID,@savedPermanent=IsPermanent,@start=StartSceneID,@end=EndSceneID,@known=IsKnownToReader,@initial=IsInitialRelationship,@book=InitialBookID,@reader=ReaderInitiallyKnows,@state=InitialRelationshipStateID,@strength=InitialIntensity,@savedReciprocal=IsReciprocal FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@RelationshipID;
DECLARE @oldCategory int=(SELECT RelationshipCategoryID FROM dbo.RelationshipTypes WHERE RelationshipTypeID=@type),@newCategory int,@categoryName nvarchar(100);
SET @TypeID=COALESCE(@TypeID,@type);SET @Reciprocal=COALESCE(@Reciprocal,@savedReciprocal);
SELECT @newCategory=t.RelationshipCategoryID,@categoryName=c.CategoryName FROM dbo.RelationshipTypes t JOIN dbo.RelationshipCategories c ON c.RelationshipCategoryID=t.RelationshipCategoryID WHERE t.RelationshipTypeID=@TypeID AND (t.IsActive=1 OR t.RelationshipTypeID=@type);
IF @newCategory IS NULL THROW 51022,'Choose a supported canonical relationship type.',1;
IF @newCategory<>@oldCategory THROW 51022,'Changing category requires the full Relationships Editor; no history or family semantics were changed.',1;
IF (@TypeID<>@type OR @ReverseDirection=1 OR @Reciprocal<>@savedReciprocal) AND EXISTS(SELECT 1 FROM dbo.RelationshipEvents WITH(UPDLOCK,HOLDLOCK) WHERE CharacterRelationshipID=@RelationshipID) THROW 51022,'This definition has recorded history. Use the full Relationships Editor for structural changes; notes and initial properties remain editable here.',1;
IF @categoryName=N'Family' AND @Reciprocal<>@savedReciprocal THROW 51022,'Family reciprocity is structural. Use the full Relationships Editor to review the exact family semantics.',1;
SET @type=@TypeID;SET @savedReciprocal=@Reciprocal;SET @savedPermanent=COALESCE(@Permanent,@savedPermanent);SET @known=COALESCE(@ReaderKnows,@known);
IF @ReverseDirection=1 BEGIN DECLARE @swap int=@a;SET @a=@b;SET @b=@swap;END;
IF @initial=1 BEGIN SET @state=@StateID;SET @strength=@Intensity;SET @reader=@Awareness;END;
EXEC dbo.Relationship_Save @CharacterRelationshipID=@RelationshipID,@ProjectID=@project,@CharacterAID=@a,@CharacterBID=@b,@RelationshipTypeID=@type,@IsPermanent=@savedPermanent,@StartSceneID=@start,@EndSceneID=@end,@IsKnownToReader=@known,@Notes=@Notes,@IsInitialRelationship=@initial,@InitialBookID=@book,@ReaderInitiallyKnows=@reader,@InitialRelationshipStateID=@state,@InitialIntensity=@strength,@IsReciprocal=@savedReciprocal;
END
ELSE IF @Action IN(N'event-edit',N'event-remove')
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents WITH(UPDLOCK,HOLDLOCK) WHERE RelationshipEventID=@EventID AND CharacterRelationshipID=@RelationshipID) THROW 51020,'Event unavailable',1;
IF EXISTS(SELECT 1 FROM dbo.RelationshipEvents WHERE RelationshipEventID=@EventID AND SourceReviewKey IS NOT NULL) OR EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex WITH(UPDLOCK,HOLDLOCK) WHERE EventKind=N'Relationship' AND EventID=@EventID) OR EXISTS(SELECT 1 FROM dbo.CharacterKnowledge WITH(UPDLOCK,HOLDLOCK) WHERE SourceEventID=@EventID) THROW 51022,'This event has source/review dependencies. Use its source or review workflow; no history was deleted.',1;
IF @Action=N'event-remove'
BEGIN
IF @Confirmed<>1 THROW 51022,'Confirm removal of this one event.',1;
EXEC dbo.RelationshipEvent_Delete @RelationshipEventID=@EventID;
END
ELSE
BEGIN
IF @StateID IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.RelationshipStates WHERE RelationshipStateID=@StateID) THROW 51022,'Choose a recorded state.',1;
IF @Intensity IS NOT NULL AND @Intensity NOT BETWEEN 1 AND 10 THROW 51022,'Intensity must be 1 to 10.',1;
DECLARE @scene int=(SELECT SceneID FROM dbo.RelationshipEvents WHERE RelationshipEventID=@EventID);
EXEC dbo.RelationshipEvent_Save @RelationshipEventID=@EventID,@CharacterRelationshipID=@RelationshipID,@SceneID=@scene,@RelationshipStateID=@StateID,@Intensity=@Intensity,@IsKnownToOtherCharacter=@Awareness,@Description=@Notes;
END;
END
ELSE THROW 51022,'Unsupported operation.',1;
COMMIT;
END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -0,0 +1,37 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.Dynamics_RelationshipEvolution
@CharacterRelationshipID int,@Page int=1
AS
BEGIN
SET NOCOUNT ON;
IF @Page<1 OR @Page>100000 THROW 51022,'Invalid history page',1;
DECLARE @project int=(SELECT ProjectID FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@CharacterRelationshipID);
SELECT cr.CharacterRelationshipID, cr.ProjectID, cr.CharacterAID, ca.CharacterName AS CharacterAName,
cr.CharacterBID, cb.CharacterName AS CharacterBName, cr.RelationshipTypeID, rt.TypeName AS RelationshipTypeName,
cr.IsReciprocal,cr.IsInitialRelationship,cr.InitialRelationshipStateID,cr.InitialIntensity,cr.ReaderInitiallyKnows,cr.InitialBookID,cr.IsPermanent, cr.StartSceneID, cr.EndSceneID, cr.IsKnownToReader, cr.Notes, cr.CreatedDate, cr.UpdatedDate, cr.IsArchived
FROM dbo.CharacterRelationships cr
INNER JOIN dbo.Characters ca ON ca.CharacterID = cr.CharacterAID
INNER JOIN dbo.Characters cb ON cb.CharacterID = cr.CharacterBID
INNER JOIN dbo.RelationshipTypes rt ON rt.RelationshipTypeID = cr.RelationshipTypeID
WHERE cr.CharacterRelationshipID = @CharacterRelationshipID;
SELECT re.RelationshipEventID, re.CharacterRelationshipID, re.SceneID, nso.BookTitle, nso.BookSubtitle, nso.ChapterNumber, nso.SceneNumber,
nso.SceneTitle, CAST(nso.Ordinal+1 AS int) GlobalSceneIndex,COUNT(*) OVER() TotalRecords, rs.StateName AS RelationshipStateName, re.Intensity, re.IsKnownToOtherCharacter,re.Description,COALESCE(ev.EvidenceState,N'Verified') EvidenceState,re.SourceReviewKey
FROM dbo.RelationshipEvents re
INNER JOIN dbo.RelationshipStates rs ON rs.RelationshipStateID = re.RelationshipStateID
INNER JOIN dbo.CharacterWorkspace_SceneOrder(@project) nso ON nso.SceneID = re.SceneID
OUTER APPLY(SELECT TOP(1) m.EvidenceState FROM dbo.ManuscriptEvidenceIndex m WHERE m.EventKind=N'Relationship' AND m.EventID=re.RelationshipEventID AND m.IsPrimary=1 ORDER BY CASE WHEN m.EvidenceState=N'Verified' THEN 1 ELSE 0 END,m.EvidenceID) ev
WHERE re.CharacterRelationshipID = @CharacterRelationshipID
ORDER BY nso.Ordinal,re.RelationshipEventID OFFSET ((@Page-1)*25) ROWS FETCH NEXT 25 ROWS ONLY;
SELECT N'Relationship Continuity' AS Category, ws.SeverityName, cw.Message AS Title, cw.Details AS Detail, cw.SceneID, cw.EntityID, cw.EntityType
FROM dbo.ContinuityWarnings cw
INNER JOIN dbo.WarningSeverities ws ON ws.WarningSeverityID = cw.WarningSeverityID
INNER JOIN dbo.WarningTypes wt ON wt.WarningTypeID = cw.WarningTypeID
WHERE cw.IsDismissed = 0 AND cw.EntityType = N'Relationship' AND cw.EntityID = @CharacterRelationshipID
AND wt.TypeName = N'Abrupt Relationship Change';
END;
GO

View File

@ -0,0 +1,29 @@
-- At most 25 groups × 3 definitions; focused groups page all definitions in batches of 25.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL,@Category nvarchar(100)=NULL,@OtherCharacterID int=NULL,@DefinitionPage int=1
AS
BEGIN
SET NOCOUNT ON;
DECLARE @project int=(SELECT c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1));
IF @project IS NULL THROW 51020,'Character unavailable',1;
IF @DefinitionPage<1 OR @DefinitionPage>100000 OR @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1;
DECLARE @pattern nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%';
SELECT r.CharacterRelationshipID,other.CharacterID OtherID,other.CharacterName OtherName,t.TypeName INTO #IDs
FROM dbo.CharacterRelationships r JOIN dbo.Characters other ON other.CharacterID=CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID
WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID) AND (@OtherCharacterID IS NULL OR other.CharacterID=@OtherCharacterID)
AND (@Category IS NULL OR @Category=N'' OR (@Category=N'family' AND cat.CategoryName=N'Family') OR (@Category=N'story' AND COALESCE(cat.CategoryName,N'')<>N'Family'))
AND (NULLIF(@Search,N'') IS NULL OR CONCAT(other.CharacterName,N' ',t.TypeName,N' ',r.Notes) LIKE @pattern ESCAPE N'~');
SELECT OtherID,OtherName,COUNT(*) DefinitionCount,ROW_NUMBER() OVER(ORDER BY OtherName COLLATE Latin1_General_100_CI_AS,OtherID) GroupNumber INTO #Groups FROM #IDs GROUP BY OtherID,OtherName;
SELECT COUNT(*) Total FROM #Groups;
SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@project AND IsArchived=0;
SELECT TOP(20001) ch.ChapterID,ch.BookID,ch.ChapterNumber,ch.SortOrder FROM dbo.Chapters ch JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0;
SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0;
;WITH Ranked AS(SELECT i.*,ROW_NUMBER() OVER(PARTITION BY i.OtherID ORDER BY i.TypeName COLLATE Latin1_General_100_CI_AS,i.CharacterRelationshipID) DefinitionNumber FROM #IDs i)
SELECT r.*,g.DefinitionCount WorkspaceDefinitionCount,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName
FROM Ranked x JOIN #Groups g ON g.OtherID=x.OtherID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=x.CharacterRelationshipID 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 st ON st.RelationshipStateID=r.InitialRelationshipStateID
WHERE g.GroupNumber BETWEEN ((@Page-1)*25)+1 AND @Page*25 AND x.DefinitionNumber BETWEEN CASE WHEN @OtherCharacterID IS NULL THEN 1 ELSE ((@DefinitionPage-1)*25)+1 END AND CASE WHEN @OtherCharacterID IS NULL THEN 3 ELSE @DefinitionPage*25 END
ORDER BY g.GroupNumber,x.DefinitionNumber;
END;
GO

View File

@ -0,0 +1,30 @@
-- Mirrors the existing canonical family predicate in ContextFamily_Structure / ContextRelationshipLenses.Family.
-- At most 25 groups × 3 definitions; focused groups page all definitions in batches of 25.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL,@Category nvarchar(100)=NULL,@OtherCharacterID int=NULL,@DefinitionPage int=1
AS
BEGIN
SET NOCOUNT ON;
DECLARE @project int=(SELECT c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1));
IF @project IS NULL THROW 51020,'Character unavailable',1;
IF @DefinitionPage<1 OR @DefinitionPage>100000 OR @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1;
DECLARE @pattern nvarchar(500)=N'%'+REPLACE(REPLACE(REPLACE(REPLACE(@Search,N'~',N'~~'),N'%',N'~%'),N'_',N'~_'),N'[',N'~[')+N'%';
SELECT r.CharacterRelationshipID,other.CharacterID OtherID,other.CharacterName OtherName,t.TypeName INTO #IDs
FROM dbo.CharacterRelationships r JOIN dbo.Characters other ON other.CharacterID=CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END JOIN dbo.RelationshipTypes t ON t.RelationshipTypeID=r.RelationshipTypeID LEFT JOIN dbo.RelationshipCategories cat ON cat.RelationshipCategoryID=t.RelationshipCategoryID
WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID) AND (@OtherCharacterID IS NULL OR other.CharacterID=@OtherCharacterID)
AND (@Category IS NULL OR @Category=N'' OR (@Category=N'family' 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')))) OR (@Category=N'story' AND NOT(cat.CategoryName=N'Family' OR (cat.CategoryName=N'Romantic / Sexual' AND t.TypeName IN(N'Spouse',N'Partner',N'Ex-spouse',N'Former spouse',N'Romantic Partner')))))
AND (NULLIF(@Search,N'') IS NULL OR CONCAT(other.CharacterName,N' ',t.TypeName,N' ',r.Notes) LIKE @pattern ESCAPE N'~');
SELECT OtherID,OtherName,COUNT(*) DefinitionCount,ROW_NUMBER() OVER(ORDER BY OtherName COLLATE Latin1_General_100_CI_AS,OtherID) GroupNumber INTO #Groups FROM #IDs GROUP BY OtherID,OtherName;
SELECT COUNT(*) Total FROM #Groups;
SELECT TOP(20001) BookID,BookNumber,SortOrder FROM dbo.Books WHERE ProjectID=@project AND IsArchived=0;
SELECT TOP(20001) ch.ChapterID,ch.BookID,ch.ChapterNumber,ch.SortOrder FROM dbo.Chapters ch JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0;
SELECT TOP(20001) s.SceneID,s.ChapterID,s.SceneNumber,s.SortOrder FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@project AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0;
;WITH Ranked AS(SELECT i.*,ROW_NUMBER() OVER(PARTITION BY i.OtherID ORDER BY i.TypeName COLLATE Latin1_General_100_CI_AS,i.CharacterRelationshipID) DefinitionNumber FROM #IDs i)
SELECT r.*,g.DefinitionCount WorkspaceDefinitionCount,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName
FROM Ranked x JOIN #Groups g ON g.OtherID=x.OtherID JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=x.CharacterRelationshipID 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 st ON st.RelationshipStateID=r.InitialRelationshipStateID
WHERE g.GroupNumber BETWEEN ((@Page-1)*25)+1 AND @Page*25 AND x.DefinitionNumber BETWEEN CASE WHEN @OtherCharacterID IS NULL THEN 1 ELSE ((@DefinitionPage-1)*25)+1 END AND CASE WHEN @OtherCharacterID IS NULL THEN 3 ELSE @DefinitionPage*25 END
ORDER BY g.GroupNumber,x.DefinitionNumber;
END;
GO

View File

@ -8,7 +8,7 @@ public sealed class CharacterWorkspaceCounts
}
public sealed class CharacterWorkspaceQuery
{
public string Tab{get;set;}="overview";public int Page{get;set;}=1;[StringLength(120)]public string? Search{get;set;}public int? BookID{get;set;}public string? Category{get;set;}public int? SceneID{get;set;}public int? RelationshipID{get;set;}
public string Tab{get;set;}="overview";public int Page{get;set;}=1;[StringLength(120)]public string? Search{get;set;}public int? BookID{get;set;}public string? Category{get;set;}public int? SceneID{get;set;}public int? RelationshipID{get;set;}public int? OtherCharacterID{get;set;}public int DefinitionPage{get;set;}=1;
}
public sealed class CharacterWorkspaceEntry
{
@ -26,6 +26,7 @@ public sealed class CharacterRelationshipFrame
public sealed class CharacterWorkspaceEvent {public RelationshipEvent Record{get;set;}=new();public bool ProtectedSource{get;set;}}
public sealed class CharacterWorkspaceOperation
{
public int? TypeID{get;set;}public bool ReverseDirection{get;set;}public bool? Reciprocal{get;set;}public bool? Permanent{get;set;}public bool? ReaderKnows{get;set;}public IReadOnlyList<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> Types{get;set;}=[];
public int CharacterID{get;set;}public int RelationshipID{get;set;}public int? EventID{get;set;}public string Action{get;set;}="definition";[Required,StringLength(64)]public string Version{get;set;}="";[StringLength(4000)]public string? Notes{get;set;}public int? StateID{get;set;}[Range(1,10)]public int? Intensity{get;set;}public bool Awareness{get;set;}public bool Confirmed{get;set;}
public CharacterRelationshipFrame Record{get;set;}=new();public CharacterWorkspaceEvent? Event{get;set;}public IReadOnlyList<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> States{get;set;}=[];
}

View File

@ -1170,6 +1170,7 @@ public sealed class CharacterArcViewModel
public sealed class RelationshipEvolutionViewModel
{
public int Page{get;set;}=1;public int Total=>Events.FirstOrDefault()?.TotalRecords??0;public int ReturnCharacterID{get;set;}public int? ReturnSceneID{get;set;}public bool CanEdit{get;set;}
public Project Project { get; set; } = new();
public CharacterRelationship Relationship { get; set; } = new();
public IReadOnlyList<RelationshipProgressionPoint> Events { get; set; } = [];

View File

@ -1,18 +1,12 @@
@model CharacterDetailViewModel
@{ViewData["DesktopLayout"]="details";ViewData["Title"]=Model.Character.CharacterName;ViewData["ProjectSection"]="Characters";var c=Model.Character;var analysis=Model.CharacterAnalysis;}
@{ViewData["DesktopLayout"]="details";ViewData["Title"]=Model.Character.CharacterName;ViewData["ProjectSection"]="Characters";var c=Model.Character;var analysis=Model.CharacterAnalysis;ViewData["CharacterRibbonModel"]=Model;}
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb"><a asp-controller="Projects" asp-action="Index">Projects</a><a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a><a asp-action="Index" asp-route-projectId="@c.ProjectID">Characters</a><span>@c.CharacterName</span></nav>
<partial name="_ProjectSectionNav" model="Model.Project" />
<div data-character-workspace data-character-id="@c.CharacterID" data-project-id="@c.ProjectID" data-user-id="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value" data-initial-tab="@Model.WorkspaceTab" data-can-edit="@Model.WorkspaceCanEdit.ToString().ToLowerInvariant()">
<header class="character-workspace-header" data-pd-context="character" data-pd-context-id="@c.CharacterID" data-pd-context-label="@c.CharacterName" data-pwa-help data-character-analysis-panel data-character-id="@c.CharacterID" data-book-id="@analysis.BookID" data-analysis-run-id="@analysis.CharacterEnrichmentRunID" data-analysis-status="@analysis.Status">
<partial name="_Avatar" model="@(new AvatarViewModel{DisplayName=c.CharacterName,ImagePath=c.AvatarImagePath??c.ImagePath,ThumbnailPath=c.AvatarThumbnailPath??c.ThumbnailPath,Size="lg",Lazy=false})" />
<div class="character-workspace-identity"><p class="eyebrow">@Model.Project.ProjectName · Character</p><h1>@c.CharacterName <help-icon key="characters.details"/></h1><span class="status-pill">@CharacterWorkspace.Classification(c.CharacterImportance)</span><span class="small" data-character-analysis-status>@(analysis.Status??"Not analysed")</span><span class="small" data-character-analysis-message>@analysis.CurrentMessage</span></div>
<div class="button-row"><a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@c.ProjectID">Characters</a><a class="btn btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@c.ProjectID" asp-route-SelectedSceneID="@Model.WorkspaceCounts.FirstSceneID" asp-route-FocusType="character" asp-route-FocusID="@c.CharacterID">Timeline</a>
@if(Model.WorkspaceCanEdit){<a class="btn btn-primary" asp-action="Edit" asp-route-id="@c.CharacterID">Edit character</a>}
<div class="dropdown"><button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Actions</button><div class="dropdown-menu dropdown-menu-end">
@if(Model.WorkspaceCanEdit){<a class="dropdown-item" asp-action="Merge" asp-route-id="@c.CharacterID">Merge with another character</a><form asp-action="Reanalyse" method="post" data-character-reanalyse-form><input type="hidden" name="id" value="@c.CharacterID"/><button class="dropdown-item" data-character-reanalyse-button disabled="@(analysis.Status is CharacterEnrichmentStatuses.Queued or CharacterEnrichmentStatuses.Running)">Reanalyse character</button></form>}
<a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@c.CharacterID">Export character</a><a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@c.CharacterID" asp-route-format="markdown">Markdown</a>
@if(Model.WorkspaceCanEdit){<form asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this character? Its data will be retained for restoration."><input type="hidden" name="id" value="@c.CharacterID"/><input type="hidden" name="projectId" value="@c.ProjectID"/><button class="dropdown-item text-danger">Archive character</button></form>}
</div></div></div>
</header>
<div class="character-workspace-switch"><label>Find another character<input type="search" class="form-control" data-character-switch maxlength="120" placeholder="Name or alias"/></label><div data-character-matches></div></div>
<nav class="character-workspace-tabs" role="tablist" aria-label="Character workspace">@foreach(var tab in CharacterWorkspace.Tabs){<a role="tab" id="character-tab-@tab" aria-controls="character-workspace-panel" aria-selected="@(Model.WorkspaceTab==tab?"true":"false")" data-character-tab="@tab" href="@Url.Action("Details",new{id=c.CharacterID,tab})">@(tab=="overview"?"Overview":tab=="relationships"?"Relationships":tab=="evolution"?"Evolution":tab=="appearances"?"Appearances":"Knowledge")</a>}</nav>

View File

@ -1,7 +1,7 @@
@model CharacterWorkspaceOperation
@{var r=Model.Record.Relationship;var destructive=Model.Action is "archive" or "event-remove";var linked=Model.Action.StartsWith("event-")&&Model.Event?.ProtectedSource==true;}
<form method="post" asp-controller="CharacterWorkspace" asp-action="Operation" asp-route-id="@Model.CharacterID" data-workspace-operation-form data-confirm-skip="true">
<h2 id="character-operation-title">@(Model.Action=="archive"?"Remove relationship":Model.Action=="event-remove"?"Remove one relationship event":Model.Action=="definition"?"Edit relationship definition":"Edit one relationship event")</h2>
<h2 id="character-operation-title">@(Model.Action=="archive"?"Remove relationship":Model.Action=="event-remove"?"Remove one relationship event":Model.Action=="definition"?"Edit relationship":"Edit one relationship event")</h2>
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
<input asp-for="CharacterID" type="hidden"/><input asp-for="RelationshipID" type="hidden"/><input asp-for="EventID" type="hidden"/><input asp-for="Action" type="hidden"/><input asp-for="Version" type="hidden"/>
<p><strong>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName</strong> · @r.RelationshipTypeName · @r.RelationshipCategoryName</p>
@ -12,7 +12,16 @@
}
@if(linked){<p class="alert alert-warning">This event has manuscript evidence, review provenance or source dependencies. Direct modification/removal is blocked so that evidence is not orphaned. Use its source/review workflow.</p><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@Model.Event?.Record.SceneID">Open source scene</a>}
else if(!destructive){
<p class="small">@(Model.Action=="definition"?"The pair, type, direction, book and narrative start/end remain unchanged. Use the full Relationships Editor for structural changes.":"This changes one recorded development at its original scene, not the definition or other events.")</p>
<p class="small">@(Model.Action=="definition"?"Category is derived from the selected canonical type. Book, narrative start/end and initial/scene-established status remain unchanged. Structural changes with recorded history or across categories require the full Relationships Editor.":"This changes one recorded development at its original scene, not the definition or other events.")</p>
@if(Model.Action=="definition"){
<label asp-for="TypeID">Relationship type (category · type)</label><select asp-for="TypeID" asp-items="Model.Types" class="form-select" disabled="@(Model.Record.EventCount>0)"></select>
<p class="small">@Model.Record.EventCount recorded event(s) will be retained. Type/direction changes are available here only without events and within the existing category. Independent definitions are unchanged.</p>
<label class="character-checkbox"><input asp-for="ReverseDirection" disabled="@(Model.Record.EventCount>0)"/> Reverse the displayed direction: @r.CharacterBName → @r.CharacterAName</label>
<label>Representation<select asp-for="Reciprocal" class="form-select" disabled="@(Model.Record.EventCount>0||r.RelationshipCategoryName=="Family")"><option value="false">Directional: A → B</option><option value="true">Reciprocal: one A ↔ B record</option></select></label><p class="small">Family-category reciprocity changes require the full editor to review family semantics.</p>
<label>Persistence<select asp-for="Permanent" class="form-select"><option value="true">Permanent relationship</option><option value="false">Not permanent</option></select></label>
<label>Reader awareness<select asp-for="ReaderKnows" class="form-select"><option value="true">Known to reader</option><option value="false">Not recorded as known</option></select></label>
<a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@r.ProjectID" asp-route-focusCharacterId="@Model.CharacterID" asp-route-relationshipId="@r.CharacterRelationshipID">Full Relationships Editor for this pair</a>
}
@if(Model.Action!="definition"||r.IsInitialRelationship){<label asp-for="StateID">@(Model.Action=="definition"?"Initial state":"Recorded event state")</label><select asp-for="StateID" asp-items="Model.States" class="form-select"><option value="">Not recorded</option></select><label asp-for="Intensity">Intensity (1–10)</label><input asp-for="Intensity" type="number" min="1" max="10" class="form-control"/><label class="character-checkbox"><input asp-for="Awareness"/> @(Model.Action=="definition"?"Reader initially knows":"Known to the other character at this event")</label>}
<label asp-for="Notes">@(Model.Action=="definition"?"Definition notes":"Event description")</label><textarea asp-for="Notes" rows="7" maxlength="4000" class="form-control"></textarea>
}

View File

@ -20,6 +20,7 @@ Model.Profile.Images=Model.Images;<partial name="/Views/Characters/_WorkspaceGal
<form data-workspace-filter class="character-workspace-filters" action="@Url.Action("Tab","CharacterWorkspace",new{id=c.CharacterID})" method="get">
<input type="hidden" name="Tab" value="@q.Tab"/><input type="hidden" name="SceneID" value="@q.SceneID"/><input type="hidden" name="RelationshipID" value="@q.RelationshipID"/>
<label>Search<input class="form-control" name="Search" value="@q.Search" maxlength="120" placeholder="Recorded names, values or notes"/></label>
@if(q.Tab=="relationships"){<label>Recorded category<select name="Category" class="form-select"><option value="">Family and Story</option><option value="family" selected="@(q.Category=="family")">Family definitions</option><option value="story" selected="@(q.Category=="story")">Story definitions</option></select></label>@if(q.OtherCharacterID.HasValue){<button type="button" class="btn btn-outline-secondary" data-all-groups>All character groups</button>}}
@if(q.Tab!="relationships"){<label>Book<select class="form-select" name="BookID"><option value="">All books</option>@foreach(var book in Model.Books){<option value="@book.Value" selected="@(q.BookID?.ToString()==book.Value)">@book.Text</option>}</select></label>}
@if(q.Tab=="evolution"){<label>Category<select class="form-select" name="Category"><option value="">All recorded changes</option>@foreach(var category in new[]{"attributes","relationships","knowledge","appearances"}){<option value="@category" selected="@(q.Category==category)">@category</option>}</select></label>}
@if(q.Tab=="knowledge"){<label>Canonical state<input class="form-control" name="Category" value="@q.Category" placeholder="Exact recorded state, or blank" list="knowledge-states"/><datalist id="knowledge-states">@foreach(var state in Model.Entries.Select(e=>e.State).Where(s=>!string.IsNullOrEmpty(s)).Distinct()){<option value="@state"/>}</datalist></label>}
@ -30,13 +31,22 @@ Model.Profile.Images=Model.Images;<partial name="/Views/Characters/_WorkspaceGal
<div data-character-graph tabindex="0" role="group" aria-label="Character relationship diagram. Drag to pan; zoom with buttons. Arrow keys pan; plus and minus zoom."></div><div data-character-graph-selection class="small"></div><div class="character-graph-legend">Family: parent · biological · adoptive (dashed) · step (dotted) · partnership. Story: friendship (green), hostility (red), romance (purple), professional/social (blue).</div>
<p class="small">Only recorded connections are shown. A relationship does not establish a first meeting, mutual trust or viewpoint knowledge.</p>
<section data-character-relationship-records aria-label="Relationship records">
@foreach(var current in Model.Relationships){var r=current.Relationship;var other=r.CharacterAID==c.CharacterID?r.CharacterBID:r.CharacterAID;var name=r.CharacterAID==c.CharacterID?r.CharacterBName:r.CharacterAName;
<article class="character-record" data-workspace-relationship="@r.CharacterRelationshipID"><div><h3><a asp-controller="Characters" asp-action="Details" asp-route-id="@other" data-character-link>@name</a></h3><p>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · <strong>@r.RelationshipTypeName</strong> <span class="status-pill">@r.RelationshipCategoryName</span></p><p>@(q.SceneID.HasValue?"Selected-point state":"Latest recorded state"): @current.CurrentStateName @if(current.CurrentIntensity.HasValue&&current.LatestEvent?.RelationshipStateName!="Not established / ended at this point"){<span>· Intensity @current.CurrentIntensity</span>}</p><p class="character-long-text">@current.CurrentNotes</p><p class="small">@(r.IsInitialRelationship?"Initial author definition":"Scene-established definition") · @(r.IsReciprocal?"One reciprocal record covers both directions":"Directional record")</p></div>
<div class="button-row"><button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-select-relationship="@r.CharacterRelationshipID">Inspect connection</button><button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-history="@r.CharacterRelationshipID">History</button>
@if(Model.Profile.WorkspaceCanEdit){<button class="btn btn-outline-primary btn-sm" type="button" data-workspace-operation="definition" data-relationship="@r.CharacterRelationshipID">Edit definition</button><button class="btn btn-outline-danger btn-sm" type="button" data-workspace-operation="archive" data-relationship="@r.CharacterRelationshipID">Remove relationship</button>}
<a class="small" asp-controller="Dynamics" asp-action="Relationship" asp-route-id="@r.CharacterRelationshipID">Advanced evolution</a><a class="small" asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@c.ProjectID" asp-route-focusCharacterId="@c.CharacterID">Full Relationships Editor</a></div></article>}
@foreach(var group in Model.Relationships.GroupBy(x=>x.Relationship.CharacterAID==c.CharacterID?x.Relationship.CharacterBID:x.Relationship.CharacterAID)){
var first=group.First();var other=group.Key;var name=first.Relationship.CharacterAID==c.CharacterID?first.Relationship.CharacterBName:first.Relationship.CharacterAName;var count=first.Relationship.WorkspaceDefinitionCount;
<details class="character-relationship-group plain-card" data-relationship-group="@other" open="@(q.OtherCharacterID==other)"><summary><strong>@name</strong> @if(count>1){<span class="status-pill">@count definitions</span>}<span>@string.Join(" · ",group.Select(x=>x.Relationship.RelationshipTypeName).Distinct().Take(3))</span><span class="small">@string.Join(" · ",group.Select(x=>x.CurrentStateName).Distinct().Take(2))</span></summary>
<div class="character-group-definitions"><a asp-controller="Characters" asp-action="Details" asp-route-id="@other" data-character-link>Open @name</a>
@foreach(var current in group){var r=current.Relationship;
<article class="character-record" tabindex="0" aria-label="Select definition @r.CharacterRelationshipID: @r.RelationshipTypeName" data-workspace-relationship="@r.CharacterRelationshipID"><p><strong>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · @r.RelationshipTypeName</strong> <span class="status-pill">@r.RelationshipCategoryName</span></p><p>@(q.SceneID.HasValue?"Selected-point state":"Latest recorded state"): @current.CurrentStateName @if(current.CurrentIntensity.HasValue&&current.LatestEvent?.RelationshipStateName!="Not established / ended at this point"){<span>· Intensity @current.CurrentIntensity</span>}</p><p class="character-long-text">@current.CurrentNotes</p><p class="small">Definition #@r.CharacterRelationshipID · @(r.IsInitialRelationship?"Initial author definition":"Scene-established definition") · @(r.IsReciprocal?"One reciprocal record covers both directions":"Independent directional record")</p>
@if(r.StartSceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@r.StartSceneID">Start scene #@r.StartSceneID</a>}@if(r.EndSceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@r.EndSceneID">End scene #@r.EndSceneID</a>}
<div class="button-row">@if(Model.Profile.WorkspaceCanEdit){<button class="btn btn-outline-primary btn-sm" type="button" data-workspace-operation="definition" data-relationship="@r.CharacterRelationshipID">Edit</button>}
<a class="btn btn-outline-secondary btn-sm" asp-controller="Dynamics" asp-action="Relationship" asp-route-id="@r.CharacterRelationshipID" asp-route-returnCharacterId="@c.CharacterID" asp-route-returnSceneId="@q.SceneID">History</a>
@if(Model.Profile.WorkspaceCanEdit){<button class="btn btn-outline-danger btn-sm" type="button" data-workspace-operation="archive" data-relationship="@r.CharacterRelationshipID">Remove</button>}</div></article>}
@if(!q.OtherCharacterID.HasValue&&count>3){<button type="button" class="btn btn-outline-secondary" data-group-page="1" data-other-character="@other">View all @count definitions for @name</button>}
@if(q.OtherCharacterID.HasValue&&count>25){<p>Showing definitions @((q.DefinitionPage-1)*25+1)–@Math.Min(q.DefinitionPage*25,count) of @count.</p><div class="button-row">@if(q.DefinitionPage>1){<button type="button" class="btn btn-outline-secondary" data-group-page="@(q.DefinitionPage-1)" data-other-character="@other">Previous definitions</button>}@if(q.DefinitionPage*25<count){<button type="button" class="btn btn-outline-secondary" data-group-page="@(q.DefinitionPage+1)" data-other-character="@other">More definitions for @name</button>}</div>}
</div></details>}
@if(!Model.Relationships.Any()){<p class="muted">No matching relationship definitions recorded. Add an initial relationship or use the scene editor for a scene-based development.</p>}
</section><div data-character-history></div>
</section><p class="small">Select a definition to highlight its diagram connection. <a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@c.ProjectID" asp-route-focusCharacterId="@c.CharacterID">Full Relationships Editor</a></p>
}else{
@if(!Model.Entries.Any()){<p class="muted">No matching records at this point. Change the filters or record information in its scene/source editor.</p>}
@foreach(var group in Model.Entries.GroupBy(e=>new{e.BookID,e.BookDisplayTitle,e.ChapterNumber,e.SceneID,e.SceneTitle,e.SceneNumber})){
@ -51,6 +61,6 @@ Model.Profile.Images=Model.Images;<partial name="/Views/Characters/_WorkspaceGal
</div></details></article>}
</section>}
}
<div class="character-workspace-pagination"><span>@Model.Total recorded results · page @q.Page of @totalPages</span>@if(q.Page>1){<button type="button" class="btn btn-outline-secondary" data-workspace-page="@(q.Page-1)">Previous</button>}@if(q.Page<totalPages){<button type="button" class="btn btn-outline-secondary" data-workspace-page="@(q.Page+1)">Next</button>}</div>
<div class="character-workspace-pagination"><span>@Model.Total @(q.Tab=="relationships"?"character groups":"recorded results") · page @q.Page of @totalPages</span>@if(q.Page>1){<button type="button" class="btn btn-outline-secondary" data-workspace-page="@(q.Page-1)">Previous</button>}@if(q.Page<totalPages){<button type="button" class="btn btn-outline-secondary" data-workspace-page="@(q.Page+1)">Next</button>}</div>
}
</div>

View File

@ -1,53 +1,22 @@
@model RelationshipEvolutionViewModel
@{
ViewData["DesktopLayout"] = "details";
ViewData["Title"] = "Relationship Evolution";
var maxIndex = Math.Max(Model.Events.Any() ? Model.Events.Max(x => x.GlobalSceneIndex) : 1, 1);
}
<div data-pwa-task class="page-heading">
<div>
<p class="eyebrow">Relationship Evolution</p>
<h1>@Model.Relationship.CharacterAName -> @Model.Relationship.CharacterBName</h1>
<p class="lead-text">@Model.Relationship.RelationshipTypeName</p>
</div>
<a class="btn btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-FocusType="relationship" asp-route-FocusID="@Model.Relationship.CharacterRelationshipID">Show on timeline</a>
@{ViewData["DesktopLayout"]="details";ViewData["Title"]="Relationship Evolution";var r=Model.Relationship;var pages=Math.Max(1,(Model.Total+24)/25);var points=Model.Events.Where(e=>e.Intensity.HasValue&&e.EvidenceState=="Verified").ToArray();var min=Model.Events.Select(e=>e.GlobalSceneIndex).DefaultIfEmpty(0).Min();var max=Model.Events.Select(e=>e.GlobalSceneIndex).DefaultIfEmpty(1).Max();}
<div data-relationship-history-content data-history-page="@Model.Page">
<div class="page-heading" data-relationship-evolution="@r.CharacterRelationshipID"><div><p class="eyebrow">Relationship Evolution · Definition #@r.CharacterRelationshipID</p><h1>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName</h1><p>@r.RelationshipTypeName · @(r.IsReciprocal?"One reciprocal definition":"Directional definition")</p></div><a class="btn btn-outline-secondary" asp-controller="Characters" asp-action="Details" asp-route-id="@Model.ReturnCharacterID" asp-route-tab="relationships" asp-route-sceneId="@Model.ReturnSceneID" asp-route-relationshipId="@r.CharacterRelationshipID">Return to character Relationships</a></div>
<p class="character-long-text">@r.Notes</p><p class="small">@(r.IsInitialRelationship?"Initial author definition":"Scene-established definition"). Events below remain distinct from the underlying definition. @Model.Total recorded event(s).</p>
@if(Model.Events.Count>1&&points.Length>1){
<section class="plain-card relationship-evolution-chart"><h2>Recorded intensity</h2><p class="small">Horizontal: canonical manuscript scene order (this page). Vertical: recorded intensity, 1–10. Each purple point is one verified event; missing values and intermediate states are not inferred. Select a point to inspect its event.</p>
<svg viewBox="0 0 800 210" role="group" aria-label="Recorded event intensities in canonical scene order">
@foreach(var level in new[]{1,5,10}){var y=170-(level-1)*16; <g><line x1="40" y1="@y" x2="770" y2="@y"/><text x="10" y="@(y+4)">@level</text></g>}
@foreach(var e in points){var x=50+(e.GlobalSceneIndex-min)*710m/Math.Max(1,max-min);var y=170-(e.Intensity!.Value-1)*16;<a href="#event-@e.RelationshipEventID" aria-label="Scene @e.SceneNumber, @e.RelationshipStateName, intensity @e.Intensity"><circle cx="@x.ToString(System.Globalization.CultureInfo.InvariantCulture)" cy="@y" r="6"><title>@e.BookDisplayTitle · Ch @e.ChapterNumber · Scene @e.SceneNumber · @e.RelationshipStateName · Intensity @e.Intensity</title></circle></a>}
<text x="40" y="202">First recorded scene on this page</text><text x="770" y="202" text-anchor="end">Last recorded scene on this page</text>
</svg></section>
}else if(Model.Total==0){<section class="plain-card"><h2>No recorded events</h2><p>This author definition has no scene-based developments. No timeline or intensity has been inferred. Use the scene editor to record a development.</p></section>}
else{<p class="plain-card">@(Model.Total==1?"One recorded event: its state and any recorded intensity are shown below.":"Recorded changes are shown chronologically below. This page has insufficient verified intensity values for a useful chart.")</p>}
@if(Model.Issues.Any()){<partial name="_DynamicsIssues" model="Model.Issues"/>}else{<p class="small">No recorded continuity warnings for this definition.</p>}
<section data-relationship-events><h2>Recorded history</h2>
@foreach(var e in Model.Events){<article class="plain-card character-record" id="event-@e.RelationshipEventID" data-evolution-event="@e.RelationshipEventID"><h3>@e.BookDisplayTitle · Ch @e.ChapterNumber · Scene @e.SceneNumber: @e.SceneTitle</h3><p><strong>@e.RelationshipStateName</strong> · Intensity @(e.Intensity?.ToString()??"not recorded") · @(e.IsKnownToOtherCharacter?"Known to the other character":"Not recorded as known to the other character")</p><p class="character-long-text">@e.Description</p><p class="small">@e.EvidenceState @(e.SourceReviewKey!=null?"· Accepted review source":"") · Event #@e.RelationshipEventID</p>@if(e.EvidenceState!="Verified"){<p class="text-warning">Source evidence needs review; this is not an established relationship development.</p>}
<div class="button-row"><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@e.SceneID">Open scene / source</a>@if(Model.CanEdit){<button type="button" class="btn btn-outline-primary btn-sm" data-history-operation="event-edit" data-event="@e.RelationshipEventID">Edit event</button><button type="button" class="btn btn-outline-danger btn-sm" data-history-operation="event-remove" data-event="@e.RelationshipEventID">Remove event</button>}</div></article>}
</section><div class="button-row">@if(Model.Page>1){<a class="btn btn-outline-secondary" asp-route-id="@r.CharacterRelationshipID" asp-route-page="@(Model.Page-1)" asp-route-returnCharacterId="@Model.ReturnCharacterID" asp-route-returnSceneId="@Model.ReturnSceneID">Previous events</a>}<span>Page @Model.Page of @pages · up to 25 events per page</span>@if(Model.Page<pages){<a class="btn btn-outline-secondary" asp-route-id="@r.CharacterRelationshipID" asp-route-page="@(Model.Page+1)" asp-route-returnCharacterId="@Model.ReturnCharacterID" asp-route-returnSceneId="@Model.ReturnSceneID">Next events</a>}<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-FocusType="relationship" asp-route-FocusID="@r.CharacterRelationshipID">Show on timeline</a></div>
</div>
<section class="story-bible-section">
<div class="dynamics-timeline relationship">
@foreach (var item in Model.Events)
{
var left = (item.GlobalSceneIndex - 1) * 100m / maxIndex;
<a class="dynamics-marker" style="left:@left%" title="@item.RelationshipStateName @item.Intensity" asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">
<span style="height:@Math.Max(item.Intensity ?? 3, 1)0%"></span>
</a>
}
</div>
</section>
<partial name="_DynamicsIssues" model="Model.Issues" />
<section class="story-bible-section">
<h2>Relationship History</h2>
<div class="writer-queue-list">
@foreach (var item in Model.Events)
{
<article class="writer-queue-card">
<div class="writer-queue-title">
<h3>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</h3>
<span class="status-pill">@item.RelationshipStateName</span>
</div>
<div class="story-bible-meta">
<span>Intensity @DisplayValue(item.Intensity)</span>
<span>@(item.IsKnownToOtherCharacter ? "Known to other character" : "Private/uncertain")</span>
</div>
<p>@item.Description</p>
</article>
}
</div>
</section>
@functions {
private static string DisplayValue(int? value) => value?.ToString() ?? "-";
}
<div data-relationship-history-shell data-project-id="@Model.Project.ProjectID" data-character-id="@Model.ReturnCharacterID" data-relationship-id="@r.CharacterRelationshipID"><p data-history-status role="status"></p><dialog data-history-dialog aria-labelledby="character-operation-title"><div data-history-dialog-content></div><button type="button" data-history-fallback>Cancel</button></dialog></div>
@section Scripts{<link rel="stylesheet" href="~/css/character-workspace.css" asp-append-version="true"/><script src="~/js/relationship-history.js" asp-append-version="true"></script>}

View File

@ -128,6 +128,7 @@
@foreach (var category in ApplicationRibbon.Categories)
{
<div class="pd-ribbon-panel" id="ribbon-panel-@category.Key" role="tabpanel" aria-labelledby="ribbon-tab-@category.Key" hidden="@(category.Key != selectedCategory)">
@if(category.Key=="characters"&&ViewData["CharacterRibbonModel"] is CharacterDetailViewModel characterRibbon){<partial name="_CharacterRibbonCommands" model="characterRibbon"/>}
@foreach (var group in category.Key == "writer" ? WriterNavigation.RibbonGroups(Model.WriterDestination,controller=="WriterInvestigations") : category.Groups)
{
<div class="pd-ribbon-group" role="group" aria-label="@group.Label">

View File

@ -0,0 +1,10 @@
@model CharacterDetailViewModel
@{var c=Model.Character;var analysis=Model.CharacterAnalysis;}
<div class="pd-ribbon-group" role="group" aria-label="Selected character" data-character-ribbon="@c.CharacterID"><div class="pd-ribbon-commands">
@if(Model.WorkspaceCanEdit){<a class="pd-ribbon-command" asp-controller="Characters" asp-action="Edit" asp-route-id="@c.CharacterID" data-character-ribbon-edit><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("writer").IconPath"/></svg><span>Edit Character</span></a>}
<div class="dropdown"><button type="button" class="pd-ribbon-command dropdown-toggle" data-bs-toggle="dropdown"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("details").IconPath"/></svg><span>Actions</span></button><div class="dropdown-menu dropdown-menu-end character-ribbon-menu" data-character-actions-for="@c.CharacterID">
@if(Model.WorkspaceCanEdit){<a class="dropdown-item" asp-controller="Characters" asp-action="Merge" asp-route-id="@c.CharacterID">Merge with another character</a><form asp-controller="Characters" asp-action="Reanalyse" method="post" data-character-reanalyse-form><input type="hidden" name="id" value="@c.CharacterID"/><button class="dropdown-item" data-character-reanalyse-button disabled="@(analysis.Status is CharacterEnrichmentStatuses.Queued or CharacterEnrichmentStatuses.Running)">Reanalyse character</button></form>}
<a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@c.CharacterID">Export character</a><a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@c.CharacterID" asp-route-format="markdown">Markdown</a>
@if(Model.WorkspaceCanEdit){<form asp-controller="Characters" asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this character? Its data will be retained for restoration."><input type="hidden" name="id" value="@c.CharacterID"/><input type="hidden" name="projectId" value="@c.ProjectID"/><button class="dropdown-item text-danger">Archive character</button></form>}
</div></div>
</div><span class="pd-ribbon-group-label">Selected character</span></div>

View File

@ -1 +1,10 @@
[data-character-workspace]{min-width:0;overflow-wrap:anywhere;}.character-workspace-header{display:flex;align-items:center;gap:1rem;flex-wrap:wrap;padding:1rem 0;}.character-workspace-header h1{margin:0;font-size:clamp(1.45rem,2.5vw,2rem);}.character-workspace-header p{margin:0;}.character-workspace-identity{flex:1;min-width:12rem;}.character-workspace-switch{display:flex;align-items:end;gap:.7rem;flex-wrap:wrap;margin-bottom:.75rem;}.character-workspace-switch label{width:min(25rem,100%);}.character-workspace-tabs{display:flex;flex-wrap:wrap;gap:.25rem;border-bottom:1px solid var(--plotline-line);margin-block:.8rem;}.character-workspace-tabs a{padding:.7rem 1rem;color:var(--plotline-ink);text-decoration:none;border-radius:.5rem .5rem 0 0;}.character-workspace-tabs [aria-selected=true]{font-weight:700;background:var(--pd-selected,var(--plotline-panel));box-shadow:inset 0 -3px var(--plotline-accent);}.character-dossier{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(0,1fr);gap:1rem;}.character-dossier .plain-card{margin-bottom:1rem;min-width:0;}.character-glance{display:grid;grid-template-columns:1fr 1fr;gap:.7rem;}.character-glance a{padding:.6rem;border:1px solid var(--plotline-line);border-radius:.5rem;}.character-glance strong{display:block;font-size:1.4rem;}.character-long-text{white-space:pre-wrap;overflow-wrap:anywhere;max-width:100%;}.character-tab-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;flex-wrap:wrap;}.character-tab-heading h2{margin-top:.5rem;}.character-workspace-filters{display:flex;align-items:end;flex-wrap:wrap;gap:.7rem;margin-block:1rem;}.character-workspace-filters label{flex:1;min-width:10rem;}.character-position,.character-graph-toolbar,.character-relationship-lenses{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-block:.7rem;}.character-relationship-lenses [aria-pressed=true]{font-weight:700;box-shadow:inset 0 -3px var(--plotline-accent);}.character-record{padding:.85rem;margin-block:.5rem;border:1px solid var(--plotline-line);border-radius:.6rem;background:var(--plotline-panel);min-width:0;}.character-record h3{font-size:1.05rem;margin:0 0 .3rem;}.character-record p{margin-block:.3rem;}.character-record.is-selected{outline:2px solid var(--plotline-accent);}.character-record-detail{padding:.7rem 0;}.character-record-detail>a,.character-record-detail>button{margin:.3rem .5rem .3rem 0;}.character-history-group>h3{font-size:1rem;margin-top:1.25rem;}.character-workspace-pagination{display:flex;flex-wrap:wrap;align-items:center;gap:.75rem;margin-block:1rem;}[data-character-graph]{height:clamp(23rem,50vh,36rem);overflow:hidden;border:1px solid var(--plotline-line);border-radius:.7rem;min-width:0;touch-action:none;cursor:grab;}[data-character-graph] svg{touch-action:none;user-select:none;}[data-character-node]{cursor:pointer;}[data-character-node] rect{fill:var(--plotline-surface,#fff);stroke:var(--plotline-muted,#777);stroke-width:1.5;}[data-character-node] text{fill:var(--plotline-ink,#222);font-size:13px;}[data-character-node] .character-node-meta{font-size:10px;fill:var(--plotline-muted,#777);}[data-character-node].is-selected rect,[data-character-node]:focus rect{stroke:var(--plotline-accent);stroke-width:3;}[data-character-edge].is-selected path{stroke-width:4;}[data-character-connection]{cursor:pointer;}[data-character-branch]{cursor:pointer;}[data-character-branch] rect{fill:var(--plotline-surface,#fff);stroke:var(--plotline-accent);}[data-character-branch] text{fill:var(--plotline-accent);font-weight:700;}[data-workspace-dialog]{width:min(48rem,calc(100vw - 2rem));max-width:calc(100vw - 2rem);max-height:90vh;border:1px solid var(--plotline-line);border-radius:.8rem;padding:1.2rem;background:var(--plotline-surface,#fff);color:var(--plotline-ink);} [data-workspace-dialog]::backdrop{background:#0008;}[data-workspace-dialog] form{display:flex;flex-direction:column;gap:.6rem;min-width:0;}[data-workspace-dialog] input:not([type=checkbox]):not([type=hidden]),[data-workspace-dialog] select,[data-workspace-dialog] textarea{width:100%;max-width:100%;min-width:0;box-sizing:border-box;}[data-workspace-dialog] textarea{min-height:9rem;resize:vertical;}.character-checkbox{display:flex;align-items:center;gap:.5rem;}.character-checkbox input{flex:none;}.character-graph-legend{font-size:.8rem;color:var(--plotline-muted);margin:.6rem 0;}@media(max-width:800px){.character-dossier{grid-template-columns:1fr;}.character-workspace-header>.button-row{width:100%;}.character-workspace-tabs a{padding:.6rem .7rem;}.character-workspace-filters{display:grid;grid-template-columns:1fr 1fr;}.character-workspace-filters label{min-width:0;}}@media(max-width:480px){.character-workspace-tabs a{flex:1;text-align:center;}.character-workspace-filters{grid-template-columns:1fr;}[data-workspace-dialog]{padding:.9rem;}.character-glance{grid-template-columns:1fr 1fr;}[data-character-graph]{height:25rem;}}
.character-relationship-group{margin-block:10px;padding:12px 16px}.character-relationship-group>summary{display:list-item;cursor:pointer}.character-relationship-group>summary>span{margin-inline-start:12px}.character-group-definitions{padding-top:12px}.character-group-definitions .character-record{cursor:pointer}.character-definition-select{font:inherit;color:inherit}.character-record:focus-visible{outline:2px solid var(--plotline-accent);outline-offset:3px}
.relationship-evolution-chart svg{display:block;width:100%;max-height:240px;color:var(--plotline-text);overflow:visible}.relationship-evolution-chart line{stroke:var(--plotline-line)}.relationship-evolution-chart text{fill:currentColor;font-size:12px}.relationship-evolution-chart circle{fill:#a587d8;stroke:var(--plotline-text);stroke-width:1}.relationship-evolution-chart a:focus circle{stroke-width:4}[data-history-dialog]{width:min(760px,calc(100vw - 32px));max-height:88vh;overflow:auto;border:1px solid var(--plotline-line);border-radius:14px;background:var(--plotline-panel);color:var(--plotline-text);padding:24px}[data-history-dialog] label{display:block;margin-top:12px}[data-history-dialog] textarea,[data-history-dialog] select,[data-history-dialog] input:not([type=checkbox]):not([type=hidden]){width:100%}[data-history-dialog]::backdrop{background:rgba(0,0,0,.55)}
.relationship-evolution-chart{overflow-x:auto;min-width:0}.relationship-evolution-chart svg{min-width:700px;height:210px}
.character-ribbon-menu{background:var(--app-surface);color:var(--app-text);z-index:1030}
html[data-theme="dark"] :is([data-character-workspace],[data-relationship-events],[data-history-dialog]) .btn-outline-primary{color:var(--app-link)!important;border-color:currentColor;background:transparent!important}
html[data-theme="dark"] :is([data-character-workspace],[data-relationship-events],[data-history-dialog]) .btn-outline-danger{color:#ffb2aa!important;border-color:rgba(238,142,131,.65);background:transparent!important}

View File

@ -10,7 +10,7 @@
for(const route of layout.routes){const l=data.links.find(l=>l.id===route.id);if(!l)continue;let d=route.d;if(lens==='story'){const a=layout.positions[l.a],b=layout.positions[l.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 g=el('g',{'data-character-edge':l.id}),colour=lens==='family'?familyColours[route.kind]||'#777':colours[l.category]||'#777';if(lens==='family')g.append(el('path',{d,fill:'none',stroke:'var(--plotline-panel,#fff)','stroke-width':6,'pointer-events':'none'}));const line=el('path',{d,fill:'none',stroke:colour,'stroke-width':2,'pointer-events':'none'});if(lens==='family'&&['adoptive','step','half','other'].includes(route.kind))line.setAttribute('stroke-dasharray',route.kind==='step'?'2 5':'7 4');if(lens==='story'){line.setAttribute('marker-end',`url(#${markerID})`);if(l.reciprocal)line.setAttribute('marker-start',`url(#${markerID})`);}g.append(line);const hit=el('path',{d,fill:'none',stroke:'transparent','stroke-width':16,role:'button',tabindex:0,'data-character-connection':l.id,'aria-label':`${l.type}: ${data.nodes.find(n=>n.id===l.a)?.name} to ${data.nodes.find(n=>n.id===l.b)?.name}`});listen(hit,'click',()=>pickLink(l.id));listen(hit,'keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();pickLink(l.id);}});g.append(hit);world.append(g);}
for(const n of data.nodes){const p=layout.positions[n.id];if(!p)continue;const g=el('g',{transform:`translate(${p.x} ${p.y})`,'data-character-node':n.id,role:'button',tabindex:0,'aria-label':n.name});g.append(el('title',{},n.name),el('rect',{width:180,height:66,rx:9}));const name=n.name.length>45?n.name.slice(0,43)+'…':n.name,cut=name.lastIndexOf(' ',23),split=cut>4?cut:23;g.append(el('text',{x:10,y:22},name.slice(0,split)),el('text',{x:10,y:39},name.slice(split).trim()),el('text',{x:10,y:57,class:'character-node-meta'},n.id===options.id?'This character':lens==='family'&&n.isDeceased===true?'† Deceased · author reference':'Recorded identity'));listen(g,'click',()=>pickNode(n.id));listen(g,'keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();pickNode(n.id);}});world.append(g);}
if(lens==='family'){for(const j of layout.junctions||[])world.append(el('circle',{cx:j.x,cy:j.y,r:3,fill:'#777','pointer-events':'none'}));for(const b of branches){const p=layout.positions[b.id];if(!p)continue;const g=el('g',{transform:`translate(${p.x+183} ${p.y+19})`,role:'button',tabindex:0,'data-character-branch':b.id,'aria-expanded':String(b.expanded),'aria-label':`${b.expanded?'Collapse':'Expand'} recorded relatives; ${b.hidden} hidden adjacent relatives`});g.append(el('rect',{width:28,height:28,rx:7}),el('text',{x:14,y:19,'text-anchor':'middle'},b.expanded?'−':'+'));const toggle=e=>{e.stopPropagation();if(b.expanded)v.expanded=v.expanded.filter(id=>id!==b.id);else if(v.expanded.length<64)v.expanded.push(b.id);else{PlotDirector.toast.info('Collapse a branch before expanding another.');return;}void load();};listen(g,'click',toggle);listen(g,'keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle(e);}});world.append(g);}}
status.textContent=[data.truncated?'The diagram reached its 128-person/256-connection bound. Re-centre to explore further.':null,...layout.warnings].filter(Boolean).join(' ');if(!v.initialised)centre(v.focus);else transform();if(v.selected)pickLink(v.selected,false);else pickNode(selectedNode&&data.nodes.some(n=>n.id===selectedNode)?selectedNode:v.focus);
status.textContent=[data.truncated?'The diagram reached its 128-person/256-connection bound. Re-centre to explore further.':null,...layout.warnings].filter(Boolean).join(' ');if(!v.initialised)centre(v.focus);else transform();if(options.selectedID&&!v.selected)v.selected=options.selectedID;if(v.selected)pickLink(v.selected,false);else pickNode(selectedNode&&data.nodes.some(n=>n.id===selectedNode)?selectedNode:v.focus);
}
async function load(){const version=++epoch;request?.abort();request=new AbortController();root.querySelectorAll('[data-character-lens]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.characterLens===lens)));status.textContent='Loading recorded relationships…';const v=view(),q=new URLSearchParams();let endpoint;if(lens==='family'){endpoint='Family';q.set('focusId',v.focus);for(const id of v.expanded)q.append('expanded',id);}else{endpoint='Story';if(options.sceneID)q.set('sceneId',options.sceneID);}try{const response=await fetch(`/Characters/Workspace/${endpoint}/${options.id}?${q}`,{cache:'no-store',signal:AbortSignal.any([signal,request.signal,AbortSignal.timeout(20000)])});if(!response.ok||response.redirected)throw Error('Relationship diagram is unavailable. Check access or use the full editor.');const result=await response.json();if(version!==epoch)return;data=result.graph||result;branches=result.branches||[];draw();}catch(e){if(e.name!=='AbortError'&&version===epoch)status.textContent=e.message;}}
for(const b of root.querySelectorAll('[data-character-lens]'))listen(b,'click',()=>{lens=b.dataset.characterLens;options.onLens?.(lens);void load();});for(const b of root.querySelectorAll('[data-character-zoom]'))listen(b,'click',()=>zoom(b.dataset.characterZoom==='in'?1.2:1/1.2));listen(root.querySelector('[data-character-graph-centre]'),'click',()=>{if(lens==='family'){view().focus=selectedNode||options.id;view().initialised=false;void load();}else centre(selectedNode||options.id);});listen(root.querySelector('[data-character-graph-reset]'),'click',()=>{view().focus=options.id;view().initialised=false;void load();});

View File

@ -1,6 +1,7 @@
(() => {
'use strict';const root=document.querySelector('[data-character-workspace]');if(!root)return;const id=Number(root.dataset.characterId),project=Number(root.dataset.projectId),panel=root.querySelector('[data-workspace-panel]'),status=root.querySelector('[data-workspace-status]'),dialog=root.querySelector('[data-workspace-dialog]'),dialogBody=root.querySelector('[data-workspace-dialog-content]'),cache=new Map(),queries=new Map(),graphViews={},key=`pd.character.tab.v1.${root.dataset.userId}.${project}`;let tab='',epoch=0,request,graph,lens='family',baseline='',saving=false,pending=false,connection,lookupRequest,lookupTimer;const controller=new AbortController(),signal=controller.signal;
const listen=(n,e,f,options={})=>n?.addEventListener(e,f,{...options,signal});function tidy(q){const names={tab:'Tab',page:'Page',search:'Search',bookid:'BookID',category:'Category',sceneid:'SceneID',relationshipid:'RelationshipID'};const clean=new URLSearchParams();for(const[k,v]of q){const name=names[k.toLowerCase()];if(name)clean.set(name,v);}return clean;}
'use strict';const root=document.querySelector('[data-character-workspace]');if(!root)return;const id=Number(root.dataset.characterId),project=Number(root.dataset.projectId),panel=root.querySelector('[data-workspace-panel]'),status=root.querySelector('[data-workspace-status]'),dialog=root.querySelector('[data-workspace-dialog]'),dialogBody=root.querySelector('[data-workspace-dialog-content]'),cache=new Map(),queries=new Map(),graphViews={},key=`pd.character.tab.v1.${root.dataset.userId}.${project}`;const expandedGroups=new Set();let selectedDefinition=Number(new URL(location.href).searchParams.get('relationshipId')||new URL(location.href).searchParams.get('RelationshipID'))||null;let tab='',epoch=0,request,graph,lens='family',baseline='',saving=false,pending=false,connection,lookupRequest,lookupTimer;const controller=new AbortController(),signal=controller.signal;
const ribbon=document.querySelector('[data-character-ribbon]'),ribbonToggle=ribbon?.querySelector('[data-bs-toggle="dropdown"]'),ribbonMenu=ribbon?.querySelector('.dropdown-menu');if(ribbonToggle&&ribbonMenu&&window.bootstrap){bootstrap.Dropdown.getOrCreateInstance(ribbonToggle,{popperConfig:config=>({...config,strategy:'fixed'})});ribbonToggle.addEventListener('show.bs.dropdown',()=>document.body.append(ribbonMenu));ribbonToggle.addEventListener('hidden.bs.dropdown',()=>ribbonToggle.parentElement.append(ribbonMenu));ribbonMenu.addEventListener('keydown',e=>{if(!['Escape','ArrowDown','ArrowUp','Home','End'].includes(e.key))return;e.preventDefault();e.stopPropagation();if(e.key==='Escape'){bootstrap.Dropdown.getInstance(ribbonToggle).hide();ribbonToggle.focus();return;}const items=[...ribbonMenu.querySelectorAll('.dropdown-item:not(:disabled)')].filter(n=>n.getClientRects().length),index=items.indexOf(document.activeElement),next=e.key==='Home'?0:e.key==='End'?items.length-1:(index+(e.key==='ArrowDown'?1:-1)+items.length)%items.length;items[next]?.focus();});}
const listen=(n,e,f,options={})=>n?.addEventListener(e,f,{...options,signal});function tidy(q){const names={tab:'Tab',page:'Page',search:'Search',bookid:'BookID',category:'Category',sceneid:'SceneID',relationshipid:'RelationshipID',othercharacterid:'OtherCharacterID',definitionpage:'DefinitionPage'};const clean=new URLSearchParams();for(const[k,v]of q){const name=names[k.toLowerCase()];if(name)clean.set(name,v);}return clean;}
const initial=new URL(location.href),normalise=t=>['overview','relationships','evolution','appearances','knowledge'].includes(t)?t:'overview';let remembered='overview';try{remembered=normalise(localStorage.getItem(key));}catch{}
const dirty=()=>dialog.open&&!!dialogBody.querySelector('[data-workspace-operation-form]')&&new URLSearchParams(new FormData(dialogBody.querySelector('[data-workspace-operation-form]'))).toString()!==baseline||[...root.querySelectorAll('form[data-workspace-dirty=true]'),...Array.from(cache.values()).flatMap(e=>[...e.node.querySelectorAll('form[data-workspace-dirty=true]')])].length>0;
function discard(){for(const node of [root,...Array.from(cache.values()).map(e=>e.node)])for(const f of node.querySelectorAll('form[data-workspace-dirty=true]')){f.reset();delete f.dataset.workspaceDirty;}baseline='';if(dialog.open)dialog.close();dialogBody.replaceChildren();}
@ -9,42 +10,45 @@
function currentQuery(){return queries.get(tab)||new URLSearchParams({Tab:tab});}function urlFor(q){return `/Characters/Workspace/Tab/${id}?${q}`;}function remember(){try{localStorage.setItem(key,tab);}catch{}}
function locationFor(t,q){const url=new URL(`/Characters/Details/${id}`,location.origin);url.searchParams.set('tab',t);for(const [k,v]of q||[])if(v&&k!=='Tab')url.searchParams.set(k,v);return url;}
function activate(){for(const a of root.querySelectorAll('[data-character-tab]')){const selected=a.dataset.characterTab===tab;a.setAttribute('aria-selected',String(selected));a.tabIndex=selected?0:-1;}panel.setAttribute('aria-labelledby','character-tab-'+tab);remember();}
function mount(){graph?.dispose();graph=null;if(tab==='relationships'){const host=panel.querySelector('[data-character-graph]');if(host)graph=window.PlotDirectorCharacterGraph.mount(host,{id,sceneID:currentQuery().get('SceneID')||null,views:graphViews,lens,onLens:l=>lens=l,onLink:selectRelationship});}panel.querySelectorAll('[data-character-link]').forEach(a=>{const url=new URL(a.href);url.searchParams.set('tab',tab);const point=currentQuery().get('SceneID');if(point)url.searchParams.set('sceneId',point);a.href=url.href;});if(location.hash==='#character-gallery'){const gallery=panel.querySelector('[data-workspace-gallery]');if(gallery){gallery.open=true;gallery.scrollIntoView({block:'start'});}}}
function mount(){for(const group of panel.querySelectorAll("[data-relationship-group]"))if(expandedGroups.has(group.dataset.relationshipGroup))group.open=true;if(selectedDefinition)panel.querySelector(`[data-workspace-relationship="${selectedDefinition}"]`)?.classList.add("is-selected");graph?.dispose();graph=null;if(tab==='relationships'){const host=panel.querySelector('[data-character-graph]');if(host)graph=window.PlotDirectorCharacterGraph.mount(host,{id,sceneID:currentQuery().get('SceneID')||null,views:graphViews,lens,selectedID:selectedDefinition,onLens:l=>lens=l,onLink:selectRelationship});}panel.querySelectorAll('[data-character-link]').forEach(a=>{const url=new URL(a.href);url.searchParams.set('tab',tab);const point=currentQuery().get('SceneID');if(point)url.searchParams.set('sceneId',point);a.href=url.href;});if(location.hash==='#character-gallery'){const gallery=panel.querySelector('[data-workspace-gallery]');if(gallery){gallery.open=true;gallery.scrollIntoView({block:'start'});}}}
async function show(t,q=null,push=false,force=false){t=normalise(t);if((t!==tab||push)&&!leave())return;const next=q||queries.get(t)||new URLSearchParams({Tab:t});next.set('Tab',t);queries.set(t,next);tab=t;activate();if(push)history.pushState({},'',locationFor(t,next));const version=++epoch;request?.abort();request=new AbortController();const cacheKey=next.toString(),old=cache.get(t);if(!force&&old?.key===cacheKey&&!old.stale){panel.replaceChildren(old.node);mount();status.textContent='';return;}
status.textContent='Loading character '+t+'…';panel.setAttribute('aria-busy','true');try{const response=await fetch(urlFor(next),{cache:'no-store',signal:AbortSignal.any([signal,request.signal,AbortSignal.timeout(25000)])});if(!response.ok||response.redirected)throw Error('This character tab is unavailable. Check access and retry.');const html=await response.text();if(version!==epoch)return;const template=document.createElement('template');template.innerHTML=html;const node=template.content.firstElementChild;if(!node?.matches('[data-character-tab-content]'))throw Error('The character tab did not return a valid workspace.');cache.set(t,{key:cacheKey,node,stale:false});panel.replaceChildren(node);mount();status.textContent='';}catch(e){if(e.name!=='AbortError'&&version===epoch)status.textContent=e.message;}finally{if(version===epoch)panel.removeAttribute('aria-busy');}}
function invalidate(){for(const e of cache.values())e.stale=true;if(dialog.open||saving||dirty()){pending=true;status.textContent='Updates available; your open form is retained.';return;}clearTimeout(invalidate.timer);invalidate.timer=setTimeout(()=>void show(tab,currentQuery(),false,true),180);}
function wire(c){if(connection||!c)return;connection=c;connection.on('ContextInvalidated',hint=>{if(hint.projectId&&Number(hint.projectId)!==project)return;invalidate();});connection.onreconnected(()=>invalidate());}
listen(document,'pd-presence-connection',e=>wire(e.detail));listen(document,'pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));wire(window.PlotDirectorPresenceConnection);
function selectRelationship(rid){root.querySelectorAll('[data-workspace-relationship]').forEach(n=>n.classList.toggle('is-selected',Number(n.dataset.workspaceRelationship)===rid));const row=panel.querySelector(`[data-workspace-relationship="${rid}"]`);if(row){row.scrollIntoView({block:'nearest'});return;}const q=new URLSearchParams(currentQuery());q.set('RelationshipID',rid);q.set('Page','1');q.delete('Search');void show('relationships',q,false,true).then(()=>{const record=panel.querySelector(`[data-workspace-relationship="${rid}"]`);if(record){record.classList.add('is-selected');graph?.selectLink(rid,false);}else status.textContent='This family connection is between relatives. Open the relevant character to manage its own records.';});}
function setDialog(html){dialogBody.innerHTML=html;root.querySelector('[data-workspace-dialog-fallback]').hidden=!!dialogBody.querySelector('[data-workspace-operation-form]');const form=dialogBody.querySelector('[data-workspace-operation-form]');baseline=form?new URLSearchParams(new FormData(form)).toString():'';dialogBody.querySelector('textarea,select,input:not([type=hidden]),button')?.focus();}
function selectRelationship(rid){selectedDefinition=rid;root.querySelectorAll('[data-workspace-relationship]').forEach(n=>n.classList.toggle('is-selected',Number(n.dataset.workspaceRelationship)===rid));const row=panel.querySelector(`[data-workspace-relationship="${rid}"]`);if(row){const group=row.closest('[data-relationship-group]');if(group){group.open=true;expandedGroups.add(group.dataset.relationshipGroup);}row.scrollIntoView({block:'nearest'});return;}const q=new URLSearchParams(currentQuery());q.set('RelationshipID',rid);q.set('Page','1');q.delete('Search');q.delete('Category');q.delete('OtherCharacterID');q.delete('DefinitionPage');void show('relationships',q,false,true).then(()=>{const record=panel.querySelector(`[data-workspace-relationship="${rid}"]`);if(record){record.classList.add('is-selected');const group=record.closest('[data-relationship-group]');if(group){group.open=true;expandedGroups.add(group.dataset.relationshipGroup);}graph?.selectLink(rid,false);}else status.textContent='This family connection is between relatives. Open the relevant character to manage its own records.';});}
function setDialog(html){dialogBody.innerHTML=html;root.querySelector('[data-workspace-dialog-fallback]').hidden=!!dialogBody.querySelector('[data-workspace-operation-form]');const form=dialogBody.querySelector('[data-workspace-operation-form]');baseline=form?new URLSearchParams(new FormData(form)).toString():'';dialogBody.querySelector('textarea:not(:disabled),select:not(:disabled),input:not([type=hidden]):not(:disabled),button:not(:disabled)')?.focus();}
async function openDialog(url){if(!leave())return;dialogBody.textContent='Loading…';root.querySelector('[data-workspace-dialog-fallback]').hidden=false;dialog.showModal();try{const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(20000)});if(!response.ok||response.redirected)throw Error('This relationship operation is unavailable. Check permission or reopen the record.');setDialog(await response.text());}catch(e){dialogBody.textContent=e.message;}}
listen(dialog,'cancel',e=>{e.preventDefault();if(leave()&&pending){pending=false;invalidate();}});listen(root.querySelector('[data-workspace-dialog-fallback]'),'click',()=>{if(leave()&&pending){pending=false;invalidate();}});
listen(root,'input',e=>{const f=e.target.closest('form');if(f&&f.method.toLowerCase()!=='get'&&!f.matches('[data-workspace-operation-form]'))f.dataset.workspaceDirty='true';});
listen(root,'click',async e=>{
const link=e.target.closest('[data-character-tab],[data-workspace-go]');if(link){e.preventDefault();void show(link.dataset.characterTab||link.dataset.workspaceGo,null,true);return;}
const cancel=e.target.closest('[data-workspace-cancel]');if(cancel){if(leave()&&pending){pending=false;invalidate();}return;}
const operation=e.target.closest('[data-workspace-operation]');if(operation){void openDialog(`/Characters/Workspace/Operation/${id}?`+new URLSearchParams({relationshipId:operation.dataset.relationship,operation:operation.dataset.workspaceOperation,...(operation.dataset.event?{eventId:operation.dataset.event}:{})}));return;}
const operation=e.target.closest('[data-workspace-operation]');if(operation){if(tab==='relationships'){const rid=Number(operation.dataset.relationship);selectRelationship(rid);graph?.selectLink(rid,false);}void openDialog(`/Characters/Workspace/Operation/${id}?`+new URLSearchParams({relationshipId:operation.dataset.relationship,operation:operation.dataset.workspaceOperation,...(operation.dataset.event?{eventId:operation.dataset.event}:{})}));return;}
if(e.target.closest('[data-workspace-add]')){void openDialog(`/Characters/Workspace/Add/${id}`);return;}
const page=e.target.closest('[data-workspace-page]');if(page){const host=page.closest('[data-character-tab-content]');if(host?.dataset.characterTabContent==='scenes'){void position(Number(page.dataset.workspacePage),dialog.dataset.positionQuery?new URLSearchParams(dialog.dataset.positionQuery):null);return;}if(host?.dataset.characterTabContent==='history'){void historyFor(host.dataset.relationshipId,Number(page.dataset.workspacePage),host.dataset.historyQuery?new URLSearchParams(host.dataset.historyQuery):null);return;}const q=new URLSearchParams(currentQuery());q.set('Page',page.dataset.workspacePage);void show(tab,q,true,true);return;}
const page=e.target.closest('[data-workspace-page]');if(page){const host=page.closest('[data-character-tab-content]');if(host?.dataset.characterTabContent==='scenes'){void position(Number(page.dataset.workspacePage),dialog.dataset.positionQuery?new URLSearchParams(dialog.dataset.positionQuery):null);return;}const q=new URLSearchParams(currentQuery());q.set('Page',page.dataset.workspacePage);void show(tab,q,true,true);return;}
const gallery=e.target.closest('[data-gallery-page]');if(gallery){if(!leave())return;const response=await fetch(urlFor(new URLSearchParams({Tab:'gallery',Page:gallery.dataset.galleryPage})),{cache:'no-store'});if(response.ok)panel.querySelector('[data-gallery-content]').innerHTML=await response.text();return;}
const record=e.target.closest('[data-workspace-select-relationship]');if(record){graph?.selectLink(Number(record.dataset.workspaceSelectRelationship),false);selectRelationship(Number(record.dataset.workspaceSelectRelationship));return;}
const hist=e.target.closest('[data-workspace-history]');if(hist){void historyFor(Number(hist.dataset.workspaceHistory));return;}
const groupPage=e.target.closest('[data-group-page]');if(groupPage){const q=new URLSearchParams(currentQuery());q.set('OtherCharacterID',groupPage.dataset.otherCharacter);q.set('DefinitionPage',groupPage.dataset.groupPage);q.set('Page','1');void show(tab,q,true,true);return;}if(e.target.closest('[data-all-groups]')){const q=new URLSearchParams(currentQuery());q.delete('OtherCharacterID');q.delete('DefinitionPage');q.set('Page','1');void show(tab,q,true,true);return;}
const definition=e.target.closest('[data-workspace-relationship]');if(definition&&!e.target.closest('button,a,input,select,textarea')){const rid=Number(definition.dataset.workspaceRelationship);graph?.selectLink(rid,false);selectRelationship(rid);return;}
if(e.target.closest('[data-workspace-position]')){void position();return;}
if(e.target.closest('[data-workspace-clear-position]')){const q=new URLSearchParams(currentQuery());q.delete('SceneID');q.set('Page','1');void show(tab,q,true,true);return;}
const point=e.target.closest('[data-workspace-set-position]');if(point){const q=new URLSearchParams(currentQuery());q.set('SceneID',point.dataset.workspaceSetPosition);q.set('Page','1');discard();void show(tab,q,true,true);return;}
const a=e.target.closest('a[data-character-link]');if(a&&!leave())e.preventDefault();
});
listen(root,'toggle',e=>{const group=e.target;if(!group.matches('[data-relationship-group]'))return;if(group.open)expandedGroups.add(group.dataset.relationshipGroup);else expandedGroups.delete(group.dataset.relationshipGroup);},{capture:true});
listen(root,'keydown',e=>{if(e.target.matches('[data-workspace-relationship]')&&(e.key==='Enter'||e.key===' ')){e.preventDefault();const rid=Number(e.target.dataset.workspaceRelationship);graph?.selectLink(rid,false);selectRelationship(rid);}});
listen(root,'submit',async e=>{
const form=e.target;if(form.matches('[data-workspace-filter]')){e.preventDefault();const q=new URLSearchParams(new FormData(form));q.set('Page','1');const owner=form.closest('[data-character-tab-content]')?.dataset.characterTabContent;if(owner==='scenes'){void position(1,q);return;}if(owner==='history'){void historyFor(Number(q.get('RelationshipID')),1,q);return;}void show(tab,q,true,true);return;}
const form=e.target;if(form.matches('[data-workspace-filter]')){e.preventDefault();const q=new URLSearchParams(new FormData(form));q.set('Page','1');const owner=form.closest('[data-character-tab-content]')?.dataset.characterTabContent;if(owner==='scenes'){void position(1,q);return;}void show(tab,q,true,true);return;}
if(!form.matches('[data-workspace-operation-form]'))return;e.preventDefault();if(saving)return;saving=true;for(const b of form.querySelectorAll('button'))b.disabled=true;
try{const response=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(30000)});if(response.ok&&response.headers.get('content-type')?.includes('json')){const result=await response.json();if(result.saved){baseline='';dialog.close();dialogBody.replaceChildren();pending=false;for(const entry of cache.values())entry.stale=true;const q=new URLSearchParams(currentQuery());q.delete('RelationshipID');queries.set(tab,q);PlotDirector.toast.success(result.message);void show(tab,q,false,true);return;}}if(response.status===400&&response.headers.get('content-type')?.includes('html')){const previous=baseline;setDialog(await response.text());baseline=previous;}else throw Error('The change was not confirmed. Your draft is retained; check access and retry.');}catch(error){let message=form.querySelector('[data-workspace-save-error]');if(!message){message=document.createElement('p');message.dataset.workspaceSaveError='';message.setAttribute('role','alert');form.prepend(message);}message.textContent=error.message;}finally{saving=false;for(const b of dialogBody.querySelectorAll('button'))b.disabled=false;}
try{const response=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(30000)});if(response.ok&&response.headers.get('content-type')?.includes('json')){const result=await response.json();if(result.saved){baseline='';dialog.close();dialogBody.replaceChildren();pending=false;for(const entry of cache.values())entry.stale=true;const q=new URLSearchParams(currentQuery());if(form.querySelector('[name=Action]')?.value==='archive'){q.delete('RelationshipID');const removed=Number(form.querySelector('[name=RelationshipID]')?.value);for(const view of Object.values(graphViews))if(view.selected===removed)view.selected=null;selectedDefinition=null;}queries.set(tab,q);PlotDirector.toast.success(result.message);void show(tab,q,false,true).then(()=>{const target=selectedDefinition?panel.querySelector(`[data-workspace-relationship="${selectedDefinition}"]`):panel;target?.focus();});return;}}if(response.status===400&&response.headers.get('content-type')?.includes('html')){const previous=baseline;setDialog(await response.text());baseline=previous;}else throw Error('The change was not confirmed. Your draft is retained; check access and retry.');}catch(error){let message=form.querySelector('[data-workspace-save-error]');if(!message){message=document.createElement('p');message.dataset.workspaceSaveError='';message.setAttribute('role','alert');form.prepend(message);}message.textContent=error.message;}finally{saving=false;for(const b of dialogBody.querySelectorAll('button'))b.disabled=false;}
});
async function historyFor(rid,page=1,criteria=null){const q=criteria||new URLSearchParams({Tab:'history',RelationshipID:rid,Page:page});q.set('Page',page);if(currentQuery().get('SceneID'))q.set('SceneID',currentQuery().get('SceneID'));const host=panel.querySelector('[data-character-history]');if(!host)return;host.textContent='Loading relationship history…';const response=await fetch(urlFor(q),{cache:'no-store'});if(response.ok){host.innerHTML=await response.text();const node=host.querySelector('[data-character-tab-content]');if(node){node.dataset.relationshipId=rid;node.dataset.historyQuery=q.toString();}host.scrollIntoView({block:'nearest'});}else host.textContent='Relationship history is unavailable.';}
async function position(page=1,criteria=null){if(!dialog.open){if(!leave())return;dialog.showModal();}const q=criteria||new URLSearchParams({Tab:'scenes',Page:page});q.set('Page',page);dialog.dataset.positionQuery=q.toString();const response=await fetch(urlFor(q),{cache:'no-store'});if(response.ok)setDialog(await response.text());else dialogBody.textContent='Narrative positions are unavailable.';}
listen(root,'input',e=>{if(e.target.matches('[data-workspace-target-search]')){clearTimeout(lookupTimer);lookupRequest?.abort();const text=e.target.value.trim();if(text.length<2)return;lookupTimer=setTimeout(async()=>{lookupRequest=new AbortController();try{const response=await fetch(`/Characters/Workspace/Lookup/${id}?search=${encodeURIComponent(text)}`,{cache:'no-store',signal:lookupRequest.signal});if(!response.ok)return;const items=await response.json(),select=dialogBody.querySelector('[data-workspace-target]');if(!select||!dialog.open)return;select.replaceChildren(new Option('Choose a character',''));for(const item of items)if(item.id!==id)select.append(new Option(item.name,item.id));}catch(e){if(e.name!=='AbortError')status.textContent='Character lookup is unavailable; your draft is retained.';}},250);}});
listen(root.querySelector('[data-character-switch]'),'input',e=>{clearTimeout(lookupTimer);lookupRequest?.abort();const text=e.target.value.trim(),host=root.querySelector('[data-character-matches]');host.replaceChildren();if(text.length<2)return;lookupTimer=setTimeout(async()=>{lookupRequest=new AbortController();try{const response=await fetch(`/Characters/Workspace/Lookup/${id}?search=${encodeURIComponent(text)}`,{cache:'no-store',signal:lookupRequest.signal});if(!response.ok)return;for(const item of await response.json()){const a=document.createElement('a');a.href=`/Characters/Details/${item.id}?tab=${tab}`;a.textContent=item.name;a.dataset.characterLink='';a.className='btn btn-outline-secondary btn-sm';host.append(a);}}catch(e){if(e.name!=='AbortError')host.textContent='Character lookup is unavailable.';}},250);});
listen(root.querySelector('[role=tablist]'),'keydown',e=>{if(!['ArrowLeft','ArrowRight','Home','End'].includes(e.key))return;e.preventDefault();const tabs=[...root.querySelectorAll('[data-character-tab]')],index=tabs.indexOf(document.activeElement),next=e.key==='Home'?0:e.key==='End'?tabs.length-1:(index+(e.key==='ArrowRight'?1:-1)+tabs.length)%tabs.length;tabs[next].focus();void show(tabs[next].dataset.characterTab,null,true);});
window.addEventListener('popstate',()=>{if(!leave()){history.pushState({},'',locationFor(tab,currentQuery()));return;}const u=new URL(location.href),q=new URLSearchParams(u.search);q.set('Tab',normalise(q.get('tab')||q.get('Tab')));q.delete('tab');void show(q.get('Tab'),q,false);});window.addEventListener('beforeunload',e=>{if(dirty()){e.preventDefault();e.returnValue='';}});window.addEventListener('pagehide',()=>{controller.abort();graph?.dispose();clearTimeout(lookupTimer);clearTimeout(invalidate.timer);request?.abort();});listen(root,'character-analysis-updated',()=>{const cached=cache.get('overview');if(cached)cached.stale=true;if(tab==='overview'&&!dialog.open&&!dirty()&&!saving)void show(tab,currentQuery(),false,true);});
let selected=root.dataset.initialTab||remembered;const hashes={'#character-overview':'overview','#character-gallery':'overview','#character-relationships':'relationships','#character-appearances':'appearances'};if(hashes[location.hash])selected=hashes[location.hash];const q=tidy(new URLSearchParams(initial.search));q.set('Tab',selected);const existing=panel.querySelector('[data-character-tab-content]');if(existing&&existing.dataset.characterTabContent===selected){tab=selected;queries.set(tab,q);cache.set(tab,{key:q.toString(),node:existing,stale:false});activate();mount();}else void show(selected,q,false);
const requested=initial.searchParams.get('operation'),rid=initial.searchParams.get('relationshipId');if(requested==='archive'&&rid)void openDialog(`/Characters/Workspace/Operation/${id}?relationshipId=${encodeURIComponent(rid)}&operation=archive`);
let selected=root.dataset.initialTab||remembered;const hashes={'#character-overview':'overview','#character-gallery':'overview','#character-relationships':'relationships','#character-appearances':'appearances'};if(hashes[location.hash])selected=hashes[location.hash];const q=tidy(new URLSearchParams(initial.search));q.set('Tab',selected);const existing=panel.querySelector('[data-character-tab-content]');let initialReady;if(existing&&existing.dataset.characterTabContent===selected){tab=selected;queries.set(tab,q);cache.set(tab,{key:q.toString(),node:existing,stale:false});activate();mount();initialReady=Promise.resolve();}else initialReady=show(selected,q,false);if(selectedDefinition&&selected==='relationships')void initialReady.then(()=>selectRelationship(selectedDefinition));
const requested=initial.searchParams.get('operation'),rid=initial.searchParams.get('relationshipId');if(['archive','definition','event-edit','event-remove'].includes(requested)&&rid)void openDialog(`/Characters/Workspace/Operation/${id}?`+new URLSearchParams({relationshipId:rid,operation:requested,...(initial.searchParams.get('eventId')?{eventId:initial.searchParams.get('eventId')}: {})}));
})();

View File

@ -0,0 +1 @@
(()=>{'use strict';const root=document.querySelector('[data-relationship-history-shell]');if(!root)return;const dialog=root.querySelector('dialog'),body=root.querySelector('[data-history-dialog-content]'),fallback=root.querySelector('[data-history-fallback]');let baseline='',saving=false,pending=false;let refreshRequest;async function refresh(){if(dialog.open||saving){pending=true;return;}refreshRequest?.abort();refreshRequest=new AbortController();try{const response=await fetch(location.href,{cache:'no-store',signal:refreshRequest.signal});if(!response.ok||response.redirected)throw Error('History refresh is unavailable. Reload to retry.');const next=new DOMParser().parseFromString(await response.text(),'text/html').querySelector('[data-relationship-history-content]');if(!next)throw Error('History refresh is unavailable. Reload to retry.');document.querySelector('[data-relationship-history-content]').replaceWith(next);const url=new URL(location.href);if(Number(next.dataset.historyPage)>1)url.searchParams.set('page',next.dataset.historyPage);else url.searchParams.delete('page');history.replaceState({},'',url);root.querySelector('[data-history-status]').textContent='';pending=false;}catch(error){if(error.name!=='AbortError')root.querySelector('[data-history-status]').textContent=error.message;}}const dirty=()=>dialog.open&&body.querySelector('form')&&new URLSearchParams(new FormData(body.querySelector('form'))).toString()!==baseline;function close(){if(saving||dirty()&&!confirm('Discard unsaved event changes?'))return false;dialog.close();body.replaceChildren();baseline='';if(pending){pending=false;void refresh();}return true;}const adopt=html=>{body.innerHTML=html;fallback.hidden=!!body.querySelector('form');baseline=new URLSearchParams(new FormData(body.querySelector('form'))).toString();body.querySelector('textarea,select,input:not([type=hidden]),button')?.focus();};document.addEventListener('click',async e=>{const button=e.target.closest('[data-history-operation]');if(!button)return;body.textContent='Loading…';fallback.hidden=false;dialog.showModal();try{const q=new URLSearchParams({relationshipId:root.dataset.relationshipId,eventId:button.dataset.event,operation:button.dataset.historyOperation});const response=await fetch(`/Characters/Workspace/Operation/${root.dataset.characterId}?${q}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('This operation is unavailable. Check access or reopen the history.');adopt(await response.text());}catch(error){body.textContent=error.message;}});dialog.addEventListener('cancel',e=>{e.preventDefault();close();});dialog.addEventListener('click',e=>{if(e.target.closest('[data-workspace-cancel],[data-history-fallback]'))close();});dialog.addEventListener('submit',async e=>{const form=e.target;if(!form.matches('[data-workspace-operation-form]'))return;e.preventDefault();if(saving)return;saving=true;form.querySelectorAll('button').forEach(b=>b.disabled=true);try{const response=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{'X-Requested-With':'XMLHttpRequest'}});if(response.ok&&response.headers.get('content-type')?.includes('json')){const result=await response.json();if(result.saved){baseline='';dialog.close();body.replaceChildren();pending=false;saving=false;PlotDirector.toast.success(result.message);void refresh();return;}}if(response.status===400&&response.headers.get('content-type')?.includes('html')){const previous=baseline;adopt(await response.text());baseline=previous;}else throw Error('The change was not confirmed. Your draft is retained.');}catch(error){let alert=form.querySelector('[role=alert]');if(!alert){alert=document.createElement('p');alert.setAttribute('role','alert');form.prepend(alert);}alert.textContent=error.message;}finally{saving=false;body.querySelectorAll('button').forEach(b=>b.disabled=false);}});window.addEventListener('beforeunload',e=>{if(dirty()){e.preventDefault();e.returnValue='';}});let wired;function wire(connection){if(!connection||wired)return;wired=connection;connection.on('ContextInvalidated',hint=>{if(hint.projectId&&Number(hint.projectId)!==Number(root.dataset.projectId))return;if(dialog.open||saving){pending=true;return;}void refresh();});connection.onreconnected(()=>void refresh());}document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));wire(window.PlotDirectorPresenceConnection);window.addEventListener('pagehide',()=>refreshRequest?.abort());})();

View File

@ -44,6 +44,7 @@
const field = name => form.elements.namedItem(name);
const castById = new Map(cast.map(c => [c.characterID, c]));
const storageKey = `pd.relationship-workspace.v1.${projectId}.${workspace.bookId || 'project'}`;
let requestedDefinition=Number(new URL(location.href).searchParams.get("relationshipId"));
let focus = workspace.focusCharacterId, source = null, saveTimer, request = null, loading = false, stateLoaded = true;
const sceneStorageKey=`pd.scene-explorer.relationships:${document.body.dataset.pdUserId}:${projectId}:${workspace.bookId||'project'}`;
let currentScene = workspace.sceneId;
@ -342,7 +343,7 @@
if (focus) renderCharacterDetail();
else clearDetail();
} catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } }
finally { if (active === request) loading = false; }
finally { if (active === request){loading = false;if(stateLoaded)selectRequestedDefinition(true);} }
}
const explorerPositions = () => [{id:'initial',label:'Initial relationships',isScene:false},...scenes.map(s=>({id:s.value,label:s.text})),{id:'end',label:'End relationships',isScene:false}];
sceneExplorer = window.PlotDirectorSceneExplorer.create({host:document.querySelector('.rw-timeline'),positions:explorerPositions,
@ -503,4 +504,6 @@
applyFocus(!!workspace.focusCharacterId);
if (focus && window.innerWidth > 800) showDetail();
function selectRequestedDefinition(consume=false){if(!requestedDefinition)return;const definition=workspace.relationships().find(r=>r.characterRelationshipID===requestedDefinition);if(definition){workspace.selectRelationship(requestedDefinition);showRelationshipDetail();}else if(!loading)status.textContent="The requested definition is not established at this story point. Select its applicable story point to review it.";if(consume)requestedDefinition=0;}
selectRequestedDefinition();setTimeout(()=>{if(!loading&&stateLoaded)requestedDefinition=0;},0);
})();