diff --git a/Docs/Writer/Main-Character-Workspace-20261123.md b/Docs/Writer/Main-Character-Workspace-20261123.md new file mode 100644 index 00000000..2bed1ad8 --- /dev/null +++ b/Docs/Writer/Main-Character-Workspace-20261123.md @@ -0,0 +1,84 @@ +# Main Character workspace redesign — 23 November 2026 + +## Phase 1 audit / preservation contract + +Audit starts at `CharactersController.Details` → `ICharacterService.GetCharacterDetailAsync` → `Views/Characters/Details.cshtml`. The current GET loads every project character, relationship lookups/books, this character's relationship containers/events, the whole project character timeline and story timeline, all appearances, attribute events, knowledge and gallery images. This work precedes even the profile render. Existing URLs `/Characters/Details/{id}` must stay valid. + +| Existing capability | Current persistence / source | Workspace destination | +|---|---|---| +| Breadcrumbs, project ribbon, character/timeline return | Existing navigation and authorised IDs | Persistent shell/header | +| Portrait, thumbnail fallback, name | Canonical Characters / shared `_Avatar` | Compact persistent header | +| Major/supporting/minor importance | `CharacterImportance`, existing character create/edit/save | Header + Overview; explicit values preserved | +| Preferred name, aliases, set preferred | CharacterAliases; `SetPreferredName` service/action | Overview names dossier, same action | +| Description, sex, DOB, age/reference scene, height, eye colour, life status | Character edit/save; canonical age display service | Overview identity/profile; existing full edit | +| Generated summary, generated DOB/age/physical facts, status/message/last analysed | Character enrichment persisted status, existing reanalyse POST and SI hub | Overview analysis, separate from canonical profile; header reanalyse | +| Full character edit, merge | Existing Edit/Save and Merge services/actions | Header actions / Overview | +| Character export (normal/Markdown), archive/restore | Existing Exports and canonical archive operations | Header actions, archive retained | +| Gallery upload/caption, full image, crop/set avatar, remove avatar/image | Existing UploadImage/CropAvatar/DeleteImage/RemoveAvatar | Overview gallery disclosure and bounded page; same actions | +| Initial relationship add/edit; type, partner, state, intensity, reciprocity, reader awareness, initial book, notes | `SaveInitialRelationshipAsync` → canonical `Relationship_Save` | Relationships focused definition editor; advanced structural editing remains linked | +| Initial relationship removal/restore | `ArchiveRelationshipAsync` → `Relationship_Archive` → `Archive_Entity` | Direct confirmed Remove relationship on every related record | +| Current relationships, categories, direction, intensity/notes | Canonical relationship definitions + verified ordered events | Relationships Family/Story lenses + bounded records | +| Per-relationship initial/current state and event history | RelationshipEvents, canonical ordering/evidence projection | Selected relationship chronological history, bounded loading | +| All relationship events + related character/timeline links | `RelationshipEvent_ListByCharacter` | Relationship history filter and Evolution relationship category, preserving source links | +| Attribute history with values/descriptions/sources | CharacterAttributeEvents / canonical classifications | Evolution chronological explorer | +| Arc charts, scene metrics/markers, appearance/knowledge/relationship KPIs, continuity issues | Existing `Dynamics.Character`, dynamics services | Explicit Advanced arc / charts link in Evolution (existing endpoint retained) | +| Scene appearances, presence/role, outfit, condition/emotion, timeline/source | SceneCharacters + scenes/chapters/books | Appearances grouped, filtered, paged explorer | +| Canonical knowledge state, asset/thread, description, source point | CharacterKnowledge + canonical KnowledgeStates / evidence | Knowledge searchable/paged explorer with narrative cutoff | +| Existing knowledge timeline and continuity/review workflows | Dynamics.Knowledge, canonical Scene editor / Review Centre | Clear links in Knowledge; no generated prose reconstruction | +| Old fragment bookmarks `#character-overview`, `#character-gallery`, `#character-relationships`, `#character-appearances` | Existing anchor navigation | Mapped into the matching tab/disclosure by the workspace router | + +### Removal audit + +`IsReciprocal` is stored on one `CharacterRelationships` row. Canonical `Relationship_Save` updates/inserts that row; it does not manufacture a reverse row. Independently recorded reverse/different-type rows are separate authored facts and must be disclosed, not silently deleted. `Relationship_Archive` delegates to `Archive_Entity`, which marks only the definition archived with timestamps; dependent RelationshipEvents remain intact and restoration is available in Archived Items. This is the correct reversible removal operation for an erroneous parent/child definition, including one with historical events. The confirmation must name both characters, type, event count and separately recorded reverse/pair records retained. + +`RelationshipEvent_Delete` is the existing single-event deletion operation. Event removal must stay distinct from definition archive. Dependencies/provenance must be checked before deletion and unsafe linked events must be blocked with their existing source/review route. New workspace management must wrap canonical operations with project permissions and original-record comparison under SQL locks, not introduce another delete implementation. No actual manuscript relationship is to be modified for testing. + +### Classification audit + +Main character creation already defaults to Supporting (importance6). Scene quick-create currently leaves importance unrecorded, rather than explicitly Major. Existing author values and classification thresholds must not be migrated. Header labels will use Major ≥8, Supporting ≥4, Minor ≥1 and Unclassified otherwise; edit choices remain available through the existing editor. + +Implementation and phase validation evidence follows below. + +## Implemented workspace and phase acceptance + +The existing Character URL and ribbon now lead to a compact persistent identity header and five primary tabs. The shell reads identity, permissions, counts and age candidates; tab fragments fetch only their required bounded data. Tab, query, page and narrative point survive navigation; the remembered tab is scoped to the signed-in user and project. Existing fragment bookmarks map to their destination. Native dialog forms retain drafts on validation/concurrency failure, protect navigation and use the shared toast service. Existing presence and Story Intelligence connections are reused; tabs do not open connections. + +- **Overview:** responsive dossier with all canonical profile/age/life-status fields, known names and preferred-name action; description disclosure; bounded canonical family/story definition summaries; counts and three recent changes. Persisted enrichment is separate from author profile. Gallery retains uploads, captions, full images, avatar crop/set/remove and image removal, paged at 25. Full edit retains all aliases beyond the 50-name overview bound. +- **Relationships:** reuses `ContextFamilyExploration`, its topology, project tree reader and the shared genealogical layout engine, including biological/adoptive/step links, partnerships, vertical generations and expandable recorded relatives. Family remains global author reference and works without a book/scene. Story reuses the canonical Context reader, relationship projection and selected-scene ordering. The diagram is bounded at 128 people/256 connections; re-centering explores further. Records are paged at 25 with selection synchronised to the diagram. Independently authored relative-to-relative links are managed from the appropriate relative's workspace. +- **Evolution:** narrative book/chapter/scene groups, expandable changes, previous attribute values, actual classifications, evidence flags, book/category/search filters and source links; 25 entries per page. Existing charts, metrics, continuity issues and scene markers remain in the clearly linked advanced Arc workspace. +- **Appearances:** 25-entry searchable/grouped pages retain role/presence, POV, appearance notes, outfit, condition, emotion and knowledge notes, plus direct scene/timeline links. +- **Knowledge:** uses actual canonical knowledge-state text, source/evidence and review flags; search, book/state filters and narrative cutoff. Author reference does not imply viewpoint knowledge. Existing knowledge timeline and review/source workflows remain linked. + +### Focused relationship management + +Definition editing deliberately preserves pair, type, direction, book and narrative boundaries. It supports notes and, for initial definitions, state/intensity/reader awareness. Structural edits remain one clear link away in the existing full Relationships Editor. Individual history events have their own focused state/intensity/awareness/description editor; event removal is explicitly distinct from definition removal. + +Removal confirmation names both characters/type, identifies definition versus single event, reports dependent event count and independently authored pair records, and requires explicit confirmation. Definition removal calls canonical `Relationship_Archive`, retaining all events and Archived Items restoration. Single-event removal calls canonical `RelationshipEvent_Delete`. Evidence, review provenance or possible knowledge-source dependencies block direct event editing/removal and link to the source workflow. No second store or deletion implementation was introduced. + +The new stored-procedure wrapper revalidates Owner/Collaborator access, relationship membership and SHA-256 definition/history version under SQL locks before invoking canonical save/archive/delete procedures. New history invalidates stale previews. Successful writes log canonical project activity and publish existing Context invalidation hints; the active list and diagram refresh without a page reload. Viewer controls are hidden and writes are independently rejected server-side. + +### Database rollout + +Forward-only migrations 306 (bounded reads), 307 (authorised/concurrency-safe canonical management) and 308 (bounded definition summaries) were applied only to the verified `PlotDirector_Development` database. Existing numbered files were not changed after application. Before application, unique COPY_ONLY/CHECKSUM backups completed and passed `RESTORE VERIFYONLY`: + +- `/var/opt/mssql/backup/character-workspace-20261123T093043Z.bak` + +The additional summary migration backup `/var/opt/mssql/backup/character-workspace-summary-20261123T095708Z.bak` also passed verification. These backups were verified, not restored. Migrations add/alter routines, with no bulk character or manuscript relationship mutation. Main create remains Supporting6; new scene quick-created characters explicitly use Minor2; existing values are unchanged. + +### Integrity and regression evidence + +`CharacterWorkspaceTests` adds 15 passing service cases covering a thin header, bounded data, canonical ordering and future-state exclusion, labels, invalid queries, dependency previews, confirmation, stale/protected records and permissions. The explicit `--character-workspace-database ` mode validates effective Development plus the disposable account prefix before creating any fixture. Every case rolls back all newly created characters/relationships/events. It passed parent archive/restore with retained events, one-row reciprocal handling, independent reverse-record preservation, family/story edits, one-event removal, concurrent-history rejection, permission rejection, confirmation and source-linked blocking. Existing manuscript relationships were not changed. + +The actual Dapper reader was exercised read-only against an existing manuscript character: 55 relationship definitions, 509 overview-source changes, 755 evolution entries, 246 appearances and 282 knowledge entries. Each explorer returned at most 25 rows; SQL and .NET canonical scene order agreed, selected-point knowledge excluded later records, the management preview mapped its version/dependencies correctly, and the relationship checksum was identical before and after. No AI reanalysis was requested. + +The Playwright suite exercises the actual Razor shell/partials with isolated fixture responses: five lazy tabs, bounded histories/pages, cached page state, selected narrative position, back/forward, character links, old gallery fragment, keyboard tabs and modal focus/Escape/draft handling, full-width modal fields, explicit archive consequences, list/tree refresh, event controls and protected-source blocking. Widths 1366, 1024, 768 and 390 all pass without whole-page horizontal overflow. CDP touch events verify actual tablet pan and pinch transforms. Existing Context Family and Story browser suites also pass after the shared reader/tree extraction. Native/SI connection counts remain stable across tab switches. + +Screenshots captured during acceptance: `/tmp/character-workspace-overview-desktop.png`, `/tmp/character-workspace-family-desktop.png`, `/tmp/character-workspace-tablet-family.png`, `/tmp/character-workspace-mobile.png`. The dossier and tablet diagram have been visually inspected. + +### Preservation reconciliation and practical limits + +All rows in the Phase 1 matrix remain in the workspace or have an explicit link to their existing editor/advanced view. The redesign does not remove chart/continuity capabilities. The canonical archive limitation is made visible: removal hides a definition and retains history; independently authored pair records remain. Source-linked events require their source/review workflow, rather than unsafe direct deletion. These are explicit supported safety boundaries, not missing author functionality. + +Physical-device touch, assistive-technology screen-reader usability and author judgement of visual family complexity remain useful manual acceptance; automated tests cover touch emulation, keyboard, focus and responsive geometry. Family life status is labelled global author reference and does not invent a death scene. Ordering metadata is capped at 20,000 books/chapters/scenes per list; larger projects receive an explicit full-editor route instead of silent truncation. No production changes are authorised or performed. + +Final build: `dotnet build PlotLine.slnx` passed with zero warnings/errors. Full executable regression harness passed **786** checks. The prior preferred-name/enrichment source assertions were updated to follow their moved profile partial; both capabilities are also exercised in the rendered browser workspace. The separate enrichment browser check proves initial/reconnect completed-run replay is silent and each later completed run refreshes the workspace exactly once, without AI work or page navigation. diff --git a/PlotLine.Tests/Browser/character-workspace-enrichment.cjs b/PlotLine.Tests/Browser/character-workspace-enrichment.cjs new file mode 100644 index 00000000..720cafd2 --- /dev/null +++ b/PlotLine.Tests/Browser/character-workspace-enrichment.cjs @@ -0,0 +1,2 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); +(async()=>{const b=await chromium.launch();try{const p=await b.newPage();await p.setContent('
Completed
');await p.evaluate(()=>{window.refreshes=0;document.querySelector('[data-character-workspace]').addEventListener('character-analysis-updated',()=>window.refreshes++);const connection={on(name,fn){window.snapshot=fn},onreconnected(fn){window.reconnect=fn},start:async()=>{},invoke:async()=>({characterId:5,characterEnrichmentRunID:10,status:'Completed'})};window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return connection}}};});await p.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/character-enrichment-detail.js')});await p.waitForTimeout(750);assert.equal(await p.evaluate(()=>refreshes),0);await p.evaluate(()=>{snapshot({characterId:99,characterEnrichmentRunID:99,status:'Completed'});snapshot({characterId:5,characterEnrichmentRunID:11,status:'Running'});snapshot({characterId:5,characterEnrichmentRunID:11,status:'Completed'});snapshot({characterId:5,characterEnrichmentRunID:11,status:'Completed'});});await p.waitForFunction(()=>refreshes===1);await p.evaluate(()=>{reconnect();snapshot({characterId:5,characterEnrichmentRunID:12,status:'Completed'});});await p.waitForFunction(()=>refreshes===2);await p.waitForTimeout(750);assert.equal(await p.evaluate(()=>refreshes),2);assert.equal(await p.locator('[data-character-analysis-status]').innerText(),'Completed');console.log('PASS Character enrichment: completed replay is silent, unrelated/old runs ignored, each later completed run refreshes persisted workspace once; no full-page navigation or AI work.');}finally{await b.close();}})().catch(e=>{console.error(e);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/character-workspace-live.cjs b/PlotLine.Tests/Browser/character-workspace-live.cjs new file mode 100644 index 00000000..0309a3d9 --- /dev/null +++ b/PlotLine.Tests/Browser/character-workspace-live.cjs @@ -0,0 +1,10 @@ +// Explicit Development-only opt-in. Creates its own disposable character and relationship. +const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'); +(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));const b=await chromium.launch();let step='login';try{const c=await b.newContext({viewport:{width:1366,height:1000}}),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());await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]); +step='new isolated character and Supporting default';await p.goto('https://dev.plotdirector.com/Characters/Create?projectId='+s.project);assert.equal(await p.locator('[name=CharacterImportance]').inputValue(),'6');const fixtureName='Workspace qualification '+Date.now();await p.locator('[name=CharacterName]').fill(fixtureName);await Promise.all([p.waitForURL(/\/Characters\/Details\/\d+/),p.locator('button[type=submit]').filter({hasText:'Save character'}).click()]);const id=Number(new URL(p.url()).pathname.split('/').at(-1));assert(!s.characters.includes(id));await p.locator('[data-character-tab-content="overview"]').waitFor(); +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='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);const row=p.locator('[data-workspace-relationship]').filter({hasText:'Disposable workspace qualification definition'});await row.waitFor();const rid=Number(await row.getAttribute('data-workspace-relationship'));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'});await p.click('[data-character-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-character-graph-status]').textContent!=='Loading recorded relationships…'); +step='archive only this newly created fixture character';await p.locator('.character-workspace-header .dropdown-toggle').click();p.once('dialog',d=>d.accept());await p.locator('.character-workspace-header form[action*="Archive"] button').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; 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();}})(); diff --git a/PlotLine.Tests/Browser/character-workspace.cjs b/PlotLine.Tests/Browser/character-workspace.cjs new file mode 100644 index 00000000..2d5c7e07 --- /dev/null +++ b/PlotLine.Tests/Browser/character-workspace.cjs @@ -0,0 +1,15 @@ +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¬es='+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"]'); + 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='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); + 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='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='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();}})(); diff --git a/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs b/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs new file mode 100644 index 00000000..fccf50e5 --- /dev/null +++ b/PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Mvc.Rendering; +using PlotLine.Models; +using PlotLine.Services.Context; +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 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;} + 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 ContextFamilyTree Family(int focus,int[] expanded,bool removed=false) + { + var links=new List{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(); + var people=new[]{1,3,4,5,6,8,11,12,13}.Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id==5?"A character with a long established canonical name":id==6?"Recorded child":id==8?"Recorded partner":"Recorded relative "+id}).ToArray();var topology=new ContextFamilyTopology(links);var visible=topology.Visible(focus,expanded);var graph=new ContextLensGraph("family",focus,null,0,"Author reference",true,visible.Truncated,people.Where(c=>visible.People.Contains(c.CharacterID)).Select(c=>new ContextLensNode(c.CharacterID,c.CharacterName,c.BirthDate,c.IsArchived,false,null,c.IsDeceased)).ToArray(),links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).Select(r=>new ContextLensLink(r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID,r.RelationshipTypeName,r.RelationshipCategoryName,"Established",r.IsReciprocal,true,null,null,null,r.Notes,[])).ToArray());return new(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People)); + } +} diff --git a/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs b/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs new file mode 100644 index 00000000..6672bb95 --- /dev/null +++ b/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs @@ -0,0 +1,28 @@ +using System.Data;using System.Text.Json;using Dapper;using Microsoft.Data.SqlClient; + +internal static class CharacterWorkspaceDatabaseTests +{ + public static async Task Run(string scopePath) + { +var settings=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));var builder=new SqlConnectionStringBuilder(settings[(settings.IndexOf('=')+1)..].Trim().Trim('"','\''));if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Wrong configured database");await using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");var scope=JsonDocument.Parse(File.ReadAllText(scopePath)).RootElement;int project=scope.GetProperty("project").GetInt32(),owner=scope.GetProperty("user").GetInt32(),scene=scope.GetProperty("scene").GetInt32(),book=scope.GetProperty("book").GetInt32(),actor=scope.GetProperty("characters")[0].GetInt32(); +if(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.ProjectUserAccess a JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE a.ProjectID=@project AND a.UserID=@owner AND a.IsActive=1 AND a.AccessRole=N'Owner' AND u.Email LIKE N'pwa-browser-%'",new{project,owner})!=1)throw new Exception("Explicitly disposable Development scope required"); +int parent=await db.ExecuteScalarAsync("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Parent'"),childType=await db.ExecuteScalarAsync("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Child'"),friend=await db.ExecuteScalarAsync("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'"),state=await db.ExecuteScalarAsync("SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates ORDER BY SortOrder,RelationshipStateID"); +void Check(bool ok,string text){if(!ok)throw new Exception(text);Console.WriteLine("PASS Development workspace SQL: "+text);} +async Task NewCharacter(SqlTransaction tx)=>await db.QuerySingleAsync("dbo.Character_Save",new{ProjectID=project,CharacterName="Isolated workspace regression "+Guid.NewGuid().ToString("N")},tx,commandType:CommandType.StoredProcedure); +async Task Rel(SqlTransaction tx,int child,bool reciprocal=false,int? type=null,bool reverse=false)=>await db.QuerySingleAsync("dbo.Relationship_Save",new{ProjectID=project,CharacterAID=reverse?child:actor,CharacterBID=reverse?actor:child,RelationshipTypeID=type??parent,IsPermanent=true,IsKnownToReader=false,IsInitialRelationship=true,InitialRelationshipStateID=state,IsReciprocal=reciprocal,Notes="Synthetic definition"},tx,commandType:CommandType.StoredProcedure); +async Task Event(SqlTransaction tx,int r,string description="Synthetic event")=>await db.QuerySingleAsync("dbo.RelationshipEvent_Save",new{CharacterRelationshipID=r,SceneID=scene,RelationshipStateID=state,Intensity=4,IsKnownToOtherCharacter=false,Description=description},tx,commandType:CommandType.StoredProcedure); +async Task<(string Version,int Events,int Other)> Frame(SqlTransaction tx,int r,int? e=null){using var rows=await db.QueryMultipleAsync("dbo.CharacterWorkspace_RelationshipFrame",new{CharacterID=actor,UserID=owner,RelationshipID=r,EventID=e},tx,commandType:CommandType.StoredProcedure);var row=(IDictionary)(await rows.ReadAsync()).Single();await rows.ReadAsync();return((string)row["Version"],(int)row["EventCount"],(int)row["OtherPairRecords"]);} +async Task Change(SqlTransaction tx,int r,string version,string action,bool confirmed=true,int? e=null,string notes="Updated isolated definition",int? user=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=user??owner,RelationshipID=r,Version=version,Action=action,Confirmed=confirmed,EventID=e,Notes=notes,StateID=state,Intensity=6,Awareness=true},tx,commandType:CommandType.StoredProcedure); +async Task Case(string name,Func action){using var tx=db.BeginTransaction();try{await action(tx);}finally{try{tx.Rollback();}catch(InvalidOperationException){}}Console.WriteLine("PASS rolled back isolated case: "+name);} +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("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsArchived=1",new{r},tx)==1&&await db.ExecuteScalarAsync("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("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("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("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("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("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("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE RelationshipEventID=@other",new{other},tx)==1&&await db.ExecuteScalarAsync("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"single-event deletion leaves the other event and definition active");}); +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");}}); +await Case("protected source event",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c),e=await Event(tx,r);await db.ExecuteAsync("INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState) VALUES(@book,NEWID(),'Relationship',@e,1,N'Verified')",new{book,e},tx);var frame=await Frame(tx,r,e);try{await Change(tx,r,frame.Version,"event-remove",e:e);throw new Exception("Protected deletion accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"evidence-linked event is blocked before canonical deletion");}}); +Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.Characters WHERE CharacterName LIKE N'Isolated workspace regression %'")==0,"all new character/relationship/event fixtures rolled back; no manuscript relationships changed"); + + } +} diff --git a/PlotLine.Tests/CharacterWorkspaceTests.cs b/PlotLine.Tests/CharacterWorkspaceTests.cs new file mode 100644 index 00000000..f3b717b4 --- /dev/null +++ b/PlotLine.Tests/CharacterWorkspaceTests.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.SignalR;using Microsoft.Extensions.Logging.Abstractions; +using PlotLine.Data;using PlotLine.Hubs;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels; +internal static class CharacterWorkspaceTests +{ + public static async Task Run() + { + void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS main Character workspace: "+message);} + var role="Owner";int records=0,galleries=0,changes=0,aliases=0;bool protectedEvent=false;var version=new string('A',64); + var character=new Character{CharacterID=5,ProjectID=7,CharacterName="Canonical identity",CharacterImportance=6,AgeAtSeriesStart=25}; + var definitions=new RelationshipMapData{Books=[new(){BookID=12,SortOrder=1}],Chapters=[new(){ChapterID=10,BookID=12,SortOrder=1}],Scenes=[new(){SceneID=90,ChapterID=10,SceneNumber=1},new(){SceneID=22,ChapterID=10,SceneNumber=2},new(){SceneID=2,ChapterID=10,SceneNumber=3}],Relationships=[new(){CharacterRelationshipID=9,ProjectID=7,CharacterAID=5,CharacterBID=6,RelationshipTypeName="Parent",RelationshipCategoryName="Family",IsInitialRelationship=true,InitialRelationshipStateName="Before"},new(){CharacterRelationshipID=11,ProjectID=7,CharacterAID=5,CharacterBID=7,RelationshipTypeName="Friend",RelationshipCategoryName="Friendship",StartSceneID=2}],RelationshipEvents=[new(){RelationshipEventID=1,CharacterRelationshipID=9,SceneID=22,RelationshipStateName="Now"},new(){RelationshipEventID=2,CharacterRelationshipID=9,SceneID=2,RelationshipStateName="Later",Description="Future notes"}]}; + var reader=NativeWorkflowTests.Proxy((name,a)=>name switch{ + "Summary"=>Task.FromResult((new CharacterWorkspaceCounts{Relationships=2,Appearances=70},(IReadOnlyList)Array.Empty())), + "Records"=>Read((CharacterWorkspaceQuery)a![2]!),"Gallery"=>Gallery(),"Relationships"=>Task.FromResult((2,definitions)), + "Frame"=>Task.FromResult((new CharacterRelationshipFrame{Relationship=definitions.Relationships[0],Version=version,EventCount=3,OtherPairRecords=1},a![3] is int eid?new CharacterWorkspaceEvent{Record=new(){RelationshipEventID=eid,SceneID=22,CharacterRelationshipID=9},ProtectedSource=protectedEvent}:null)), + "Change"=>Changed(),_=>throw new Exception(name)}); + Task<(int,IReadOnlyList)> Read(CharacterWorkspaceQuery q){records++;return Task.FromResult((1,(IReadOnlyList)new[]{new CharacterWorkspaceEntry{ID=1,SceneID=q.SceneID??22,Heading="Recorded source",BookTitle="Book",Kind=q.Tab}}));} + Task<(int,IReadOnlyList)> Gallery(){galleries++;return Task.FromResult((0,(IReadOnlyList)Array.Empty()));}Task Changed(){changes++;return Task.CompletedTask;} + var repo=NativeWorkflowTests.Proxy((n,a)=>n switch{"GetCharacterAsync"=>Task.FromResult((int)a![0]! ==99?null:character),"GetReferenceCharacterAsync"=>Task.FromResult(character),"ListAliasesAsync"=>Alias(),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData()),_=>throw new Exception("Unexpected eager read: "+n)}); + Task> Alias(){aliases++;return Task.FromResult>(Enumerable.Range(1,75).Select(i=>new CharacterAlias{CharacterID=5,Alias="Alias "+i}).ToArray());} + var client=NativeWorkflowTests.Proxy((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy((_,_)=>client);var hub=NativeWorkflowTests.Proxy>((_,_)=>clients); + var workspace=new CharacterWorkspace(repo,NativeWorkflowTests.Proxy((n,_)=>n=="GetForUserAsync"?Task.FromResult(new(){ProjectID=7,ProjectName="Author project",AccessRole=role}):throw new Exception("Unscoped project read")),NativeWorkflowTests.Proxy((_,_)=>Task.FromResult>([])),NativeWorkflowTests.Proxy((_,_)=>4),NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(null)),reader,NativeWorkflowTests.Proxy((_,_)=>throw new Exception("Unexpected graph/history read")),null!,new ContextWorkspaceNotifications(hub,NullLogger.Instance),NativeWorkflowTests.Proxy((_,_)=>Task.CompletedTask),NativeWorkflowTests.Proxy((_,_)=>throw new Exception("Legacy full-detail service called"))); + var header=await workspace.Header(5,null,CancellationToken.None);Check(records==0&&galleries==0&&aliases==0&&header.Character.CharacterName=="Canonical identity","shell loads only identity, scoped project, counts/age candidates and persisted enrichment status"); + var overview=await workspace.Page(5,new(){Tab="overview"},CancellationToken.None);Check(records==1&&galleries==1&&aliases==1&&overview.Profile.Aliases.Count==50&&overview.Entries.Count<=3,"Overview is bounded; it does not load full character/project histories"); + var page=await workspace.Page(5,new(){Tab="relationships",SceneID=22},CancellationToken.None);Check(page.Relationships.Single(r=>r.Relationship.CharacterRelationshipID==9).CurrentStateName=="Now"&&!page.Relationships[0].Events.Any(e=>e.SceneID==2),"selected-point relationship state and displayed history exclude future events using canonical ordering");Check(page.Relationships.Single(r=>r.Relationship.CharacterRelationshipID==11).CurrentStateName=="Not established / ended at this point","later definitions stay identifiable as author records without pretending to exist at the selected point"); + Check(CharacterWorkspace.Classification(10)=="Major"&&CharacterWorkspace.Classification(6)=="Supporting"&&CharacterWorkspace.Classification(2)=="Minor"&&CharacterWorkspace.Classification(null)=="Unclassified"&&character.CharacterImportance==6,"classification labels preserve explicit values and do not reclassify existing records"); + foreach(var q in new[]{new CharacterWorkspaceQuery{Tab="unknown"},new(){Tab="evolution",Page=0},new(){Tab="knowledge",Search=new string('x',121)}}){try{await workspace.Page(5,q,CancellationToken.None);throw new Exception("Invalid query accepted");}catch(ArgumentException){Check(true,"closed tabs and bounded query criteria reject invalid requests");}} + var op=await workspace.Operation(5,9,null,"archive",CancellationToken.None);Check(op.Record.EventCount==3&&op.Record.OtherPairRecords==1,"removal preview exposes retained dependencies and separate pair records");op.Confirmed=true;op.Version=new string('B',64);try{await workspace.Change(op,CancellationToken.None);throw new Exception("Stale accepted");}catch(InvalidOperationException){Check(changes==0,"stale form is rejected before canonical mutation");} + op.Version=version;op.Confirmed=false;try{await workspace.Change(op,CancellationToken.None);throw new Exception("Unconfirmed removal");}catch(ArgumentException){Check(changes==0,"destructive definition removal requires explicit confirmation");} + protectedEvent=true;var evt=await workspace.Operation(5,9,1,"event-remove",CancellationToken.None);evt.Confirmed=true;try{await workspace.Change(evt,CancellationToken.None);throw new Exception("Protected source accepted");}catch(ArgumentException){Check(changes==0,"source/review-linked event cannot be removed or orphaned by focused operations");} + role="Viewer";try{await workspace.Operation(5,9,null,"definition",CancellationToken.None);throw new Exception("Viewer edit accepted");}catch(UnauthorizedAccessException){Check(changes==0,"Viewer cannot open or execute an editing operation");} + var viewer=await workspace.Header(5,null,CancellationToken.None);Check(!viewer.WorkspaceCanEdit,"Viewer header stays read-only");try{await workspace.Header(99,null,CancellationToken.None);throw new Exception("Unknown accepted");}catch(UnauthorizedAccessException){Check(true,"unavailable character rejected before reading histories");} + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 96f35918..6189d0da 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -182,6 +182,8 @@ if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text. if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;} +if(args.Contains("--character-workspace-database")){await CharacterWorkspaceDatabaseTests.Run(args.Last());return;} +if(args.Contains("--character-workspace")){await CharacterWorkspaceTests.Run();return;} if(args.Contains("--context-family")){ContextFamilyTests.Run();return;} if(args.Contains("--context-lenses")){await ContextRelationshipLensTests.Run();return;} if(args.Contains("--context-names")){await ContextNamesTests.Run();return;} @@ -191,6 +193,7 @@ if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;} var tests = new (string Name, Action Test)[] { + ("Main Character workspace lazy reads and safe management",()=>CharacterWorkspaceTests.Run().GetAwaiter().GetResult()), ("Scene family identification and branch exploration",ContextFamilyTests.Run), ("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()), ("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()), @@ -1605,7 +1608,8 @@ static void CharacterDetailEnrichmentStatusUsesScopedSignalR() { var root = PlotLineRoot(); var viewModel = File.ReadAllText(Path.Combine(root, "ViewModels/CoreViewModels.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/Characters/_WorkspaceProfile.cshtml")); var hub = File.ReadAllText(Path.Combine(root, "Hubs/StoryIntelligenceHub.cs")); var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/character-enrichment-detail.js")); var models = File.ReadAllText(Path.Combine(root, "Models/CharacterEnrichmentModels.cs")); @@ -1619,7 +1623,7 @@ static void CharacterDetailEnrichmentStatusUsesScopedSignalR() Assert(models.Contains("public int? CharacterID { get; init; }", StringComparison.Ordinal), "SignalR progress event should include character scope."); Assert(script.Contains("CharacterEnrichmentProgressChanged", StringComparison.Ordinal) && script.Contains("Number(snapshot.characterID || snapshot.characterId || 0) !== characterId", StringComparison.Ordinal), "Character detail script should ignore unrelated enrichment events."); - Assert(script.Contains("window.location.reload()", StringComparison.Ordinal), "Character detail should refresh displayed generated details after completion."); + Assert(script.Contains("character-analysis-updated", StringComparison.Ordinal), "Character workspace should refresh persisted generated details after completion without reloading its shell."); Assert(migration.Contains("LastAnalysedUtc = @LastAnalysedUtc", StringComparison.Ordinal), "Last analysed should come only from a successful completed enrichment run."); Assert(migration.Contains("Status = COALESCE((SELECT TOP (1) Status FROM @Attempt)", StringComparison.Ordinal), "Failed latest attempts should remain visible and retryable."); } @@ -6277,7 +6281,8 @@ static void EntityPreferredNamesArePeerAliases() var services = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs")); var characterController = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs")); var locationController = File.ReadAllText(Path.Combine(root, "Controllers/LocationsController.cs")); - var characterDetails = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")); + var characterDetails = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + + File.ReadAllText(Path.Combine(root, "Views/Characters/_WorkspaceProfile.cshtml")); var characterEdit = File.ReadAllText(Path.Combine(root, "Views/Characters/Edit.cshtml")); var locationDetails = File.ReadAllText(Path.Combine(root, "Views/Locations/Details.cshtml")); var locationEdit = File.ReadAllText(Path.Combine(root, "Views/Locations/Edit.cshtml")); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index ead6c8b6..f05210b3 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -206,6 +206,10 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(FixtureProxy((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((_,_)=>throw new NotSupportedException())); + builder.Services.AddSingleton(FixtureProxy((_,_)=>throw new NotSupportedException())); + builder.Services.AddSingleton(FixtureProxy((_,_)=>throw new NotSupportedException())); + builder.Services.AddSingleton(FixtureProxy((name,_)=>name=="GetCurrentForCharacterAsync"?Task.FromResult(null):throw new NotSupportedException(name))); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -410,6 +414,17 @@ 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("/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); + }); + app.MapGet("/character-workspace-tab-fixture",async context=>{ + int? Number(string key)=>int.TryParse(context.Request.Query[key],out var value)?value:null;var q=new CharacterWorkspaceQuery{Tab=context.Request.Query["Tab"].FirstOrDefault()??"overview",Page=Number("Page")??1,SceneID=Number("SceneID"),BookID=Number("BookID"),RelationshipID=Number("RelationshipID"),Search=context.Request.Query["Search"],Category=context.Request.Query["Category"]};var model=CharacterWorkspaceBrowserFixture.Page(Number("id")??5,q,context.Request.Query["viewer"]=="true",context.Request.Query["removed"]=="true",context.Request.Query["notes"].FirstOrDefault());await WorkspacePartial(context,"_WorkspaceTab",model); + }); + app.MapGet("/character-workspace-operation-fixture",async context=>{ + var action=context.Request.Query["operation"].FirstOrDefault()??"definition";var model=CharacterWorkspaceBrowserFixture.Operation(5,action,int.TryParse(context.Request.Query["relationshipId"],out var r)?r:9,int.TryParse(context.Request.Query["eventId"],out var e)?e:null,context.Request.Query["protected"]=="true");if(context.Request.Query["invalid"]=="true"){context.Response.StatusCode=400;model.Notes=context.Request.Query["notes"].FirstOrDefault()??model.Notes;context.Items["WorkspaceValidation"]="The record changed. Your draft is retained.";}await WorkspacePartial(context,"_WorkspaceOperation",model); + }); + app.MapGet("/character-workspace-family-fixture",context=>{var expanded=context.Request.Query["expanded"].Select(v=>int.Parse(v!)).ToArray();return context.Response.WriteAsJsonAsync(CharacterWorkspaceBrowserFixture.Family(int.TryParse(context.Request.Query["focusId"],out var f)?f:5,expanded,context.Request.Query["removed"]=="true"));}); + static async Task WorkspacePartial(HttpContext context,string partial,object model){var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Characters/"+partial+".cshtml",false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};if(context.Items["WorkspaceValidation"] is string error)data.ModelState.AddModelError("",error);await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());} app.MapGet("/context-edit-fixture",async context=>{ var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false); var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"}; @@ -750,6 +765,7 @@ internal static class ToolbarBrowserHost context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); }); + app.MapHub("/hubs/story-intelligence"); app.MapHub("/hubs/native-companion"); app.MapHub("/hubs/word-companion-follow"); await app.RunAsync(); diff --git a/PlotLine/Controllers/CharacterWorkspaceController.cs b/PlotLine/Controllers/CharacterWorkspaceController.cs new file mode 100644 index 00000000..08c356ff --- /dev/null +++ b/PlotLine/Controllers/CharacterWorkspaceController.cs @@ -0,0 +1,37 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Data.SqlClient; +using PlotLine.Services; +using PlotLine.ViewModels; +namespace PlotLine.Controllers; +[Authorize,Route("Characters/Workspace"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] +public sealed class CharacterWorkspaceController(CharacterWorkspace workspace):Controller +{ + [HttpGet("Tab/{id:int}")] + public async Task Tab(int id,[FromQuery]CharacterWorkspaceQuery query,CancellationToken ct) + {try{return PartialView("~/Views/Characters/_WorkspaceTab.cshtml",await workspace.Page(id,query,ct));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(SqlException e)when(e.Number is 51020 or 51022){return BadRequest(new{message="This character or story point is unavailable."});}} + [HttpGet("Family/{id:int}")] + public async Task Family(int id,int? focusId,[FromQuery]int[]? expanded,CancellationToken ct) + {try{return Ok(await workspace.Family(id,focusId,expanded??[],ct));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}} + [HttpGet("Story/{id:int}")] + public async Task Story(int id,int? sceneId,CancellationToken ct) + {try{return Ok(await workspace.Story(id,sceneId,ct));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}} + [HttpGet("Lookup/{id:int}")] + public async Task Lookup(int id,string? search,CancellationToken ct) + {try{return Ok(await workspace.Lookup(id,search??"",ct));}catch(UnauthorizedAccessException){return Forbid();}} + [HttpGet("Operation/{id:int}")] + public async Task Operation(int id,int relationshipId,int? eventId,string operation="definition",CancellationToken ct=default) + {try{return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",await workspace.Operation(id,relationshipId,eventId,operation,ct));}catch(UnauthorizedAccessException){return Forbid();}catch(SqlException e)when(e.Number==51020){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}} + [HttpPost("Operation/{id:int}"),ValidateAntiForgeryToken] + public async Task 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);} + } + [HttpGet("Add/{id:int}")] + public async Task Add(int id,CancellationToken ct) + {try{return PartialView("~/Views/Characters/_WorkspaceAdd.cshtml",await workspace.AddForm(id,ct));}catch(UnauthorizedAccessException){return Forbid();}} + [HttpPost("Add/{id:int}"),ValidateAntiForgeryToken] + public async Task Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct) + {try{if(!ModelState.IsValid)throw new ArgumentException("Check the relationship fields.");await workspace.Add(id,input,ct);return Ok(new{saved=true,message="Initial relationship added."});}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){var model=await workspace.AddForm(id,ct,input);ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceAdd.cshtml",model);}} +} diff --git a/PlotLine/Controllers/CharactersController.cs b/PlotLine/Controllers/CharactersController.cs index f52af703..b0c86e0a 100644 --- a/PlotLine/Controllers/CharactersController.cs +++ b/PlotLine/Controllers/CharactersController.cs @@ -26,10 +26,9 @@ public sealed class CharactersController(ICharacterService characters) : Control return model is null ? NotFound() : View(model); } - public async Task Details(int id) + public async Task Details(int id,[FromServices] CharacterWorkspace workspace,string? tab=null,int? sceneId=null,CancellationToken cancellationToken=default) { - var model = await characters.GetCharacterDetailAsync(id); - return model is null ? NotFound() : View(model); + try{var model=await workspace.Header(id,tab,cancellationToken);if(tab!=null)model.WorkspacePage=await workspace.Page(id,new(){Tab=tab,SceneID=sceneId},cancellationToken);return View(model);}catch(UnauthorizedAccessException){return NotFound();}catch(ArgumentException e){return BadRequest(e.Message);} } public async Task Merge(int id) @@ -292,10 +291,9 @@ public sealed class CharactersController(ICharacterService characters) : Control [HttpPost] [ValidateAntiForgeryToken] - public async Task ArchiveRelationship(int id, int characterId) + public IActionResult ArchiveRelationship(int id, int characterId) { - await characters.ArchiveRelationshipAsync(id); - TempData["ArchiveMessage"] = "Relationship archived. You can restore it from Archived Items."; - return RedirectToAction(nameof(Details), new { id = characterId }); + // Old bookmarked/forms enter the new explicit preview; no removal bypass. + return RedirectToAction(nameof(Details), new { id = characterId,tab="relationships",relationshipId=id,operation="archive" }); } } diff --git a/PlotLine/Data/CharacterWorkspaceReader.cs b/PlotLine/Data/CharacterWorkspaceReader.cs new file mode 100644 index 00000000..620f3cb3 --- /dev/null +++ b/PlotLine/Data/CharacterWorkspaceReader.cs @@ -0,0 +1,48 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.ViewModels; +namespace PlotLine.Data; +public sealed class WorkspaceAgeRow +{ + public int SceneID{get;set;}public int ChapterID{get;set;}public string SceneTitle{get;set;}="";public DateTime? StartDateTime{get;set;}public string? TimeModeName{get;set;}public bool IsAppearance{get;set;} + public Scene Scene=>new(){SceneID=SceneID,ChapterID=ChapterID,SceneTitle=SceneTitle,StartDateTime=StartDateTime,TimeModeName=TimeModeName??""}; +} +public interface ICharacterWorkspaceReader +{ + Task<(CharacterWorkspaceCounts Counts,IReadOnlyList Ages)> Summary(int character,int user,CancellationToken ct); + Task<(int Total,IReadOnlyList Rows)> Records(int character,int user,CharacterWorkspaceQuery query,CancellationToken ct); + Task<(int Total,RelationshipMapData Data)> Relationships(int character,int project,int user,CharacterWorkspaceQuery query,CancellationToken ct); + Task<(int Total,IReadOnlyList Images)> Gallery(int character,int user,int page,CancellationToken ct); + Task<(CharacterRelationshipFrame Relationship,CharacterWorkspaceEvent? Event)> Frame(int character,int user,int relationship,int? eventID,CancellationToken ct); + Task Change(CharacterWorkspaceOperation input,int user,CancellationToken ct); +} +public sealed class CharacterWorkspaceReader(ISqlConnectionFactory connections,IConfiguration configuration):ICharacterWorkspaceReader +{ + private sealed class Count{public int Total{get;set;}} + public async Task<(CharacterWorkspaceCounts,IReadOnlyList)> Summary(int character,int user,CancellationToken ct) + {using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Summary",new{CharacterID=character,UserID=user},commandType:CommandType.StoredProcedure,cancellationToken:ct));return(await grid.ReadSingleAsync(),(await grid.ReadAsync()).ToList());} + public async Task<(int,IReadOnlyList)> Records(int character,int user,CharacterWorkspaceQuery q,CancellationToken ct) + {using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Records",new{CharacterID=character,UserID=user,q.Tab,q.Page,Search=q.Search??"",q.BookID,q.Category,q.SceneID,q.RelationshipID},commandType:CommandType.StoredProcedure,cancellationToken:ct));return((await grid.ReadSingleAsync()).Total,(await grid.ReadAsync()).ToList());} + 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()).Total;data=new(){Books=(await grid.ReadAsync()).ToList(),Chapters=(await grid.ReadAsync()).ToList(),Scenes=(await grid.ReadAsync()).ToList(),Relationships=(await grid.ReadAsync()).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(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); + return(total,new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Relationships=data.Relationships,RelationshipEvents=events}); + } + public async Task<(int,IReadOnlyList)> Gallery(int character,int user,int page,CancellationToken ct) + {using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Gallery",new{CharacterID=character,UserID=user,Page=page},commandType:CommandType.StoredProcedure,cancellationToken:ct));return((await grid.ReadSingleAsync()).Total,(await grid.ReadAsync()).ToList());} + public async Task<(CharacterRelationshipFrame,CharacterWorkspaceEvent?)> Frame(int character,int user,int relationship,int? eventID,CancellationToken ct) + { + using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_RelationshipFrame",new{CharacterID=character,UserID=user,RelationshipID=relationship,EventID=eventID},commandType:CommandType.StoredProcedure,cancellationToken:ct)); + var definition=(await grid.ReadAsync()).Single();var json=JsonSerializer.Serialize((object)definition);var options=new JsonSerializerOptions{PropertyNameCaseInsensitive=true};var frame=JsonSerializer.Deserialize(json,options)!;frame.Relationship=JsonSerializer.Deserialize(json,options)!; + var item=(await grid.ReadAsync()).SingleOrDefault();if(item==null)return(frame,null);json=JsonSerializer.Serialize((object)item);var eventFrame=JsonSerializer.Deserialize(json,options)!;eventFrame.Record=JsonSerializer.Deserialize(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));} +} diff --git a/PlotLine/Data/ContextRelationshipReader.cs b/PlotLine/Data/ContextRelationshipReader.cs index 0d1fc5ba..4f940750 100644 --- a/PlotLine/Data/ContextRelationshipReader.cs +++ b/PlotLine/Data/ContextRelationshipReader.cs @@ -14,7 +14,7 @@ public sealed class ContextRelationshipReader(ISqlConnectionFactory connectionFa using var db=connectionFactory.CreateConnection();IReadOnlyList books;IReadOnlyList chapters;IReadOnlyList scenes;IReadOnlyList people;IReadOnlyList links;Boundary boundary; using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextRelationshipLens_Read",new{ProjectID=project,UserID=user,FocusCharacterID=focus,Lens=lens,Depth=depth,PhysicalIDs=JsonSerializer.Serialize(physical)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))){books=(await grid.ReadAsync()).ToList();chapters=(await grid.ReadAsync()).ToList();scenes=(await grid.ReadAsync()).ToList();people=(await grid.ReadAsync()).ToList();links=(await grid.ReadAsync()).ToList();boundary=await grid.ReadSingleAsync();} if(books.Count>20000||chapters.Count>20000||scenes.Count>20000)throw new ArgumentException("This project exceeds the Context narrative-order limit. Use the full Relationships Editor."); - var order=StoryStateService.OrderScenes(new(){Books=books,Chapters=chapters,Scenes=scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var at=lens=="family"?order.Count-1:order.FirstOrDefault(s=>s.SceneID==scene)?.Ordinal??-1; + var order=StoryStateService.OrderScenes(new(){Books=books,Chapters=chapters,Scenes=scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var at=lens=="family"||scene==0?order.Count-1:order.FirstOrDefault(s=>s.SceneID==scene)?.Ordinal??-1; var changes=(await db.QueryAsync(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(links.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=at},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList(); await ParagraphEvidenceProjection.Apply(db,configuration,changes); return new(new(){Books=books,Chapters=chapters,Scenes=scenes,Characters=people,Relationships=links,RelationshipEvents=changes},boundary.FocusCharacterID,boundary.Truncated); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index ba0d57b6..27655749 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -298,6 +298,8 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Services/CharacterWorkspace.cs b/PlotLine/Services/CharacterWorkspace.cs new file mode 100644 index 00000000..59e83936 --- /dev/null +++ b/PlotLine/Services/CharacterWorkspace.cs @@ -0,0 +1,67 @@ +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.Data.SqlClient; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services.Context; +using PlotLine.ViewModels; +namespace PlotLine.Services; +public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectRepository projects,IBookRepository books,ICurrentUserService user,ICharacterEnrichmentService enrichment,ICharacterWorkspaceReader reader,IContextRelationshipReader graphReader,ContextFamilyExploration families,ContextWorkspaceNotifications notifications,IProjectActivityService activity,ICharacterService canonical) +{ + public static readonly string[] Tabs=["overview","relationships","evolution","appearances","knowledge"]; + public static string Classification(int? importance)=>importance switch{>=8=>"Major",>=4=>"Supporting",>=1=>"Minor",_=>"Unclassified"}; + public async Task<(Character Character,Project Project,bool CanEdit)> Scope(int id) + { + 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.");} + public async Task 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()); + return new(){Character=scope.Character,Project=scope.Project,WorkspaceCanEdit=scope.CanEdit,WorkspaceTab=tab,WorkspaceCounts=summary.Counts,DisplayAge=age.DisplayText,AgeContext=age.Context,AgeReferenceScene=age.ReferenceScene,CharacterAnalysis=await enrichment.GetCharacterStatusAsync(id,user.UserId.Value)??new(){CharacterID=id}}; + } + public async Task Page(int id,CharacterWorkspaceQuery q,CancellationToken ct) + { + Validate(q);var header=await Header(id,q.Tab is "gallery" or "history" or "scenes"?null:q.Tab,ct);var page=new CharacterWorkspacePage{Profile=header,Query=q}; + if(q.SceneID.HasValue){var point=(await reader.Records(id,user.UserId!.Value,new(){Tab="point",SceneID=q.SceneID},ct)).Rows.SingleOrDefault();if(point==null)throw new UnauthorizedAccessException();page.PointLabel=$"{point.BookDisplayTitle} · Ch {point.ChapterNumber} · Scene {point.SceneNumber}: {point.SceneTitle}";} + if(q.Tab=="overview"){ + header.Aliases=(await characters.ListAliasesAsync(id)).Take(50).ToArray();var gallery=await reader.Gallery(id,user.UserId!.Value,1,ct);page.Images=gallery.Images; + var records=await reader.Records(id,user.UserId.Value,q,ct);page.Entries=records.Rows.Take(3).ToArray(); + }else if(q.Tab=="gallery"){var gallery=await reader.Gallery(id,user.UserId!.Value,q.Page,ct);page.Total=gallery.Total;page.Images=gallery.Images;} + else if(q.Tab=="relationships"){ + var result=await reader.Relationships(id,header.Project.ProjectID,user.UserId!.Value,q,ct);var order=StoryStateService.OrderScenes(new(){Books=result.Data.Books,Chapters=result.Data.Chapters,Scenes=result.Data.Scenes}).Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i); + var projected=q.SceneID.HasValue?RelationshipMapService.BuildAtScene(result.Data,order,q.SceneID.Value).ToDictionary(r=>r.CharacterRelationshipID):null; + page.Total=result.Total;page.Relationships=result.Data.Relationships.Select(r=>{var events=result.Data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==r.CharacterRelationshipID&&e.EvidenceState=="Verified"&&(!q.SceneID.HasValue||order.GetValueOrDefault(e.SceneID,int.MaxValue)<=order.GetValueOrDefault(q.SceneID.Value,-1))).OrderBy(e=>order.GetValueOrDefault(e.SceneID,-1)).ThenBy(e=>e.CreatedDate).ThenBy(e=>e.RelationshipEventID).ToArray();return new CurrentRelationshipViewModel{Relationship=r,Events=events,LatestEvent=q.SceneID.HasValue?(projected!.TryGetValue(r.CharacterRelationshipID,out var p)?new(){RelationshipStateName=p.CurrentStateName,Intensity=p.CurrentIntensity,Description=p.Notes}:new(){RelationshipStateName="Not established / ended at this point",Description="Author definition; no established selected-point state."}):events.LastOrDefault()};}).ToArray(); + }else{var result=await reader.Records(id,user.UserId!.Value,q,ct);page.Total=result.Total;page.Entries=result.Rows;} + if(q.Tab is not ("overview" or "gallery"))page.Books=(await books.ListByProjectAsync(header.Project.ProjectID)).Take(2000).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();return page; + } + public async Task Family(int id,int? focus,int[] expanded,CancellationToken ct) + {var scope=await Scope(id);return await families.ReadProjectTree(scope.Project.ProjectID,user.UserId!.Value,focus??id,new(){SceneID=0,ChapterID=0,SceneTitle="Author family reference"},scope.CanEdit,expanded,ct);} + public async Task Story(int id,int? sceneId,CancellationToken ct) + { + var scope=await Scope(id);var data=await graphReader.Read(scope.Project.ProjectID,user.UserId!.Value,sceneId??0,id,"story",3,[],ct);var order=StoryStateService.OrderScenes(new(){Books=data.Data.Books,Chapters=data.Data.Chapters,Scenes=data.Data.Scenes}).ToArray(); + // An omitted point means the last canonical scene, explicitly labelled as author reference. + var selected=sceneId.HasValue?order.SingleOrDefault(s=>s.SceneID==sceneId):order.LastOrDefault();if(sceneId.HasValue&&selected==null)throw new UnauthorizedAccessException(); + if(selected==null)return new("story",id,null,0,"No narrative scene recorded",scope.CanEdit,data.Truncated,[new(id,scope.Character.CharacterName,scope.Character.BirthDate,scope.Character.IsArchived,false,null)],[]); + return ContextRelationshipLenses.Compose(data,"story",new(){SceneID=selected.SceneID,ChapterID=selected.ChapterID,SceneTitle=selected.SceneTitle},scope.CanEdit); + } + public async Task> Lookup(int id,string search,CancellationToken ct) + {var scope=await Scope(id);if(search.Length is <2 or >120)return [];return (await graphReader.Lookup(scope.Project.ProjectID,user.UserId!.Value,search,ct)).Select(c=>(object)new{id=c.CharacterID,name=c.CharacterName}).ToArray();} + public async Task Operation(int id,int relationship,int? eventID,string action,CancellationToken ct) + { + 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()}; + } + public async Task Change(CharacterWorkspaceOperation input,CancellationToken ct) + { + var frame=await Operation(input.CharacterID,input.RelationshipID,input.EventID,input.Action,ct);if(input.Version!=frame.Version)throw new InvalidOperationException("This relationship or its history changed. Cancel and reopen to review current values.");if(input.Action is "archive" or "event-remove"&&!input.Confirmed)throw new ArgumentException("Confirm the identified removal.");if(input.Notes?.Length>4000||input.Intensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity."); + if(input.Action.StartsWith("event-")&&frame.Event?.ProtectedSource==true)throw new ArgumentException("This event has source/review dependencies. Manage it through its source workflow."); + try{await reader.Change(input,user.UserId!.Value,ct);}catch(SqlException ex)when(ex.Number==51020){throw new UnauthorizedAccessException();}catch(SqlException ex)when(ex.Number==51021){throw new InvalidOperationException(ex.Message);}catch(SqlException ex)when(ex.Number==51022){throw new ArgumentException(ex.Message);} + var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID); + } + public async Task AddForm(int id,CancellationToken ct,InitialRelationshipEditViewModel? input=null) + {var model=await Header(id,null,ct);if(!model.WorkspaceCanEdit)throw new UnauthorizedAccessException();var lookup=await characters.GetLookupsAsync(model.Project.ProjectID);model.RelationshipTypeOptions=lookup.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray();model.RelationshipStateOptions=lookup.RelationshipStates.Select(t=>new SelectListItem(t.StateName,t.RelationshipStateID.ToString())).ToArray();model.BookOptions=(await books.ListByProjectAsync(model.Project.ProjectID)).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();if(input!=null){model.NewInitialRelationship=input;var target=await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value);if(target?.ProjectID==model.Project.ProjectID)model.CharacterOptions=[new(target.CharacterName,target.CharacterID.ToString())];}return model;} + public async Task Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct) + {var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID);} +} diff --git a/PlotLine/Services/Context/ContextFamilyExploration.cs b/PlotLine/Services/Context/ContextFamilyExploration.cs index bc4026ad..3e99d395 100644 --- a/PlotLine/Services/Context/ContextFamilyExploration.cs +++ b/PlotLine/Services/Context/ContextFamilyExploration.cs @@ -75,12 +75,17 @@ public sealed class ContextFamilyExploration(ContextRelationshipLenses lenses,IC public async Task Tree(int book,int scene,int focus,IReadOnlyList expanded,CancellationToken cancellationToken) { var scope=await lenses.Scope(book,scene);var author=user.UserId!.Value;if((await characters.GetReferenceCharacterAsync(focus,author))?.ProjectID!=scope.Book.ProjectID)throw new UnauthorizedAccessException(); - var structure=await reader.Structure(scope.Book.ProjectID,author,Seeds(scope.Scene,focus),cancellationToken);var topology=new ContextFamilyTopology(structure.Links);var visible=topology.Visible(focus,expanded);var data=await reader.Tree(scope.Book.ProjectID,author,visible.People,visible.Links,cancellationToken); + return await ReadProjectTree(scope.Book.ProjectID,author,focus,scope.Scene,scope.CanEdit,expanded,cancellationToken); + } + public async Task ReadProjectTree(int project,int author,int focus,SceneEditViewModel scene,bool canEdit,IReadOnlyList expanded,CancellationToken cancellationToken) + { + if((await characters.GetReferenceCharacterAsync(focus,author))?.ProjectID!=project)throw new UnauthorizedAccessException(); + var structure=await reader.Structure(project,author,Seeds(scene,focus),cancellationToken);var topology=new ContextFamilyTopology(structure.Links);var visible=topology.Visible(focus,expanded);var data=await reader.Tree(project,author,visible.People,visible.Links,cancellationToken); // Re-check the returned records: a concurrent edit must not leave disconnected // physical participants in the chosen tree after an edge changed semantics. var current=new ContextFamilyTopology(data.Relationships);var reachable=new HashSet{focus};var pending=new Queue();pending.Enqueue(focus);while(pending.TryDequeue(out var id))foreach(var adjacent in current.Adjacent(id))if(reachable.Add(adjacent))pending.Enqueue(adjacent); var safe=new RelationshipMapData{Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters.Where(c=>reachable.Contains(c.CharacterID)).ToList(),Relationships=current.Links.Where(r=>reachable.Contains(r.CharacterAID)&&reachable.Contains(r.CharacterBID)).ToList(),RelationshipEvents=data.RelationshipEvents}; - var graph=ContextRelationshipLenses.Compose(new(safe,focus,visible.Truncated),"family",scope.Scene,scope.CanEdit); + var graph=ContextRelationshipLenses.Compose(new(safe,focus,visible.Truncated),"family",scene,canEdit); // Unlike Story, Family contains only the chosen genealogical component, including isolated focus. return new(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People)); } diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index cd2c7f98..ba7293e3 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -10134,7 +10134,8 @@ public sealed class CharacterService( characterId = await characters.SaveCharacterAsync(new Character { ProjectID = model.ReturnProjectID.Value, - CharacterName = model.NewCharacterName.Trim() + CharacterName = model.NewCharacterName.Trim(), + CharacterImportance = 2 }); await activity.RecordAsync(model.ReturnProjectID.Value, "Created", "Character", characterId, model.NewCharacterName.Trim()); } diff --git a/PlotLine/Sql/306_CharacterWorkspaceReads.sql b/PlotLine/Sql/306_CharacterWorkspaceReads.sql new file mode 100644 index 00000000..835ba94d --- /dev/null +++ b/PlotLine/Sql/306_CharacterWorkspaceReads.sql @@ -0,0 +1,105 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- Ordering mirrors StoryStateService.OrderScenes. Metadata only; no manuscript text. +CREATE OR ALTER FUNCTION dbo.CharacterWorkspace_SceneOrder(@ProjectID int) +RETURNS TABLE AS RETURN + SELECT s.SceneID,s.ChapterID,s.SceneTitle,s.SceneNumber,s.StartDateTime,s.POVCharacterID,tm.TimeModeName, + ch.BookID,ch.ChapterNumber,b.BookTitle,b.Subtitle AS BookSubtitle, + ROW_NUMBER() OVER(ORDER BY ISNULL(b.SortOrder,0),b.BookNumber,ISNULL(ch.SortOrder,0),ch.ChapterNumber,ISNULL(s.SortOrder,0),s.SceneNumber,s.SceneID)-1 AS Ordinal + FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID LEFT JOIN dbo.TimeModes tm ON tm.TimeModeID=s.TimeModeID + WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND ch.IsArchived=0 AND s.IsArchived=0; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Summary @CharacterID int,@UserID int +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; + SELECT (SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE ProjectID=@project AND IsArchived=0 AND (CharacterAID=@CharacterID OR CharacterBID=@CharacterID)) Relationships, + (SELECT COUNT(*) FROM dbo.SceneCharacters sc JOIN dbo.CharacterWorkspace_SceneOrder(@project) o ON o.SceneID=sc.SceneID WHERE sc.CharacterID=@CharacterID) Appearances, + (SELECT COUNT(*) FROM dbo.CharacterAttributeEvents WHERE CharacterID=@CharacterID) Attributes, + (SELECT COUNT(*) FROM dbo.CharacterKnowledge WHERE CharacterID=@CharacterID) Knowledge, + (SELECT COUNT(*) FROM dbo.CharacterImages WHERE CharacterID=@CharacterID AND IsDeleted=0) Images, + (SELECT TOP(1) o.SceneID FROM dbo.CharacterWorkspace_SceneOrder(@project) o JOIN dbo.SceneCharacters sc ON sc.SceneID=o.SceneID WHERE sc.CharacterID=@CharacterID ORDER BY o.Ordinal) FirstSceneID; + SELECT o.*,CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.SceneCharacters sc WHERE sc.CharacterID=@CharacterID AND sc.SceneID=o.SceneID) THEN 1 ELSE 0 END AS bit) IsAppearance + FROM dbo.CharacterWorkspace_SceneOrder(@project) o WHERE o.SceneID=(SELECT AgeReferenceSceneID FROM dbo.Characters WHERE CharacterID=@CharacterID) + OR o.SceneID=(SELECT TOP(1) x.SceneID FROM dbo.CharacterWorkspace_SceneOrder(@project) x JOIN dbo.SceneCharacters sc ON sc.SceneID=x.SceneID JOIN dbo.Characters c ON c.CharacterID=sc.CharacterID WHERE sc.CharacterID=@CharacterID AND x.TimeModeName IN(N'Exact Date',N'Exact DateTime',N'Exact Date and Time') AND x.StartDateTime IS NOT NULL AND (c.BirthDate IS NULL OR x.StartDateTime>=c.BirthDate) ORDER BY x.Ordinal) + ORDER BY o.Ordinal; +END; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Records @CharacterID int,@UserID int,@Tab nvarchar(20),@Page int=1,@Search nvarchar(120)=N'',@BookID int=NULL,@Category nvarchar(100)=NULL,@SceneID int=NULL,@RelationshipID int=NULL +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 @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'%',@maximum bigint=NULL; + SELECT * INTO #Order FROM dbo.CharacterWorkspace_SceneOrder(@project);CREATE UNIQUE CLUSTERED INDEX IX_Order ON #Order(SceneID); + IF @SceneID IS NOT NULL BEGIN SELECT @maximum=Ordinal FROM #Order WHERE SceneID=@SceneID;IF @maximum IS NULL THROW 51022,'Scene unavailable in this project',1;END; + CREATE TABLE #Rows(Kind nvarchar(20),ID int,SceneID int NULL,RelationshipID int NULL,BookID int NULL,BookTitle nvarchar(200) NULL,BookSubtitle nvarchar(200) NULL,ChapterNumber decimal(10,2) NULL,SceneNumber decimal(10,2) NULL,SceneTitle nvarchar(200) NULL,Ordinal bigint NULL,Heading nvarchar(500) NULL,State nvarchar(500) NULL,Previous nvarchar(500) NULL,Notes nvarchar(max) NULL,EvidenceState nvarchar(30) NULL,RelatedCharacterID int NULL,IsPov bit NULL); + IF @Tab IN(N'evolution',N'overview') + BEGIN + INSERT #Rows SELECT N'attributes',e.CharacterAttributeEventID,e.SceneID,NULL,o.BookID,o.BookTitle,o.BookSubtitle,o.ChapterNumber,o.SceneNumber,o.SceneTitle,o.Ordinal,t.AttributeName,e.AttributeValue, + LAG(e.AttributeValue) OVER(PARTITION BY e.CharacterAttributeTypeID ORDER BY o.Ordinal,e.CharacterAttributeEventID),e.Description,N'Author record',NULL,NULL + FROM dbo.CharacterAttributeEvents e JOIN #Order o ON o.SceneID=e.SceneID JOIN dbo.CharacterAttributeTypes t ON t.CharacterAttributeTypeID=e.CharacterAttributeTypeID WHERE e.CharacterID=@CharacterID; + END; + IF @Tab IN(N'evolution',N'history',N'overview') + BEGIN + INSERT #Rows SELECT N'relationships',e.RelationshipEventID,e.SceneID,r.CharacterRelationshipID,o.BookID,o.BookTitle,o.BookSubtitle,o.ChapterNumber,o.SceneNumber,o.SceneTitle,o.Ordinal,CONCAT(a.CharacterName,N' → ',b.CharacterName,N' · ',t.TypeName),st.StateName,NULL, + CONCAT(e.Description,CASE WHEN e.Intensity IS NULL THEN N'' ELSE CONCAT(N' · Intensity ',e.Intensity) END,CASE WHEN e.IsKnownToOtherCharacter=1 THEN N' · Known to other character' ELSE N' · Not recorded as known to other character' END),COALESCE(ev.EvidenceState,N'Verified'),CASE WHEN r.CharacterAID=@CharacterID THEN r.CharacterBID ELSE r.CharacterAID END,NULL + FROM dbo.RelationshipEvents e JOIN dbo.CharacterRelationships r ON r.CharacterRelationshipID=e.CharacterRelationshipID JOIN #Order o ON o.SceneID=e.SceneID 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 JOIN dbo.RelationshipStates st ON st.RelationshipStateID=e.RelationshipStateID + OUTER APPLY(SELECT TOP(1) m.EvidenceState FROM dbo.ManuscriptEvidenceIndex m WHERE m.EventKind=N'Relationship' AND m.EventID=e.RelationshipEventID AND m.IsPrimary=1 ORDER BY CASE WHEN m.EvidenceState=N'Verified' THEN 1 ELSE 0 END,m.EvidenceID) ev + WHERE r.ProjectID=@project AND r.IsArchived=0 AND (r.CharacterAID=@CharacterID OR r.CharacterBID=@CharacterID) AND (@RelationshipID IS NULL OR r.CharacterRelationshipID=@RelationshipID); + END; + IF @Tab IN(N'knowledge',N'evolution',N'overview') + BEGIN + INSERT #Rows SELECT N'knowledge',k.CharacterKnowledgeID,k.SceneID,NULL,o.BookID,o.BookTitle,o.BookSubtitle,o.ChapterNumber,o.SceneNumber,o.SceneTitle,o.Ordinal,COALESCE(sa.AssetName,pt.ThreadTitle,N'Knowledge record'),st.StateName,NULL, + CONCAT(k.Description,CASE WHEN k.SourceEventID IS NOT NULL THEN N' · Linked source event' ELSE N'' END,CASE WHEN k.SourceReviewKey IS NOT NULL THEN N' · Accepted review source' ELSE N'' END),COALESCE(ev.EvidenceState,N'Verified'),NULL,NULL + FROM dbo.CharacterKnowledge k JOIN #Order o ON o.SceneID=k.SceneID JOIN dbo.KnowledgeStates st ON st.KnowledgeStateID=k.KnowledgeStateID LEFT JOIN dbo.StoryAssets sa ON sa.StoryAssetID=k.StoryAssetID LEFT JOIN dbo.PlotThreads pt ON pt.PlotThreadID=k.PlotThreadID + OUTER APPLY(SELECT TOP(1) m.EvidenceState FROM dbo.ManuscriptEvidenceIndex m WHERE m.EventKind=N'Knowledge' AND m.EventID=k.CharacterKnowledgeID AND m.IsPrimary=1 ORDER BY CASE WHEN m.EvidenceState=N'Verified' THEN 1 ELSE 0 END,m.EvidenceID) ev + WHERE k.CharacterID=@CharacterID; + END; + IF @Tab IN(N'appearances',N'evolution') + BEGIN + INSERT #Rows SELECT N'appearances',sc.SceneCharacterID,sc.SceneID,NULL,o.BookID,o.BookTitle,o.BookSubtitle,o.ChapterNumber,o.SceneNumber,o.SceneTitle,o.Ordinal,o.SceneTitle,CONCAT(COALESCE(role.TypeName,N'Role not recorded'),N' / ',COALESCE(pr.TypeName,N'Presence not recorded')),NULL, + CONCAT(sc.AppearanceNotes,N' ',sc.OutfitDescription,N' · Condition: ',sc.PhysicalCondition,N' · Emotion: ',sc.EmotionalState,N' · Knowledge notes: ',sc.KnowledgeNotes),N'Author record',NULL,CAST(CASE WHEN o.POVCharacterID=@CharacterID THEN 1 ELSE 0 END AS bit) + FROM dbo.SceneCharacters sc JOIN #Order o ON o.SceneID=sc.SceneID LEFT JOIN dbo.CharacterRoleInSceneTypes role ON role.CharacterRoleInSceneTypeID=sc.RoleInSceneTypeID LEFT JOIN dbo.PresenceTypes pr ON pr.PresenceTypeID=sc.PresenceTypeID WHERE sc.CharacterID=@CharacterID; + END; + IF @Tab=N'point' INSERT #Rows SELECT N'scenes',SceneID,SceneID,NULL,BookID,BookTitle,BookSubtitle,ChapterNumber,SceneNumber,SceneTitle,Ordinal,SceneTitle,NULL,NULL,NULL,NULL,NULL,NULL FROM #Order WHERE SceneID=@SceneID; + IF @Tab=N'scenes' INSERT #Rows SELECT N'scenes',SceneID,SceneID,NULL,BookID,BookTitle,BookSubtitle,ChapterNumber,SceneNumber,SceneTitle,Ordinal,SceneTitle,NULL,NULL,NULL,NULL,NULL,NULL FROM #Order; + DELETE FROM #Rows WHERE (@BookID IS NOT NULL AND BookID<>@BookID) OR (@maximum IS NOT NULL AND Ordinal>@maximum) OR (NULLIF(@Category,N'') IS NOT NULL AND CASE WHEN @Tab=N'knowledge' THEN State ELSE Kind END<>@Category) OR (NULLIF(@Search,N'') IS NOT NULL AND NOT(CONCAT(Heading,N' ',State,N' ',Notes,N' ',SceneTitle) LIKE @pattern ESCAPE N'~')); + SELECT COUNT(*) AS Total FROM #Rows; + SELECT * FROM #Rows ORDER BY CASE WHEN @Tab=N'overview' THEN -Ordinal ELSE Ordinal END,SceneID,Kind,ID OFFSET ((@Page-1)*25) ROWS FETCH NEXT 25 ROWS ONLY; +END; +GO +-- Bounded definitions; the existing .NET relationship projection supplies selected-point state. +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Relationships @CharacterID int,@UserID int,@Page int=1,@Search nvarchar(120)=N'',@RelationshipID int=NULL +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 @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 INTO #IDs FROM dbo.CharacterRelationships r 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 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 (NULLIF(@Search,N'') IS NULL OR CONCAT(a.CharacterName,N' ',b.CharacterName,N' ',t.TypeName) LIKE @pattern ESCAPE N'~'); + SELECT COUNT(*) Total FROM #IDs; + 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; + SELECT r.*,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName,st.StateName InitialRelationshipStateName + FROM dbo.CharacterRelationships r JOIN (SELECT CharacterRelationshipID FROM #IDs ORDER BY CharacterRelationshipID OFFSET ((@Page-1)*25) ROWS FETCH NEXT 25 ROWS ONLY) x ON x.CharacterRelationshipID=r.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 ORDER BY r.CharacterRelationshipID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Gallery @CharacterID int,@UserID int,@Page int=1 +AS +BEGIN + SET NOCOUNT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=c.ProjectID WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) THROW 51020,'Character unavailable',1; + IF @Page<1 OR @Page>100000 THROW 51022,'Invalid page',1; + SELECT COUNT(*) Total FROM dbo.CharacterImages WHERE CharacterID=@CharacterID AND IsDeleted=0; + SELECT * FROM dbo.CharacterImages WHERE CharacterID=@CharacterID AND IsDeleted=0 ORDER BY SortOrder,CharacterImageID OFFSET ((@Page-1)*25) ROWS FETCH NEXT 25 ROWS ONLY; +END; +GO diff --git a/PlotLine/Sql/307_CharacterWorkspaceManagement.sql b/PlotLine/Sql/307_CharacterWorkspaceManagement.sql new file mode 100644 index 00000000..09745188 --- /dev/null +++ b/PlotLine/Sql/307_CharacterWorkspaceManagement.sql @@ -0,0 +1,72 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- A reversible definition archive delegates to the existing canonical archive operation. +-- A single event save/delete delegates to its existing canonical operation; linked audit is never cascaded. +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_RelationshipFrame @CharacterID int,@UserID int,@RelationshipID int,@EventID int=NULL +AS +BEGIN + SET NOCOUNT ON; + DECLARE @project int; + SELECT @project=c.ProjectID FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE c.CharacterID=@CharacterID AND c.IsArchived=0 AND p.IsArchived=0; + IF @project IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@RelationshipID AND ProjectID=@project AND IsArchived=0 AND (CharacterAID=@CharacterID OR CharacterBID=@CharacterID)) THROW 51020,'Relationship unavailable',1; + IF @EventID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents WHERE RelationshipEventID=@EventID AND CharacterRelationshipID=@RelationshipID) THROW 51020,'Event unavailable',1; + SELECT r.*,a.CharacterName CharacterAName,b.CharacterName CharacterBName,t.TypeName RelationshipTypeName,cat.CategoryName RelationshipCategoryName, + 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 WHERE e.CharacterRelationshipID=r.CharacterRelationshipID ORDER BY e.RelationshipEventID FOR JSON PATH))),2) Version, + (SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE CharacterRelationshipID=r.CharacterRelationshipID) EventCount, + (SELECT COUNT(*) FROM dbo.CharacterRelationships x WHERE x.ProjectID=@project AND x.IsArchived=0 AND x.CharacterRelationshipID<>r.CharacterRelationshipID AND ((x.CharacterAID=r.CharacterAID AND x.CharacterBID=r.CharacterBID) OR (x.CharacterAID=r.CharacterBID AND x.CharacterBID=r.CharacterAID))) OtherPairRecords + FROM dbo.CharacterRelationships r 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 WHERE r.CharacterRelationshipID=@RelationshipID; + SELECT e.*,CAST(CASE WHEN e.SourceReviewKey IS NOT NULL OR EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex m WHERE m.EventKind=N'Relationship' AND m.EventID=e.RelationshipEventID) OR EXISTS(SELECT 1 FROM dbo.CharacterKnowledge k WHERE k.SourceEventID=e.RelationshipEventID) THEN 1 ELSE 0 END AS bit) ProtectedSource FROM dbo.RelationshipEvents e WHERE e.RelationshipEventID=@EventID AND e.CharacterRelationshipID=@RelationshipID; +END; +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 +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,@permanent bit,@start int,@end int,@known bit,@initial bit,@book int,@reader bit,@state int,@strength int,@reciprocal bit; + SELECT @a=CharacterAID,@b=CharacterBID,@type=RelationshipTypeID,@permanent=IsPermanent,@start=StartSceneID,@end=EndSceneID,@known=IsKnownToReader,@initial=IsInitialRelationship,@book=InitialBookID,@reader=ReaderInitiallyKnows,@state=InitialRelationshipStateID,@strength=InitialIntensity,@reciprocal=IsReciprocal FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@RelationshipID; + 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=@permanent,@StartSceneID=@start,@EndSceneID=@end,@IsKnownToReader=@known,@Notes=@Notes,@IsInitialRelationship=@initial,@InitialBookID=@book,@ReaderInitiallyKnows=@reader,@InitialRelationshipStateID=@state,@InitialIntensity=@strength,@IsReciprocal=@reciprocal; + 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 diff --git a/PlotLine/Sql/308_CharacterWorkspaceConnectionSummaries.sql b/PlotLine/Sql/308_CharacterWorkspaceConnectionSummaries.sql new file mode 100644 index 00000000..0aba3f32 --- /dev/null +++ b/PlotLine/Sql/308_CharacterWorkspaceConnectionSummaries.sql @@ -0,0 +1,24 @@ +-- Bounded canonical author-reference connections; no event histories or inferred ranking. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterWorkspace_Summary @CharacterID int,@UserID int +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; + SELECT (SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE ProjectID=@project AND IsArchived=0 AND (CharacterAID=@CharacterID OR CharacterBID=@CharacterID)) Relationships, + (SELECT COUNT(*) FROM dbo.SceneCharacters sc JOIN dbo.CharacterWorkspace_SceneOrder(@project) o ON o.SceneID=sc.SceneID WHERE sc.CharacterID=@CharacterID) Appearances, + (SELECT COUNT(*) FROM dbo.CharacterAttributeEvents WHERE CharacterID=@CharacterID) Attributes, + (SELECT COUNT(*) FROM dbo.CharacterKnowledge WHERE CharacterID=@CharacterID) Knowledge, + (SELECT COUNT(*) FROM dbo.CharacterImages WHERE CharacterID=@CharacterID AND IsDeleted=0) Images, + (SELECT TOP(1) o.SceneID FROM dbo.CharacterWorkspace_SceneOrder(@project) o JOIN dbo.SceneCharacters sc ON sc.SceneID=o.SceneID WHERE sc.CharacterID=@CharacterID ORDER BY o.Ordinal) FirstSceneID, + (SELECT STRING_AGG(CONVERT(nvarchar(max),x.Label),N'; ') FROM (SELECT TOP(3) CONCAT(c.CharacterName,N' · ',t.TypeName) Label FROM dbo.CharacterRelationships r JOIN dbo.Characters c ON c.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 cat.CategoryName=N'Family' ORDER BY r.CharacterRelationshipID) x) FamilyConnections, + (SELECT STRING_AGG(CONVERT(nvarchar(max),x.Label),N'; ') FROM (SELECT TOP(3) CONCAT(c.CharacterName,N' · ',t.TypeName) Label FROM dbo.CharacterRelationships r JOIN dbo.Characters c ON c.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 (cat.CategoryName<>N'Family' OR cat.CategoryName IS NULL) ORDER BY r.CharacterRelationshipID) x) StoryConnections; + SELECT o.*,CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.SceneCharacters sc WHERE sc.CharacterID=@CharacterID AND sc.SceneID=o.SceneID) THEN 1 ELSE 0 END AS bit) IsAppearance + FROM dbo.CharacterWorkspace_SceneOrder(@project) o WHERE o.SceneID=(SELECT AgeReferenceSceneID FROM dbo.Characters WHERE CharacterID=@CharacterID) + OR o.SceneID=(SELECT TOP(1) x.SceneID FROM dbo.CharacterWorkspace_SceneOrder(@project) x JOIN dbo.SceneCharacters sc ON sc.SceneID=x.SceneID JOIN dbo.Characters c ON c.CharacterID=sc.CharacterID WHERE sc.CharacterID=@CharacterID AND x.TimeModeName IN(N'Exact Date',N'Exact DateTime',N'Exact Date and Time') AND x.StartDateTime IS NOT NULL AND (c.BirthDate IS NULL OR x.StartDateTime>=c.BirthDate) ORDER BY x.Ordinal) + ORDER BY o.Ordinal; +END; +GO diff --git a/PlotLine/ViewModels/CharacterWorkspaceModels.cs b/PlotLine/ViewModels/CharacterWorkspaceModels.cs new file mode 100644 index 00000000..f3a8a1c8 --- /dev/null +++ b/PlotLine/ViewModels/CharacterWorkspaceModels.cs @@ -0,0 +1,31 @@ +using System.ComponentModel.DataAnnotations; +using PlotLine.Models; +namespace PlotLine.ViewModels; +public sealed class CharacterWorkspaceCounts +{ + public string? FamilyConnections{get;set;}public string? StoryConnections{get;set;} + public int Relationships{get;set;}public int Appearances{get;set;}public int Attributes{get;set;}public int Knowledge{get;set;}public int Images{get;set;}public int? FirstSceneID{get;set;} +} +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 sealed class CharacterWorkspaceEntry +{ + public string Kind{get;set;}="";public int ID{get;set;}public int? SceneID{get;set;}public int? RelationshipID{get;set;}public int? BookID{get;set;}public string? BookTitle{get;set;}public string? BookSubtitle{get;set;}public string BookDisplayTitle=>BookTitleFormatter.DisplayTitle(BookTitle,BookSubtitle); + public decimal? ChapterNumber{get;set;}public decimal? SceneNumber{get;set;}public string? SceneTitle{get;set;}public long? Ordinal{get;set;}public string? Heading{get;set;}public string? State{get;set;}public string? Previous{get;set;}public string? Notes{get;set;}public string? EvidenceState{get;set;}public int? RelatedCharacterID{get;set;}public bool IsPov{get;set;} +} +public sealed class CharacterWorkspacePage +{ + public CharacterDetailViewModel Profile{get;set;}=new();public CharacterWorkspaceQuery Query{get;set;}=new();public string? PointLabel{get;set;}public int Total{get;set;}public IReadOnlyList Entries{get;set;}=[];public IReadOnlyList Relationships{get;set;}=[];public IReadOnlyList Images{get;set;}=[];public IReadOnlyList Books{get;set;}=[]; +} +public sealed class CharacterRelationshipFrame +{ + public CharacterRelationship Relationship{get;set;}=new();public string Version{get;set;}="";public int EventCount{get;set;}public int OtherPairRecords{get;set;} +} +public sealed class CharacterWorkspaceEvent {public RelationshipEvent Record{get;set;}=new();public bool ProtectedSource{get;set;}} +public sealed class CharacterWorkspaceOperation +{ + 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 States{get;set;}=[]; +} diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 2956170c..5621d375 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -1969,9 +1969,9 @@ public sealed class CharacterEditViewModel public IReadOnlyList ImportanceOptions { get; set; } = [ - new("Use timeline fallback", string.Empty), + new("Unclassified · use timeline fallback", string.Empty), new("Major", "10"), - new("Secondary / Supporting", "6"), + new("Supporting", "6"), new("Minor", "2") ]; @@ -1982,6 +1982,10 @@ public sealed class CharacterEditViewModel public sealed class CharacterDetailViewModel { + public bool WorkspaceCanEdit {get;set;} + public string? WorkspaceTab {get;set;} + public CharacterWorkspaceCounts WorkspaceCounts {get;set;}=new(); + public CharacterWorkspacePage? WorkspacePage {get;set;} public Project Project { get; set; } = new(); public Character Character { get; set; } = new(); public IReadOnlyList Aliases { get; set; } = []; diff --git a/PlotLine/Views/Characters/Details.cshtml b/PlotLine/Views/Characters/Details.cshtml index ede2f203..7b1007e6 100644 --- a/PlotLine/Views/Characters/Details.cshtml +++ b/PlotLine/Views/Characters/Details.cshtml @@ -1,591 +1,31 @@ @model CharacterDetailViewModel -@{ - ViewData["DesktopLayout"] = "details"; - ViewData["Title"] = Model.Character.CharacterName; - ViewData["ProjectSection"] = "Characters"; - var firstAppearance = Model.Appearances.FirstOrDefault(); - var storyImportance = Model.Character.CharacterImportance switch - { - >= 8 => "Major", - >= 4 => "Secondary / Supporting", - >= 1 => "Minor", - _ => "Timeline fallback" - }; - var characterLookup = Model.ProjectCharacters.ToDictionary(x => x.CharacterID); - var knownNames = Model.Aliases - .Select(x => x.Alias) - .Append(Model.Character.CharacterName) - .Where(name => !string.IsNullOrWhiteSpace(name)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(name => !string.Equals(name, Model.Character.CharacterName, StringComparison.OrdinalIgnoreCase)) - .ThenBy(name => name, StringComparer.OrdinalIgnoreCase) - .ToList(); - var analysis = Model.CharacterAnalysis; - var analysisStatus = string.IsNullOrWhiteSpace(analysis.Status) ? "Not analysed" : analysis.Status; - var analysisActive = analysis.Status is CharacterEnrichmentStatuses.Queued or CharacterEnrichmentStatuses.Running; - var analysisButtonText = analysis.Status switch - { - CharacterEnrichmentStatuses.Queued => "Queued...", - CharacterEnrichmentStatuses.Running => "Analysing...", - _ => "Reanalyse character" - }; - var lastAnalysed = analysis.LastAnalysedUtc?.ToLocalTime().ToString("d MMMM yyyy, HH:mm"); -} - - - +@{ViewData["DesktopLayout"]="details";ViewData["Title"]=Model.Character.CharacterName;ViewData["ProjectSection"]="Characters";var c=Model.Character;var analysis=Model.CharacterAnalysis;} + - -
- -
-

Character

-

@Model.Character.CharacterName

-

@Model.Character.DefaultDescription

-
-
- Back to characters - Back to timeline - -
+
+
+ +

@Model.Project.ProjectName · Character

@c.CharacterName

@CharacterWorkspace.Classification(c.CharacterImportance)@(analysis.Status??"Not analysed")@analysis.CurrentMessage
+
CharactersTimeline +@if(Model.WorkspaceCanEdit){Edit character} +
+
+
+ +
@if(Model.WorkspacePage!=null){}
+ +
- - - -@if (TempData["ImageMessage"] is string imageMessage) -{ - -} -@if (TempData["ImageError"] is string imageError) -{ -
@imageError
-} -@if (TempData["RelationshipMessage"] is string relationshipMessage) -{ - -} -@if (TempData["CharacterMessage"] is string characterMessage) -{ - -} - -
-
-

Profile

-

Preferred name: @Model.Character.CharacterName

-

Life status: @(Model.Character.IsDeceased == true ? "Deceased" : Model.Character.IsDeceased == false ? "Living" : "Unrecorded") Global author reference; no death scene is implied.

-

Sex: @Model.Character.Sex

-

Date of birth: @(Model.Character.BirthDate?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) ?? "Not recorded")

-

Age: @Model.DisplayAge - @Model.AgeContext - @if (Model.AgeReferenceScene is { } ageScene) - { - @ageScene.SceneTitle · @ageScene.StartDateTime?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) - } - -

-

Height: @Model.Character.Height

-

Eye colour: @Model.Character.EyeColour

-

Story importance: @storyImportance

-
-

Character analysis: @analysisStatus

-

Last analysed: @(lastAnalysed ?? "Not analysed")

- @if (!string.IsNullOrWhiteSpace(analysis.CurrentMessage)) - { -

@analysis.CurrentMessage

- } - else - { -

- } -
-
-

Story Intelligence Analysis

-

@(analysis.Summary ?? "No generated character analysis yet.")

-

Date of birth: @(analysis.DateOfBirth ?? "Unknown")

-

Age at start of series: @(analysis.AgeAtStartOfSeries ?? "Unknown")

-

Height: @(analysis.Height ?? "Unknown")

-

Eye colour: @(analysis.EyeColour ?? "Unknown")

-
-
-

Known names

-
- @foreach (var name in knownNames) - { - var isPreferred = string.Equals(name, Model.Character.CharacterName, StringComparison.OrdinalIgnoreCase); -
- @name - @if (isPreferred) - { - Preferred - } - else - { -
- - - -
- } -
- } -
-
-
-

Initial Relationships

- @if (!Model.InitialRelationships.Any()) - { -

No initial relationships yet.

- } - else - { -
- @foreach (var categoryGroup in Model.InitialRelationships.GroupBy(x => new { x.RelationshipCategoryName, x.CategorySortOrder }).OrderBy(x => x.Key.CategorySortOrder).ThenBy(x => x.Key.RelationshipCategoryName)) - { -

@categoryGroup.Key.RelationshipCategoryName

- @foreach (var relationship in categoryGroup.OrderBy(x => x.RelationshipTypeSortOrder).ThenBy(x => x.CharacterAName).ThenBy(x => x.CharacterBName)) - { - var initialSourceId = relationship.CharacterAID; - var initialRelatedId = relationship.CharacterBID; - Character? relatedCharacter = null; - characterLookup.TryGetValue(relationship.CharacterAID == Model.Character.CharacterID ? relationship.CharacterBID : relationship.CharacterAID, out relatedCharacter); -
-
-
- -
- @relationship.CharacterAName -> @relationship.CharacterBName - @relationship.RelationshipTypeName @relationship.RelationshipCategoryName - Reciprocal: @(relationship.IsReciprocal ? "Yes" : "No") - Reader initially knows: @(relationship.ReaderInitiallyKnows ? "Yes" : "No") - @if (!string.IsNullOrWhiteSpace(relationship.InitialRelationshipStateName) || relationship.InitialIntensity.HasValue) - { - @relationship.InitialRelationshipStateName@if (relationship.InitialIntensity.HasValue) { / Intensity @relationship.InitialIntensity } - } - @if (!string.IsNullOrWhiteSpace(relationship.InitialBookDisplayTitle)) - { - Initial book: @relationship.InitialBookDisplayTitle - } - @if (!string.IsNullOrWhiteSpace(relationship.Notes)) - { - @relationship.Notes - } -
-
-
- Open related character - Evolution - -
- - - -
-
-
-
- - - - -
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- } - } -
- } -
- Add initial relationship -
- - - -
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- -
-
-
-
-
- - - -
-

Current Relationships

- @if (!Model.CurrentRelationships.Any()) - { -

No current relationship state yet.

- } - else - { -
- @foreach (var categoryGroup in Model.CurrentRelationships.GroupBy(x => new { x.Relationship.RelationshipCategoryName, x.Relationship.CategorySortOrder }).OrderBy(x => x.Key.CategorySortOrder).ThenBy(x => x.Key.RelationshipCategoryName)) - { -

@categoryGroup.Key.RelationshipCategoryName

- @foreach (var current in categoryGroup.OrderBy(x => x.Relationship.RelationshipTypeSortOrder).ThenBy(x => x.Relationship.CharacterAName).ThenBy(x => x.Relationship.CharacterBName)) - { - var relationship = current.Relationship; - var relatedCharacterId = relationship.CharacterAID == Model.Character.CharacterID ? relationship.CharacterBID : relationship.CharacterAID; - var relatedCharacterName = relationship.CharacterAID == Model.Character.CharacterID ? relationship.CharacterBName : relationship.CharacterAName; -
- @relatedCharacterName - @relationship.RelationshipTypeName @relationship.RelationshipCategoryName / Current: @current.CurrentStateName - Reciprocal: @(relationship.IsReciprocal ? "Yes" : "No") / Confidence / intensity: @(current.CurrentIntensity?.ToString() ?? "Unknown") - @if (!string.IsNullOrWhiteSpace(current.CurrentNotes)) - { - @current.CurrentNotes - } - Open related character - Evolution -
- View History -
-
- Initial: @relationship.RelationshipTypeName @relationship.RelationshipCategoryName - @(relationship.InitialRelationshipStateName ?? "No awareness state")@if (relationship.InitialIntensity.HasValue) { / Intensity @relationship.InitialIntensity } - Reader initially knows: @(relationship.ReaderInitiallyKnows ? "Yes" : "No") - @if (!string.IsNullOrWhiteSpace(relationship.Notes)) - { - @relationship.Notes - } -
- @foreach (var item in current.Events) - { -
- @item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle - @item.RelationshipStateName @item.RelationshipCategoryName / Intensity @(item.Intensity?.ToString() ?? "Unknown") - Awareness: @(item.IsKnownToOtherCharacter ? "known to other character" : "not known to other character") - @if (!string.IsNullOrWhiteSpace(item.Description)) - { - @item.Description - } - Open scene -
- } -
- Current: @current.CurrentStateName - Confidence / intensity: @(current.CurrentIntensity?.ToString() ?? "Unknown") -
-
-
-
- } - } -
- } -
-
-

Relationship Events

- @if (!Model.RelationshipEvents.Any()) - { -

No relationship events yet.

- } - else - { -
- @foreach (var item in Model.RelationshipEvents) - { -
- @item.CharacterAName -> @item.CharacterBName: @item.RelationshipStateName - @item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle - @item.RelationshipTypeName @item.RelationshipCategoryName / Awareness: @(item.IsKnownToOtherCharacter ? "known to other character" : "not known to other character") - Reciprocal: @(item.IsReciprocal ? "Yes" : "No") / Confidence / intensity: @(item.Intensity?.ToString() ?? "Unknown") - @if (!string.IsNullOrWhiteSpace(item.Description)) - { - @item.Description - } - Open in timeline - Open related character -
- } -
- } -
- -
-

Scene appearances

- @if (!Model.Appearances.Any()) - { -

No scene appearances yet.

- } - else - { -
- @foreach (var appearance in Model.Appearances) - { -
- @appearance.BookDisplayTitle / Ch @appearance.ChapterNumber / Scene @appearance.SceneNumber: @appearance.SceneTitle - @appearance.RoleInSceneTypeName / @appearance.PresenceTypeName - @appearance.OutfitDescription @appearance.PhysicalCondition @appearance.EmotionalState - Open in timeline -
- } -
- } -
- -
-

Attribute history

- @if (!Model.AttributeEvents.Any()) - { -

No attribute events yet.

- } - else - { -
- @foreach (var item in Model.AttributeEvents) - { -
- @item.AttributeName: @item.AttributeValue - @item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle - @item.Description - Open in timeline -
- } -
- } -
- -
-

Knowledge

- @if (!Model.KnowledgeItems.Any()) - { -

No knowledge entries yet.

- } - else - { -
- @foreach (var item in Model.KnowledgeItems) - { -
- @item.KnowledgeStateName: @(item.AssetName ?? item.ThreadTitle) - @item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle - @item.Description - Open in timeline -
- } -
- } -
- - -@section Scripts { - - +@foreach(var key in new[]{"ImageMessage","RelationshipMessage","CharacterMessage"}){if(TempData[key] is string message){}} +@if(TempData["ImageError"] is string error){
@error
} +@section Scripts{ + + + + + } diff --git a/PlotLine/Views/Characters/_WorkspaceAdd.cshtml b/PlotLine/Views/Characters/_WorkspaceAdd.cshtml new file mode 100644 index 00000000..bdf7af8d --- /dev/null +++ b/PlotLine/Views/Characters/_WorkspaceAdd.cshtml @@ -0,0 +1,11 @@ +@model CharacterDetailViewModel +
+

Add an initial relationship

Author-established definition for @Model.Character.CharacterName. For a scene-based development, use the source scene editor.

+ + + + + + +
+
diff --git a/PlotLine/Views/Characters/_WorkspaceGallery.cshtml b/PlotLine/Views/Characters/_WorkspaceGallery.cshtml new file mode 100644 index 00000000..5c6962dd --- /dev/null +++ b/PlotLine/Views/Characters/_WorkspaceGallery.cshtml @@ -0,0 +1,64 @@ +@model CharacterDetailViewModel + + diff --git a/PlotLine/Views/Characters/_WorkspaceOperation.cshtml b/PlotLine/Views/Characters/_WorkspaceOperation.cshtml new file mode 100644 index 00000000..bb81cf72 --- /dev/null +++ b/PlotLine/Views/Characters/_WorkspaceOperation.cshtml @@ -0,0 +1,21 @@ +@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;} +
+

@(Model.Action=="archive"?"Remove relationship":Model.Action=="event-remove"?"Remove one relationship event":Model.Action=="definition"?"Edit relationship definition":"Edit one relationship event")

+ + +

@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · @r.RelationshipTypeName · @r.RelationshipCategoryName

+@if(Model.Action=="archive"){ +

This removes the underlying relationship definition from active Family, Story and Timeline views. It archives one canonical record; it does not permanently delete it.

@Model.Record.EventCount dependent scene events will be retained, including their source/history. Restore the definition through Archived Items to make them active again.

@(r.IsReciprocal?"Both directions of this reciprocal flag belong to this one record and will be removed together.":"This is a directional record.")

@if(Model.Record.OtherPairRecords>0){

@Model.Record.OtherPairRecords separately recorded relationship(s) between these characters will remain. They are independent authored records; review them separately.

} +}else if(Model.Action=="event-remove"){ +

This permanently removes only event #@Model.EventID at scene #@Model.Event?.Record.SceneID. The relationship definition and other events remain. Its derived state will be recalculated from the remaining records.

+} +@if(linked){

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.

Open source scene} +else if(!destructive){ +

@(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.")

+@if(Model.Action!="definition"||r.IsInitialRelationship){} + +} +@if(destructive&&!linked){} +
@if(!linked){}Full Relationships Editor
+
diff --git a/PlotLine/Views/Characters/_WorkspaceProfile.cshtml b/PlotLine/Views/Characters/_WorkspaceProfile.cshtml new file mode 100644 index 00000000..c5d48246 --- /dev/null +++ b/PlotLine/Views/Characters/_WorkspaceProfile.cshtml @@ -0,0 +1,61 @@ +@model CharacterDetailViewModel +@{var analysis=Model.CharacterAnalysis;var analysisStatus=string.IsNullOrWhiteSpace(analysis.Status)?"Not analysed":analysis.Status;var lastAnalysed=analysis.LastAnalysedUtc?.ToLocalTime().ToString("d MMMM yyyy, HH:mm");var storyImportance=CharacterWorkspace.Classification(Model.Character.CharacterImportance);var knownNames=Model.Aliases.Select(a=>a.Alias).Append(Model.Character.CharacterName).Where(n=>!string.IsNullOrWhiteSpace(n)).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(n=>n!=Model.Character.CharacterName).ThenBy(n=>n).ToArray();} +
+

Profile

+

Preferred name: @Model.Character.CharacterName

+

Life status: @(Model.Character.IsDeceased == true ? "Deceased" : Model.Character.IsDeceased == false ? "Living" : "Unrecorded") Global author reference; no death scene is implied.

+

Sex: @Model.Character.Sex

+

Date of birth: @(Model.Character.BirthDate?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) ?? "Not recorded")

+

Age: @Model.DisplayAge + @Model.AgeContext + @if (Model.AgeReferenceScene is { } ageScene) + { + @ageScene.SceneTitle · @ageScene.StartDateTime?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) + } + +

+

Height: @Model.Character.Height

+

Eye colour: @Model.Character.EyeColour

+

Story importance: @storyImportance

+
+

Character analysis: @analysisStatus

+

Last analysed: @(lastAnalysed ?? "Not analysed")

+ @if (!string.IsNullOrWhiteSpace(analysis.CurrentMessage)) + { +

@analysis.CurrentMessage

+ } + else + { +

+ } +

Biography and description

@if(Model.Character.DefaultDescription?.Length>800){

@Model.Character.DefaultDescription[..600]…

Read full recorded description

@Model.Character.DefaultDescription

}else{

@(string.IsNullOrWhiteSpace(Model.Character.DefaultDescription)?"No description recorded.":Model.Character.DefaultDescription)

}@if(Model.WorkspaceCanEdit){Edit profile and background}
+

Known names

+
Recorded names and aliases (@knownNames.Length)
+ @foreach (var name in knownNames) + { + var isPreferred = string.Equals(name, Model.Character.CharacterName, StringComparison.OrdinalIgnoreCase); +
+ @name + @if (isPreferred) + { + Preferred + } + else + { + + } +
+ } +
+

Showing up to 50 aliases. The full character editor retains every recorded name and alias.

\ No newline at end of file diff --git a/PlotLine/Views/Characters/_WorkspaceTab.cshtml b/PlotLine/Views/Characters/_WorkspaceTab.cshtml new file mode 100644 index 00000000..337a7b9f --- /dev/null +++ b/PlotLine/Views/Characters/_WorkspaceTab.cshtml @@ -0,0 +1,56 @@ +@model CharacterWorkspacePage +@{var c=Model.Profile.Character;var q=Model.Query;var totalPages=Math.Max(1,(Model.Total+24)/25);} +
+@if(q.Tab=="overview"){ + +

Recent recorded changes

@if(!Model.Entries.Any()){

No changes recorded yet.

}else{foreach(var entry in Model.Entries){

@entry.Heading · @entry.State @entry.BookDisplayTitle · @entry.SceneTitle

}}Explore evolution
+ +}else if(q.Tab=="gallery"){ +Model.Profile.Images=Model.Images; +
@if(q.Page>1){}Page @q.Page of @totalPages@if(q.PageNext images}
+}else{ +

@(q.Tab=="history"?"Relationship history":q.Tab=="scenes"?"Choose a narrative position":q.Tab=="relationships"?"Relationships":q.Tab=="evolution"?"Evolution":q.Tab=="appearances"?"Appearances":"Knowledge")

@(q.Tab=="knowledge"?"Canonical knowledge classifications and sources. Records through the selected point are author reference to this character; they are not proof of another viewpoint’s knowledge.":q.Tab=="relationships"?"Author definitions and recorded developments remain distinct. Family is author-reference truth; Story shows the selected narrative point.":"Recorded narrative order, grouped by book, chapter and scene.")

+@if(q.Tab=="evolution"){Advanced arc, charts and continuity} +@if(q.Tab=="knowledge"){Knowledge timeline and continuity} +@if(q.Tab=="relationships"&&Model.Profile.WorkspaceCanEdit){} +
+@if(q.Tab is "relationships" or "knowledge"){ +
@(q.SceneID.HasValue?Model.PointLabel:"Latest recorded author reference")@if(q.SceneID.HasValue){}
+} +
+ + +@if(q.Tab!="relationships"){} +@if(q.Tab=="evolution"){} +@if(q.Tab=="knowledge"){} +
+@if(q.Tab=="relationships"){ +
+
+
Family: parent · biological · adoptive (dashed) · step (dotted) · partnership. Story: friendship (green), hostility (red), romance (purple), professional/social (blue).
+

Only recorded connections are shown. A relationship does not establish a first meeting, mutual trust or viewpoint knowledge.

+
+@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; +

@name

@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · @r.RelationshipTypeName @r.RelationshipCategoryName

@(q.SceneID.HasValue?"Selected-point state":"Latest recorded state"): @current.CurrentStateName @if(current.CurrentIntensity.HasValue&¤t.LatestEvent?.RelationshipStateName!="Not established / ended at this point"){· Intensity @current.CurrentIntensity}

@current.CurrentNotes

@(r.IsInitialRelationship?"Initial author definition":"Scene-established definition") · @(r.IsReciprocal?"One reciprocal record covers both directions":"Directional record")

+
+@if(Model.Profile.WorkspaceCanEdit){} +Advanced evolutionFull Relationships Editor
} +@if(!Model.Relationships.Any()){

No matching relationship definitions recorded. Add an initial relationship or use the scene editor for a scene-based development.

} +
+}else{ +@if(!Model.Entries.Any()){

No matching records at this point. Change the filters or record information in its scene/source editor.

} +@foreach(var group in Model.Entries.GroupBy(e=>new{e.BookID,e.BookDisplayTitle,e.ChapterNumber,e.SceneID,e.SceneTitle,e.SceneNumber})){ +

@group.Key.BookDisplayTitle · Chapter @group.Key.ChapterNumber · Scene @group.Key.SceneNumber: @group.Key.SceneTitle

+@foreach(var item in group){
@item.Heading · @item.State @if(item.IsPov){POV} · @item.Kind · @item.EvidenceState
+@if(!string.IsNullOrWhiteSpace(item.Previous)){

Previous recorded value: @item.Previous

}

@item.Notes

+@if(item.EvidenceState is not (null or "Verified" or "Author record")){

Source evidence needs review; this is not established knowledge or a verified relationship development.

} +@if(item.SceneID.HasValue){Open scene / source editorTimeline} +@if(item.RelatedCharacterID.HasValue){Related character} +@if(item.Kind=="relationships"&&Model.Profile.WorkspaceCanEdit&&item.RelationshipID.HasValue){} +@if(q.Tab=="scenes"){} +
} +
} +} +
@Model.Total recorded results · page @q.Page of @totalPages@if(q.Page>1){}@if(q.PageNext}
+} +
diff --git a/PlotLine/wwwroot/css/character-workspace.css b/PlotLine/wwwroot/css/character-workspace.css new file mode 100644 index 00000000..7e62e28c --- /dev/null +++ b/PlotLine/wwwroot/css/character-workspace.css @@ -0,0 +1 @@ +[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;}} diff --git a/PlotLine/wwwroot/js/character-enrichment-detail.js b/PlotLine/wwwroot/js/character-enrichment-detail.js index 174fda11..e582584a 100644 --- a/PlotLine/wwwroot/js/character-enrichment-detail.js +++ b/PlotLine/wwwroot/js/character-enrichment-detail.js @@ -9,6 +9,7 @@ const renderedStatus = panel.dataset.analysisStatus || ""; let latestRunId = renderedRunId; let reloadScheduled = false; + let refreshedRunId = renderedStatus === "Completed" ? renderedRunId : 0; const form = document.querySelector("[data-character-reanalyse-form]"); const button = document.querySelector("[data-character-reanalyse-button]"); const status = document.querySelector("[data-character-analysis-status]"); @@ -63,11 +64,16 @@ if (nextStatus === "Completed") { setReady(); + const workspace = document.querySelector('[data-character-workspace]'); + if (workspace) { + if (runId > refreshedRunId) { refreshedRunId = runId; window.setTimeout(() => workspace.dispatchEvent(new Event('character-analysis-updated')), 700); } + return; + } // Initial subscriptions and reconnects replay completed runs. Only reload // when the saved page does not already contain this completed analysis. if (!reloadScheduled && (runId > renderedRunId || renderedStatus !== "Completed")) { reloadScheduled = true; - window.setTimeout(() => window.location.reload(), 700); + window.setTimeout(() => { const workspace=document.querySelector('[data-character-workspace]');if(workspace)workspace.dispatchEvent(new Event('character-analysis-updated'));else window.location.reload(); }, 700); } return; } diff --git a/PlotLine/wwwroot/js/character-workspace-graph.js b/PlotLine/wwwroot/js/character-workspace-graph.js new file mode 100644 index 00000000..955c342c --- /dev/null +++ b/PlotLine/wwwroot/js/character-workspace-graph.js @@ -0,0 +1,19 @@ +(() => { + 'use strict';const NS='http://www.w3.org/2000/svg',engine=window.PlotDirectorContextRelationshipLayout,colours={'Family':'#976512','Friendship':'#2d805c','Hostile / Conflict':'#b94a48','Romantic / Sexual':'#9957a7','Professional / Social':'#397ba2'},familyColours={parent:'#6b727a',biological:'#397ba2',adoptive:'#2d805c',step:'#a16b27',partner:'#9957a7',sibling:'#777',half:'#a16b27',other:'#777'}; + const el=(tag,attrs={},text)=>{const n=document.createElementNS(NS,tag);for(const[k,v]of Object.entries(attrs))n.setAttribute(k,v);if(text!=null)n.textContent=text;return n;}; + window.PlotDirectorCharacterGraph={mount(host,options){const abort=new AbortController(),signal=abort.signal,root=host.closest('[data-character-tab-content]'),status=root.querySelector('[data-character-graph-status]'),selection=root.querySelector('[data-character-graph-selection]'),views=options.views;let lens=options.lens||'family',data,branches=[],epoch=0,request,selectedNode=options.id;const svg=el('svg',{width:'100%',height:'100%','aria-label':'Recorded character relationships'}),world=el('g');svg.append(world);host.replaceChildren(svg);let suppress=0; + const listen=(node,type,fn,extra={})=>node.addEventListener(type,fn,{...extra,signal});function view(){return views[lens]||=( {x:0,y:0,scale:1,focus:options.id,expanded:[],selected:null,initialised:false,layout:null,key:''});}function transform(){const v=view();world.setAttribute('transform',`translate(${v.x} ${v.y}) scale(${v.scale})`);}function centre(id){const v=view(),p=v.layout?.positions[id];if(!p)return;v.x=host.clientWidth/2-(p.x+90)*v.scale;v.y=host.clientHeight/2-(p.y+33)*v.scale;v.initialised=true;transform();}function zoom(factor,x=host.clientWidth/2,y=host.clientHeight/2){const v=view(),s=Math.max(.4,Math.min(3,v.scale*factor));v.x=x-(x-v.x)*s/v.scale;v.y=y-(y-v.y)*s/v.scale;v.scale=s;transform();} + function highlight(){const id=view().selected;world.querySelectorAll('[data-character-edge]').forEach(e=>e.classList.toggle('is-selected',Number(e.dataset.characterEdge)===id));world.querySelectorAll('[data-character-node]').forEach(e=>e.classList.toggle('is-selected',Number(e.dataset.characterNode)===selectedNode));} + function pickLink(id,notify=true){if(!data?.links.some(l=>l.id===id)){status.textContent='This connection is outside the bounded diagram or is not established at the selected point. Its author record remains available below.';return;}view().selected=id;highlight();const l=data.links.find(l=>l.id===id),a=data.nodes.find(n=>n.id===l.a),b=data.nodes.find(n=>n.id===l.b);selection.replaceChildren();const p=document.createElement('p');p.textContent=`${a?.name} ${l.reciprocal?'↔':'→'} ${b?.name} · ${l.type} · ${l.state}`;selection.append(p);if(notify)options.onLink?.(id);} + function pickNode(id){selectedNode=id;view().selected=null;highlight();selection.replaceChildren();const n=data.nodes.find(n=>n.id===id);const p=document.createElement('p');p.textContent=n.name+(lens==='family'&&n.isDeceased===true?' · Deceased (global author reference)':'')+(n.archived?' · Archived identity':'');const a=document.createElement('a');a.href='/Characters/Details/'+id;a.dataset.characterLink='';a.textContent='Open character workspace';selection.append(p,a);} + function draw(){const v=view(),key=engine.signature(data.nodes,data.links)+(lens==='story'?':'+data.focusID:'');if(v.key!==key||!v.layout){const prior=v.layout;v.layout=lens==='family'?engine.family(data.nodes,data.links):engine.story(data.nodes,data.links,data.focusID);v.key=key;if(prior&&v.initialised){const a=prior.positions[v.focus],b=v.layout.positions[v.focus];if(a&&b){v.x+=(a.x-b.x)*v.scale;v.y+=(a.y-b.y)*v.scale;}}}world.replaceChildren();const layout=v.layout,defs=el('defs'),markerID='cw-arrow-'+crypto.randomUUID(),marker=el('marker',{id:markerID,markerWidth:9,markerHeight:9,refX:8,refY:4.5,orient:'auto-start-reverse',markerUnits:'userSpaceOnUse'});marker.append(el('path',{d:'M 0 0 L 9 4.5 L 0 9 Z',fill:'context-stroke'}));defs.append(marker);world.append(defs); + 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); + } + 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();}); + const pointers=new Map();let drag;listen(svg,'click',e=>{if(performance.now(){if(e.target.closest('[data-character-branch]'))return;pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={x:e.clientX,y:e.clientY};});listen(svg,'pointermove',e=>{if(!pointers.has(e.pointerId))return;const before=[...pointers.values()];pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});const after=[...pointers.values()];if(after.length===2){const a=Math.hypot(before[0].x-before[1].x,before[0].y-before[1].y),b=Math.hypot(after[0].x-after[1].x,after[0].y-after[1].y);if(a>0)zoom(b/a);suppress=performance.now()+500;}else if(drag&&Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>6){svg.setPointerCapture(e.pointerId);view().x+=e.clientX-drag.x;view().y+=e.clientY-drag.y;transform();drag={x:e.clientX,y:e.clientY};suppress=performance.now()+500;}});for(const type of ['pointerup','pointercancel'])listen(svg,type,e=>{pointers.delete(e.pointerId);drag=null;});listen(host,'keydown',e=>{if(e.target!==host)return;if(['+','-','=','Home','ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(e.key))e.preventDefault();if(['+','='].includes(e.key))zoom(1.2);else if(e.key==='-')zoom(1/1.2);else if(e.key==='Home')centre(view().focus);else{view().x+=e.key==='ArrowRight'?-40:e.key==='ArrowLeft'?40:0;view().y+=e.key==='ArrowDown'?-40:e.key==='ArrowUp'?40:0;transform();}});signal.addEventListener('abort',()=>request?.abort(),{once:true});void load();return{selectLink:pickLink,refresh:load,dispose(){abort.abort();}}; + }}; +})(); diff --git a/PlotLine/wwwroot/js/character-workspace.js b/PlotLine/wwwroot/js/character-workspace.js new file mode 100644 index 00000000..afa5c8b3 --- /dev/null +++ b/PlotLine/wwwroot/js/character-workspace.js @@ -0,0 +1,50 @@ +(() => { + '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;} + 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();} + function leave(){if(saving)return false;if(dirty()&&!confirm('Discard unsaved changes in this character workspace?'))return false;discard();return true;} + window.PlotDirectorCharacterWorkspace={isDirty:dirty,async requestLeave(navigate){if(!leave())return false;await navigate();return true;},refresh(){invalidate();}}; + 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'});}}} + 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();} + 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;} + 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 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;} + 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,'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;} + 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;} + }); + 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`); +})(); diff --git a/PlotLine/wwwroot/js/context-main-window.js b/PlotLine/wwwroot/js/context-main-window.js index 437a25d7..96d7f3f2 100644 --- a/PlotLine/wwwroot/js/context-main-window.js +++ b/PlotLine/wwwroot/js/context-main-window.js @@ -27,6 +27,7 @@ const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(10000)});if(!response.ok||response.redirected)throw Error();const value=await response.json(),destination=new URL(value.url,location.origin);if(destination.origin!==location.origin)throw Error(); const navigate=async()=>{status='focused';await connection.invoke('CompleteContextInteraction',delivery.commandID,status);try{window.focus();}catch{}location.assign(destination.href);}; if(window.PlotDirectorMapWorkspace?.requestLeave){if(!await window.PlotDirectorMapWorkspace.requestLeave(navigate))status='busy';return;} + if(window.PlotDirectorCharacterWorkspace?.requestLeave){if(!await window.PlotDirectorCharacterWorkspace.requestLeave(navigate))status='busy';return;} if(dirty&&!confirm('Leave this workspace with unsaved changes?')){status='busy';return;} await navigate();return; }catch{}finally{if(status!=='focused')await connection.invoke('CompleteContextInteraction',delivery.commandID,status).catch(()=>{});busy=false;}