Redesign main Character workspace with bounded tabs and safe relationship management
This commit is contained in:
parent
0fc459a270
commit
7ff5306c3b
84
Docs/Writer/Main-Character-Workspace-20261123.md
Normal file
84
Docs/Writer/Main-Character-Workspace-20261123.md
Normal file
@ -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 <disposable-scope>` 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.
|
||||
@ -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('<div data-character-workspace><header data-character-analysis-panel data-character-id="5" data-analysis-run-id="10" data-analysis-status="Completed"><span data-character-analysis-status>Completed</span><span data-character-analysis-message></span></header></div>');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});
|
||||
10
PlotLine.Tests/Browser/character-workspace-live.cjs
Normal file
10
PlotLine.Tests/Browser/character-workspace-live.cjs
Normal file
@ -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();}})();
|
||||
15
PlotLine.Tests/Browser/character-workspace.cjs
Normal file
15
PlotLine.Tests/Browser/character-workspace.cjs
Normal file
@ -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();}})();
|
||||
21
PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs
Normal file
21
PlotLine.Tests/CharacterWorkspaceBrowserFixture.cs
Normal file
@ -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<CharacterRelationship>{Relationship(9),Relationship(10),new(){CharacterRelationshipID=1,CharacterAID=1,CharacterBID=3,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=2,CharacterAID=3,CharacterBID=5,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=3,CharacterAID=4,CharacterBID=5,RelationshipTypeName="Biological Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=4,CharacterAID=6,CharacterBID=11,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=5,CharacterAID=12,CharacterBID=6,RelationshipTypeName="Adoptive Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=6,CharacterAID=13,CharacterBID=6,RelationshipTypeName="Step Parent",RelationshipCategoryName="Family"}}.Where(r=>!removed||r.CharacterRelationshipID!=9).ToArray();
|
||||
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));
|
||||
}
|
||||
}
|
||||
28
PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs
Normal file
28
PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs
Normal file
@ -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<string>("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<int>("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<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Parent'"),childType=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Child'"),friend=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'"),state=await db.ExecuteScalarAsync<int>("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<int> NewCharacter(SqlTransaction tx)=>await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Isolated workspace regression "+Guid.NewGuid().ToString("N")},tx,commandType:CommandType.StoredProcedure);
|
||||
async Task<int> Rel(SqlTransaction tx,int child,bool reciprocal=false,int? type=null,bool reverse=false)=>await db.QuerySingleAsync<int>("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<int> Event(SqlTransaction tx,int r,string description="Synthetic event")=>await db.QuerySingleAsync<int>("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<string,object>)(await rows.ReadAsync<dynamic>()).Single();await rows.ReadAsync<dynamic>();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<SqlTransaction,Task> 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<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsArchived=1",new{r},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE CharacterRelationshipID=@r",new{r},tx)==2,"erroneous parent definition archives reversibly without cascading its two events");await db.ExecuteAsync("dbo.Archive_Restore",new{EntityType="Relationship",EntityID=r},tx,commandType:CommandType.StoredProcedure);Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"existing canonical restore reactivates the same definition and retained history");});
|
||||
await Case("reciprocal single record and independent reverse",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterAID=@actor AND CharacterBID=@c OR CharacterAID=@c AND CharacterBID=@actor",new{actor,c},tx)==1,"canonical reciprocal flag does not create an extra reverse row");int reverse=await Rel(tx,c,false,childType,true);var frame=await Frame(tx,r);Check(frame.Other==1,"confirmation distinguishes a separately authored reverse fact");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@reverse",new{reverse},tx)==0,"independent reverse fact is retained, not silently cascaded");});
|
||||
foreach(var type in new[]{parent,friend})await Case("definition edit "+type,async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,type);var frame=await Frame(tx,r);await Change(tx,r,frame.Version,"definition");var row=await db.QuerySingleAsync<(int Type,int A,int B,bool Initial,string Notes)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID,IsInitialRelationship,Notes FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==type&&row.A==actor&&row.B==c&&row.Initial&&row.Notes=="Updated isolated definition","focused definition edit preserves pair/type and family/story meaning");});
|
||||
await Case("single event edit then remove",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);int e=await Event(tx,r),other=await Event(tx,r);var frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-edit",e:e,notes:"Updated one event");Check(await db.ExecuteScalarAsync<string>("SELECT Description FROM dbo.RelationshipEvents WHERE RelationshipEventID=@e",new{e},tx)=="Updated one event","one event changes without rewriting the definition");frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-remove",e:e);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE RelationshipEventID=@other",new{other},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"single-event deletion leaves the other event and definition active");});
|
||||
await Case("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<int>("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");
|
||||
|
||||
}
|
||||
}
|
||||
33
PlotLine.Tests/CharacterWorkspaceTests.cs
Normal file
33
PlotLine.Tests/CharacterWorkspaceTests.cs
Normal file
@ -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<ICharacterWorkspaceReader>((name,a)=>name switch{
|
||||
"Summary"=>Task.FromResult((new CharacterWorkspaceCounts{Relationships=2,Appearances=70},(IReadOnlyList<WorkspaceAgeRow>)Array.Empty<WorkspaceAgeRow>())),
|
||||
"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<CharacterWorkspaceEntry>)> Read(CharacterWorkspaceQuery q){records++;return Task.FromResult((1,(IReadOnlyList<CharacterWorkspaceEntry>)new[]{new CharacterWorkspaceEntry{ID=1,SceneID=q.SceneID??22,Heading="Recorded source",BookTitle="Book",Kind=q.Tab}}));}
|
||||
Task<(int,IReadOnlyList<CharacterImage>)> Gallery(){galleries++;return Task.FromResult((0,(IReadOnlyList<CharacterImage>)Array.Empty<CharacterImage>()));}Task Changed(){changes++;return Task.CompletedTask;}
|
||||
var repo=NativeWorkflowTests.Proxy<ICharacterRepository>((n,a)=>n switch{"GetCharacterAsync"=>Task.FromResult<Character?>((int)a![0]! ==99?null:character),"GetReferenceCharacterAsync"=>Task.FromResult<Character?>(character),"ListAliasesAsync"=>Alias(),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData()),_=>throw new Exception("Unexpected eager read: "+n)});
|
||||
Task<IReadOnlyList<CharacterAlias>> Alias(){aliases++;return Task.FromResult<IReadOnlyList<CharacterAlias>>(Enumerable.Range(1,75).Select(i=>new CharacterAlias{CharacterID=5,Alias="Alias "+i}).ToArray());}
|
||||
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
|
||||
var workspace=new CharacterWorkspace(repo,NativeWorkflowTests.Proxy<IProjectRepository>((n,_)=>n=="GetForUserAsync"?Task.FromResult<Project?>(new(){ProjectID=7,ProjectName="Author project",AccessRole=role}):throw new Exception("Unscoped project read")),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<IReadOnlyList<Book>>([])),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),NativeWorkflowTests.Proxy<ICharacterEnrichmentService>((_,_)=>Task.FromResult<CharacterEnrichmentCharacterStatus?>(null)),reader,NativeWorkflowTests.Proxy<IContextRelationshipReader>((_,_)=>throw new Exception("Unexpected graph/history read")),null!,new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance),NativeWorkflowTests.Proxy<IProjectActivityService>((_,_)=>Task.CompletedTask),NativeWorkflowTests.Proxy<ICharacterService>((_,_)=>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");}
|
||||
}
|
||||
}
|
||||
@ -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"));
|
||||
|
||||
@ -206,6 +206,10 @@ internal static class ToolbarBrowserHost
|
||||
builder.Services.AddSingleton(FixtureProxy<IFeatureRequestService>((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name)));
|
||||
builder.Services.AddSingleton(FixtureProxy<IOnboardingService>((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name)));
|
||||
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceGlobalProgressService>((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name)));
|
||||
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceService>((_,_)=>throw new NotSupportedException()));
|
||||
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceResultRepository>((_,_)=>throw new NotSupportedException()));
|
||||
builder.Services.AddSingleton(FixtureProxy<IOnboardingStoryIntelligenceService>((_,_)=>throw new NotSupportedException()));
|
||||
builder.Services.AddSingleton(FixtureProxy<ICharacterEnrichmentService>((name,_)=>name=="GetCurrentForCharacterAsync"?Task.FromResult<CharacterEnrichmentRun?>(null):throw new NotSupportedException(name)));
|
||||
builder.Services.AddSingleton<IHelpService, HelpService>();
|
||||
builder.Services.AddSingleton<IWritingSolverRepository, WritingSolverFixtureRepository>();
|
||||
builder.Services.AddSingleton<IWritingSolverWorkspaceContext, SolverWorkspaceFixture>();
|
||||
@ -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<ICompositeViewEngine>().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<ITempDataProvider>()),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<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false);
|
||||
var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"};
|
||||
@ -750,6 +765,7 @@ internal static class ToolbarBrowserHost
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + "' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><link rel='stylesheet' href='/css/scene-explorer.css'><script src='/js/scene-explorer.js'></script><script src='/js/narrative-focus.js' defer></script><script src='/js/narrative-focus-workspaces.js' defer></script><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-theme-sync.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script>" + writerScripts + "</body></html>");
|
||||
});
|
||||
app.MapHub<PlotLine.Hubs.StoryIntelligenceHub>("/hubs/story-intelligence");
|
||||
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");
|
||||
app.MapHub<PlotLine.Hubs.WordCompanionFollowHub>("/hubs/word-companion-follow");
|
||||
await app.RunAsync();
|
||||
|
||||
37
PlotLine/Controllers/CharacterWorkspaceController.cs
Normal file
37
PlotLine/Controllers/CharacterWorkspaceController.cs
Normal file
@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> Operation(int id,CharacterWorkspaceOperation input,CancellationToken ct)
|
||||
{
|
||||
if(input.CharacterID!=id)return Forbid();try{if(!ModelState.IsValid)throw new ArgumentException("Check the fields below.");await workspace.Change(input,ct);return Ok(new{saved=true,message=input.Action=="archive"?"Relationship removed from active views. History retained; restore is available in Archived Items.":input.Action=="event-remove"?"One relationship event removed.":"Relationship changes saved."});}
|
||||
catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){var frame=await workspace.Operation(id,input.RelationshipID,input.EventID,input.Action,ct);frame.Version=input.Version;frame.Notes=input.Notes;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Awareness=input.Awareness;frame.Confirmed=input.Confirmed;ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",frame);}
|
||||
}
|
||||
[HttpGet("Add/{id:int}")]
|
||||
public async Task<IActionResult> 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<IActionResult> 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);}}
|
||||
}
|
||||
@ -26,10 +26,9 @@ public sealed class CharactersController(ICharacterService characters) : Control
|
||||
return model is null ? NotFound() : View(model);
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Details(int id)
|
||||
public async Task<IActionResult> 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<IActionResult> Merge(int id)
|
||||
@ -292,10 +291,9 @@ public sealed class CharactersController(ICharacterService characters) : Control
|
||||
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> 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" });
|
||||
}
|
||||
}
|
||||
|
||||
48
PlotLine/Data/CharacterWorkspaceReader.cs
Normal file
48
PlotLine/Data/CharacterWorkspaceReader.cs
Normal file
@ -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<WorkspaceAgeRow> Ages)> Summary(int character,int user,CancellationToken ct);
|
||||
Task<(int Total,IReadOnlyList<CharacterWorkspaceEntry> 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<CharacterImage> 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<WorkspaceAgeRow>)> 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<CharacterWorkspaceCounts>(),(await grid.ReadAsync<WorkspaceAgeRow>()).ToList());}
|
||||
public async Task<(int,IReadOnlyList<CharacterWorkspaceEntry>)> 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<Count>()).Total,(await grid.ReadAsync<CharacterWorkspaceEntry>()).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<Count>()).Total;data=new(){Books=(await grid.ReadAsync<Book>()).ToList(),Chapters=(await grid.ReadAsync<Chapter>()).ToList(),Scenes=(await grid.ReadAsync<Scene>()).ToList(),Relationships=(await grid.ReadAsync<CharacterRelationship>()).ToList()};}
|
||||
if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Use the full Relationships Editor for a project beyond the workspace ordering limit.");
|
||||
var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var maximum=q.SceneID.HasValue?order.SingleOrDefault(s=>s.SceneID==q.SceneID)?.Ordinal??throw new UnauthorizedAccessException():order.Count-1;
|
||||
var events=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=maximum},commandType:CommandType.StoredProcedure,cancellationToken:ct))).ToList();await ParagraphEvidenceProjection.Apply(db,configuration,events);
|
||||
return(total,new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Relationships=data.Relationships,RelationshipEvents=events});
|
||||
}
|
||||
public async Task<(int,IReadOnlyList<CharacterImage>)> 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<Count>()).Total,(await grid.ReadAsync<CharacterImage>()).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<dynamic>()).Single();var json=JsonSerializer.Serialize((object)definition);var options=new JsonSerializerOptions{PropertyNameCaseInsensitive=true};var frame=JsonSerializer.Deserialize<CharacterRelationshipFrame>(json,options)!;frame.Relationship=JsonSerializer.Deserialize<CharacterRelationship>(json,options)!;
|
||||
var item=(await grid.ReadAsync<dynamic>()).SingleOrDefault();if(item==null)return(frame,null);json=JsonSerializer.Serialize((object)item);var eventFrame=JsonSerializer.Deserialize<CharacterWorkspaceEvent>(json,options)!;eventFrame.Record=JsonSerializer.Deserialize<RelationshipEvent>(json,options)!;return(frame,eventFrame);
|
||||
}
|
||||
public async Task Change(CharacterWorkspaceOperation input,int user,CancellationToken ct)
|
||||
{using var db=connections.CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=input.CharacterID,UserID=user,RelationshipID=input.RelationshipID,input.Version,input.Action,input.Confirmed,EventID=input.EventID,input.Notes,input.StateID,input.Intensity,input.Awareness},commandType:CommandType.StoredProcedure,cancellationToken:ct));}
|
||||
}
|
||||
@ -14,7 +14,7 @@ public sealed class ContextRelationshipReader(ISqlConnectionFactory connectionFa
|
||||
using var db=connectionFactory.CreateConnection();IReadOnlyList<Book> books;IReadOnlyList<Chapter> chapters;IReadOnlyList<Scene> scenes;IReadOnlyList<Character> people;IReadOnlyList<CharacterRelationship> links;Boundary boundary;
|
||||
using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextRelationshipLens_Read",new{ProjectID=project,UserID=user,FocusCharacterID=focus,Lens=lens,Depth=depth,PhysicalIDs=JsonSerializer.Serialize(physical)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))){books=(await grid.ReadAsync<Book>()).ToList();chapters=(await grid.ReadAsync<Chapter>()).ToList();scenes=(await grid.ReadAsync<Scene>()).ToList();people=(await grid.ReadAsync<Character>()).ToList();links=(await grid.ReadAsync<CharacterRelationship>()).ToList();boundary=await grid.ReadSingleAsync<Boundary>();}
|
||||
if(books.Count>20000||chapters.Count>20000||scenes.Count>20000)throw new ArgumentException("This project exceeds the Context narrative-order limit. Use the full Relationships Editor.");
|
||||
var order=StoryStateService.OrderScenes(new(){Books=books,Chapters=chapters,Scenes=scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var at=lens=="family"?order.Count-1:order.FirstOrDefault(s=>s.SceneID==scene)?.Ordinal??-1;
|
||||
var 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<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(links.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=at},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();
|
||||
await ParagraphEvidenceProjection.Apply(db,configuration,changes);
|
||||
return new(new(){Books=books,Chapters=chapters,Scenes=scenes,Characters=people,Relationships=links,RelationshipEvents=changes},boundary.FocusCharacterID,boundary.Truncated);
|
||||
|
||||
@ -298,6 +298,8 @@ public class Program
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipLenses>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IContextFamilyReader,PlotLine.Data.ContextFamilyReader>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextFamilyExploration>();
|
||||
builder.Services.AddScoped<PlotLine.Data.ICharacterWorkspaceReader,PlotLine.Data.CharacterWorkspaceReader>();
|
||||
builder.Services.AddScoped<PlotLine.Services.CharacterWorkspace>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterEditing>();
|
||||
builder.Services.AddSingleton<IManuscriptScanPreviewStore, ManuscriptScanPreviewStore>();
|
||||
builder.Services.AddSingleton<IOnboardingStoryIntelligenceBatchStore, OnboardingStoryIntelligenceBatchStore>();
|
||||
|
||||
67
PlotLine/Services/CharacterWorkspace.cs
Normal file
67
PlotLine/Services/CharacterWorkspace.cs
Normal file
@ -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<CharacterDetailViewModel> Header(int id,string? tab,CancellationToken ct)
|
||||
{
|
||||
if(tab!=null&&!Tabs.Contains(tab))throw new ArgumentException("Choose a character workspace tab.");var scope=await Scope(id);var summary=await reader.Summary(id,user.UserId!.Value,ct);var age=CharacterAgeDisplayService.GetProfileAge(scope.Character,summary.Ages.Select(r=>r.Scene).ToArray(),summary.Ages.Where(r=>r.IsAppearance).Select(r=>new SceneCharacter{CharacterID=id,SceneID=r.SceneID}).ToArray());
|
||||
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<CharacterWorkspacePage> 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<ContextFamilyTree> 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<ContextLensGraph> 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<IReadOnlyList<object>> 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<CharacterWorkspaceOperation> 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<CharacterDetailViewModel> 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);}
|
||||
}
|
||||
@ -75,12 +75,17 @@ public sealed class ContextFamilyExploration(ContextRelationshipLenses lenses,IC
|
||||
public async Task<ContextFamilyTree> Tree(int book,int scene,int focus,IReadOnlyList<int> expanded,CancellationToken cancellationToken)
|
||||
{
|
||||
var scope=await lenses.Scope(book,scene);var author=user.UserId!.Value;if((await characters.GetReferenceCharacterAsync(focus,author))?.ProjectID!=scope.Book.ProjectID)throw new UnauthorizedAccessException();
|
||||
var structure=await reader.Structure(scope.Book.ProjectID,author,Seeds(scope.Scene,focus),cancellationToken);var topology=new ContextFamilyTopology(structure.Links);var visible=topology.Visible(focus,expanded);var data=await reader.Tree(scope.Book.ProjectID,author,visible.People,visible.Links,cancellationToken);
|
||||
return await ReadProjectTree(scope.Book.ProjectID,author,focus,scope.Scene,scope.CanEdit,expanded,cancellationToken);
|
||||
}
|
||||
public async Task<ContextFamilyTree> ReadProjectTree(int project,int author,int focus,SceneEditViewModel scene,bool canEdit,IReadOnlyList<int> 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<int>{focus};var pending=new Queue<int>();pending.Enqueue(focus);while(pending.TryDequeue(out var id))foreach(var adjacent in current.Adjacent(id))if(reachable.Add(adjacent))pending.Enqueue(adjacent);
|
||||
var safe=new RelationshipMapData{Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters.Where(c=>reachable.Contains(c.CharacterID)).ToList(),Relationships=current.Links.Where(r=>reachable.Contains(r.CharacterAID)&&reachable.Contains(r.CharacterBID)).ToList(),RelationshipEvents=data.RelationshipEvents};
|
||||
var graph=ContextRelationshipLenses.Compose(new(safe,focus,visible.Truncated),"family",scope.Scene,scope.CanEdit);
|
||||
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));
|
||||
}
|
||||
|
||||
@ -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());
|
||||
}
|
||||
|
||||
105
PlotLine/Sql/306_CharacterWorkspaceReads.sql
Normal file
105
PlotLine/Sql/306_CharacterWorkspaceReads.sql
Normal file
@ -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
|
||||
72
PlotLine/Sql/307_CharacterWorkspaceManagement.sql
Normal file
72
PlotLine/Sql/307_CharacterWorkspaceManagement.sql
Normal file
@ -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
|
||||
24
PlotLine/Sql/308_CharacterWorkspaceConnectionSummaries.sql
Normal file
24
PlotLine/Sql/308_CharacterWorkspaceConnectionSummaries.sql
Normal file
@ -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
|
||||
31
PlotLine/ViewModels/CharacterWorkspaceModels.cs
Normal file
31
PlotLine/ViewModels/CharacterWorkspaceModels.cs
Normal file
@ -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<CharacterWorkspaceEntry> Entries{get;set;}=[];public IReadOnlyList<CurrentRelationshipViewModel> Relationships{get;set;}=[];public IReadOnlyList<CharacterImage> Images{get;set;}=[];public IReadOnlyList<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> 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<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> States{get;set;}=[];
|
||||
}
|
||||
@ -1969,9 +1969,9 @@ public sealed class CharacterEditViewModel
|
||||
|
||||
public IReadOnlyList<SelectListItem> 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<CharacterAlias> Aliases { get; set; } = [];
|
||||
|
||||
@ -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");
|
||||
}
|
||||
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Characters</a>
|
||||
<span>@Model.Character.CharacterName</span>
|
||||
</nav>
|
||||
|
||||
@{ViewData["DesktopLayout"]="details";ViewData["Title"]=Model.Character.CharacterName;ViewData["ProjectSection"]="Characters";var c=Model.Character;var analysis=Model.CharacterAnalysis;}
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb"><a asp-controller="Projects" asp-action="Index">Projects</a><a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a><a asp-action="Index" asp-route-projectId="@c.ProjectID">Characters</a><span>@c.CharacterName</span></nav>
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div data-pd-context="character" data-pd-context-id="@Model.Character.CharacterID" data-pd-context-label="@Model.Character.CharacterName" data-pwa-help class="page-heading pw-page-heading">
|
||||
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = Model.Character.CharacterName, ImagePath = Model.Character.AvatarImagePath ?? Model.Character.ImagePath, ThumbnailPath = Model.Character.AvatarThumbnailPath ?? Model.Character.ThumbnailPath, Size = "xl", Lazy = false })" />
|
||||
<div>
|
||||
<p class="eyebrow">Character</p>
|
||||
<h1>@Model.Character.CharacterName <help-icon key="characters.details" /></h1>
|
||||
<p class="lead-text">@Model.Character.DefaultDescription</p>
|
||||
</div>
|
||||
<div data-pwa-context="Manage" class="button-row">
|
||||
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Back to characters</a>
|
||||
<a class="btn btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@firstAppearance?.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Back to timeline</a>
|
||||
<div class="dropdown pw-actions">
|
||||
<button class="btn pw-actions__toggle dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
Actions
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<a class="dropdown-item" asp-action="Edit" asp-route-id="@Model.Character.CharacterID">Edit character</a>
|
||||
<a class="dropdown-item" asp-action="Merge" asp-route-id="@Model.Character.CharacterID">Merge with another character</a>
|
||||
<form asp-action="Reanalyse" method="post" data-character-reanalyse-form>
|
||||
<input type="hidden" name="id" value="@Model.Character.CharacterID" />
|
||||
<button class="dropdown-item" type="submit" data-character-reanalyse-button @(analysisActive ? "disabled" : string.Empty)>@analysisButtonText</button>
|
||||
</form>
|
||||
<a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@Model.Character.CharacterID">Export character</a>
|
||||
<a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@Model.Character.CharacterID" asp-route-format="markdown">Markdown</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<form asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this character? This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
|
||||
<input type="hidden" name="id" value="@Model.Character.CharacterID" />
|
||||
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||
<button class="dropdown-item text-danger" type="submit">Archive Character</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-character-workspace data-character-id="@c.CharacterID" data-project-id="@c.ProjectID" data-user-id="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value" data-initial-tab="@Model.WorkspaceTab" data-can-edit="@Model.WorkspaceCanEdit.ToString().ToLowerInvariant()">
|
||||
<header class="character-workspace-header" data-pd-context="character" data-pd-context-id="@c.CharacterID" data-pd-context-label="@c.CharacterName" data-pwa-help data-character-analysis-panel data-character-id="@c.CharacterID" data-book-id="@analysis.BookID" data-analysis-run-id="@analysis.CharacterEnrichmentRunID" data-analysis-status="@analysis.Status">
|
||||
<partial name="_Avatar" model="@(new AvatarViewModel{DisplayName=c.CharacterName,ImagePath=c.AvatarImagePath??c.ImagePath,ThumbnailPath=c.AvatarThumbnailPath??c.ThumbnailPath,Size="lg",Lazy=false})" />
|
||||
<div class="character-workspace-identity"><p class="eyebrow">@Model.Project.ProjectName · Character</p><h1>@c.CharacterName <help-icon key="characters.details"/></h1><span class="status-pill">@CharacterWorkspace.Classification(c.CharacterImportance)</span><span class="small" data-character-analysis-status>@(analysis.Status??"Not analysed")</span><span class="small" data-character-analysis-message>@analysis.CurrentMessage</span></div>
|
||||
<div class="button-row"><a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@c.ProjectID">Characters</a><a class="btn btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@c.ProjectID" asp-route-SelectedSceneID="@Model.WorkspaceCounts.FirstSceneID" asp-route-FocusType="character" asp-route-FocusID="@c.CharacterID">Timeline</a>
|
||||
@if(Model.WorkspaceCanEdit){<a class="btn btn-primary" asp-action="Edit" asp-route-id="@c.CharacterID">Edit character</a>}
|
||||
<div class="dropdown"><button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">Actions</button><div class="dropdown-menu dropdown-menu-end">
|
||||
@if(Model.WorkspaceCanEdit){<a class="dropdown-item" asp-action="Merge" asp-route-id="@c.CharacterID">Merge with another character</a><form asp-action="Reanalyse" method="post" data-character-reanalyse-form><input type="hidden" name="id" value="@c.CharacterID"/><button class="dropdown-item" data-character-reanalyse-button disabled="@(analysis.Status is CharacterEnrichmentStatuses.Queued or CharacterEnrichmentStatuses.Running)">Reanalyse character</button></form>}
|
||||
<a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@c.CharacterID">Export character</a><a class="dropdown-item" asp-controller="Exports" asp-action="Character" asp-route-id="@c.CharacterID" asp-route-format="markdown">Markdown</a>
|
||||
@if(Model.WorkspaceCanEdit){<form asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this character? Its data will be retained for restoration."><input type="hidden" name="id" value="@c.CharacterID"/><input type="hidden" name="projectId" value="@c.ProjectID"/><button class="dropdown-item text-danger">Archive character</button></form>}
|
||||
</div></div></div>
|
||||
</header>
|
||||
<div class="character-workspace-switch"><label>Find another character<input type="search" class="form-control" data-character-switch maxlength="120" placeholder="Name or alias"/></label><div data-character-matches></div></div>
|
||||
<nav class="character-workspace-tabs" role="tablist" aria-label="Character workspace">@foreach(var tab in CharacterWorkspace.Tabs){<a role="tab" id="character-tab-@tab" aria-controls="character-workspace-panel" aria-selected="@(Model.WorkspaceTab==tab?"true":"false")" data-character-tab="@tab" href="@Url.Action("Details",new{id=c.CharacterID,tab})">@(tab=="overview"?"Overview":tab=="relationships"?"Relationships":tab=="evolution"?"Evolution":tab=="appearances"?"Appearances":"Knowledge")</a>}</nav>
|
||||
<div data-workspace-status role="status"></div><section id="character-workspace-panel" data-workspace-panel role="tabpanel" tabindex="-1">@if(Model.WorkspacePage!=null){<partial name="/Views/Characters/_WorkspaceTab.cshtml" model="Model.WorkspacePage"/>}</section>
|
||||
<noscript><p>Select a tab above to open its content.</p></noscript>
|
||||
<dialog data-workspace-dialog aria-labelledby="character-operation-title"><div data-workspace-dialog-content></div><button type="button" data-workspace-dialog-fallback>Cancel</button></dialog>
|
||||
</div>
|
||||
|
||||
<nav class="pw-character-nav" aria-label="Character sections">
|
||||
<a class="pw-character-nav__link active" href="#character-overview">Overview</a>
|
||||
<a class="pw-character-nav__link" href="#character-relationships">Relationships</a>
|
||||
<a class="pw-character-nav__link" asp-controller="Dynamics" asp-action="Character" asp-route-id="@Model.Character.CharacterID">Arc</a>
|
||||
<a class="pw-character-nav__link" asp-controller="Dynamics" asp-action="Knowledge" asp-route-id="@Model.Character.CharacterID">Knowledge</a>
|
||||
<a class="pw-character-nav__link" href="#character-gallery">Gallery</a>
|
||||
<a class="pw-character-nav__link" href="#character-appearances">Appearances</a>
|
||||
</nav>
|
||||
|
||||
@if (TempData["ImageMessage"] is string imageMessage)
|
||||
{
|
||||
<span hidden data-toast-message="success">@imageMessage</span>
|
||||
}
|
||||
@if (TempData["ImageError"] is string imageError)
|
||||
{
|
||||
<div class="alert alert-warning">@imageError</div>
|
||||
}
|
||||
@if (TempData["RelationshipMessage"] is string relationshipMessage)
|
||||
{
|
||||
<span hidden data-toast-message="info">@relationshipMessage</span>
|
||||
}
|
||||
@if (TempData["CharacterMessage"] is string characterMessage)
|
||||
{
|
||||
<span hidden data-toast-message="info">@characterMessage</span>
|
||||
}
|
||||
|
||||
<section id="character-overview" class="asset-detail-grid">
|
||||
<article class="plain-card" data-character-analysis-panel data-character-id="@Model.Character.CharacterID" data-book-id="@analysis.BookID" data-analysis-run-id="@analysis.CharacterEnrichmentRunID" data-analysis-status="@analysis.Status">
|
||||
<h2>Profile</h2>
|
||||
<p><strong>Preferred name:</strong> @Model.Character.CharacterName</p>
|
||||
<p><strong>Life status:</strong> @(Model.Character.IsDeceased == true ? "Deceased" : Model.Character.IsDeceased == false ? "Living" : "Unrecorded") <small class="d-block muted">Global author reference; no death scene is implied.</small></p>
|
||||
<p><strong>Sex:</strong> @Model.Character.Sex</p>
|
||||
<p><strong>Date of birth:</strong> <span data-character-birth-date>@(Model.Character.BirthDate?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) ?? "Not recorded")</span></p>
|
||||
<p><strong>Age:</strong> <span data-character-profile-age>@Model.DisplayAge</span>
|
||||
<small class="d-block muted">@Model.AgeContext
|
||||
@if (Model.AgeReferenceScene is { } ageScene)
|
||||
{
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@ageScene.SceneID">@ageScene.SceneTitle · @ageScene.StartDateTime?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB"))</a>
|
||||
}
|
||||
</small>
|
||||
</p>
|
||||
<p><strong>Height:</strong> @Model.Character.Height</p>
|
||||
<p><strong>Eye colour:</strong> @Model.Character.EyeColour</p>
|
||||
<p><strong>Story importance:</strong> @storyImportance</p>
|
||||
<hr />
|
||||
<p><strong>Character analysis:</strong> <span data-character-analysis-status>@analysisStatus</span></p>
|
||||
<p><strong>Last analysed:</strong> <span data-character-analysis-last>@(lastAnalysed ?? "Not analysed")</span></p>
|
||||
@if (!string.IsNullOrWhiteSpace(analysis.CurrentMessage))
|
||||
{
|
||||
<p class="muted" data-character-analysis-message>@analysis.CurrentMessage</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="muted" data-character-analysis-message></p>
|
||||
}
|
||||
</article>
|
||||
<article class="plain-card" data-character-generated-analysis>
|
||||
<h2>Story Intelligence Analysis</h2>
|
||||
<p class="@(string.IsNullOrWhiteSpace(analysis.Summary) ? "muted" : string.Empty)" data-character-analysis-summary>@(analysis.Summary ?? "No generated character analysis yet.")</p>
|
||||
<p><strong>Date of birth:</strong> <span data-character-analysis-dob>@(analysis.DateOfBirth ?? "Unknown")</span></p>
|
||||
<p><strong>Age at start of series:</strong> <span data-character-analysis-age>@(analysis.AgeAtStartOfSeries ?? "Unknown")</span></p>
|
||||
<p><strong>Height:</strong> <span data-character-analysis-height>@(analysis.Height ?? "Unknown")</span></p>
|
||||
<p><strong>Eye colour:</strong> <span data-character-analysis-eye>@(analysis.EyeColour ?? "Unknown")</span></p>
|
||||
</article>
|
||||
<article class="plain-card">
|
||||
<h2>Known names</h2>
|
||||
<div class="asset-mini-list">
|
||||
@foreach (var name in knownNames)
|
||||
{
|
||||
var isPreferred = string.Equals(name, Model.Character.CharacterName, StringComparison.OrdinalIgnoreCase);
|
||||
<div class="asset-mini-item">
|
||||
<strong>@name</strong>
|
||||
@if (isPreferred)
|
||||
{
|
||||
<span class="status-pill">Preferred</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form asp-action="SetPreferredName" method="post">
|
||||
<input type="hidden" name="id" value="@Model.Character.CharacterID" />
|
||||
<input type="hidden" name="preferredName" value="@name" />
|
||||
<button class="btn btn-outline-secondary btn-sm" type="submit">Set as preferred</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</article>
|
||||
<article class="plain-card">
|
||||
<h2>Initial Relationships <help-icon key="characters.initialRelationships" /></h2>
|
||||
@if (!Model.InitialRelationships.Any())
|
||||
{
|
||||
<p class="muted">No initial relationships yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="asset-mini-list">
|
||||
@foreach (var categoryGroup in Model.InitialRelationships.GroupBy(x => new { x.RelationshipCategoryName, x.CategorySortOrder }).OrderBy(x => x.Key.CategorySortOrder).ThenBy(x => x.Key.RelationshipCategoryName))
|
||||
{
|
||||
<h3 class="eyebrow">@categoryGroup.Key.RelationshipCategoryName</h3>
|
||||
@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);
|
||||
<div class="asset-mini-item character-relationship-editor" data-relationship-editor>
|
||||
<div class="character-relationship-read" data-relationship-read>
|
||||
<div class="visual-card-heading">
|
||||
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = relatedCharacter?.CharacterName ?? relationship.CharacterBName, ImagePath = relatedCharacter?.AvatarImagePath ?? relatedCharacter?.ImagePath, ThumbnailPath = relatedCharacter?.AvatarThumbnailPath ?? relatedCharacter?.ThumbnailPath })" />
|
||||
<div>
|
||||
<strong>@relationship.CharacterAName -> @relationship.CharacterBName</strong>
|
||||
<span>@relationship.RelationshipTypeName <span class="status-pill">@relationship.RelationshipCategoryName</span></span>
|
||||
<span>Reciprocal: @(relationship.IsReciprocal ? "Yes" : "No")</span>
|
||||
<span>Reader initially knows: @(relationship.ReaderInitiallyKnows ? "Yes" : "No")</span>
|
||||
@if (!string.IsNullOrWhiteSpace(relationship.InitialRelationshipStateName) || relationship.InitialIntensity.HasValue)
|
||||
{
|
||||
<span>@relationship.InitialRelationshipStateName@if (relationship.InitialIntensity.HasValue) { <text> / Intensity @relationship.InitialIntensity</text> }</span>
|
||||
}
|
||||
@if (!string.IsNullOrWhiteSpace(relationship.InitialBookDisplayTitle))
|
||||
{
|
||||
<span>Initial book: @relationship.InitialBookDisplayTitle</span>
|
||||
}
|
||||
@if (!string.IsNullOrWhiteSpace(relationship.Notes))
|
||||
{
|
||||
<span>@relationship.Notes</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<a asp-action="Details" asp-route-id="@(relationship.CharacterAID == Model.Character.CharacterID ? relationship.CharacterBID : relationship.CharacterAID)">Open related character</a>
|
||||
<a asp-controller="Dynamics" asp-action="Relationship" asp-route-id="@relationship.CharacterRelationshipID">Evolution</a>
|
||||
<button class="btn btn-outline-primary btn-sm" type="button" data-relationship-edit>Edit</button>
|
||||
<form asp-action="ArchiveRelationship" method="post" class="archive-button-form" data-confirm-message="Remove this relationship? This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
|
||||
<input type="hidden" name="id" value="@relationship.CharacterRelationshipID" />
|
||||
<input type="hidden" name="characterId" value="@Model.Character.CharacterID" />
|
||||
<button class="btn btn-outline-danger btn-sm" type="submit">Remove</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<form asp-action="SaveInitialRelationship" method="post" class="row g-2 mt-2 d-none character-relationship-edit-form" data-relationship-form>
|
||||
<input type="hidden" name="CharacterRelationshipID" value="@relationship.CharacterRelationshipID" />
|
||||
<input type="hidden" name="ProjectID" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="CharacterID" value="@initialSourceId" />
|
||||
<input type="hidden" name="ReturnCharacterID" value="@Model.Character.CharacterID" />
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Related character <help-icon key="characters.relationships.relatedCharacter" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="RelatedCharacterID" required>
|
||||
@foreach (var option in Model.CharacterOptions.Where(x => x.Value != initialSourceId.ToString()))
|
||||
{
|
||||
<option value="@option.Value" selected="@(option.Value == initialRelatedId.ToString())">@option.Text</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Relationship type <help-icon key="characters.relationships.relationshipType" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="RelationshipTypeID">
|
||||
@foreach (var option in Model.RelationshipTypeOptions)
|
||||
{
|
||||
<option value="@option.Value" selected="@(option.Value == relationship.RelationshipTypeID.ToString())">@option.Text</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Awareness <help-icon key="characters.relationships.awareness" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="InitialRelationshipStateID">
|
||||
<option value="">No awareness state</option>
|
||||
@foreach (var option in Model.RelationshipStateOptions)
|
||||
{
|
||||
<option value="@option.Value" selected="@(option.Value == relationship.InitialRelationshipStateID?.ToString())">@option.Text</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Initial book <help-icon key="characters.relationships.initialBook" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="InitialBookID">
|
||||
<option value="">Project start</option>
|
||||
@foreach (var option in Model.BookOptions)
|
||||
{
|
||||
<option value="@option.Value" selected="@(option.Value == relationship.InitialBookID?.ToString())">@option.Text</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-8">
|
||||
<label class="form-label">Confidence / intensity <output>@(relationship.InitialIntensity ?? 5)</output> <help-icon key="characters.relationships.confidenceIntensity" mode="inline" /></label>
|
||||
<input class="form-range" name="InitialIntensity" type="range" min="1" max="10" step="1" value="@(relationship.InitialIntensity ?? 5)" oninput="this.previousElementSibling.querySelector('output').value = this.value" />
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-check mt-4">
|
||||
<input type="hidden" name="IsReciprocal" value="false" />
|
||||
<input class="form-check-input" name="IsReciprocal" type="checkbox" value="true" checked="@relationship.IsReciprocal" />
|
||||
<span class="form-check-label">Reciprocal <help-icon key="characters.relationships.reciprocal" mode="inline" /></span>
|
||||
</label>
|
||||
<label class="form-check">
|
||||
<input type="hidden" name="ReaderInitiallyKnows" value="false" />
|
||||
<input class="form-check-input" name="ReaderInitiallyKnows" type="checkbox" value="true" checked="@relationship.ReaderInitiallyKnows" />
|
||||
<span class="form-check-label">Reader initially knows <help-icon key="characters.relationships.readerInitiallyKnows" mode="inline" /></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Notes <help-icon key="characters.relationships.notes" mode="inline" /></label>
|
||||
<textarea class="form-control form-control-sm" name="Notes" rows="3">@relationship.Notes</textarea>
|
||||
</div>
|
||||
<div class="col-12 button-row">
|
||||
<button class="btn btn-outline-primary btn-sm" type="submit">Save Changes</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-relationship-cancel>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<details class="mt-3">
|
||||
<summary>Add initial relationship</summary>
|
||||
<form asp-action="SaveInitialRelationship" method="post" class="row g-2 mt-2">
|
||||
<input type="hidden" name="ProjectID" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="CharacterID" value="@Model.Character.CharacterID" />
|
||||
<input type="hidden" name="ReturnCharacterID" value="@Model.Character.CharacterID" />
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Related character <help-icon key="characters.relationships.relatedCharacter" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="RelatedCharacterID" required>
|
||||
<option value="">Choose character</option>
|
||||
@foreach (var option in Model.CharacterOptions.Where(x => x.Value != Model.Character.CharacterID.ToString()))
|
||||
{
|
||||
<option value="@option.Value">@option.Text</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Relationship type <help-icon key="characters.relationships.relationshipType" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="RelationshipTypeID" asp-items="Model.RelationshipTypeOptions"></select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Awareness <help-icon key="characters.relationships.awareness" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="InitialRelationshipStateID" asp-items="Model.RelationshipStateOptions">
|
||||
<option value="">No awareness state</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Initial book <help-icon key="characters.relationships.initialBook" mode="inline" /></label>
|
||||
<select class="form-select form-select-sm" name="InitialBookID" asp-items="Model.BookOptions">
|
||||
<option value="">Project start</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-8">
|
||||
<label class="form-label">Confidence / intensity <output>5</output> <help-icon key="characters.relationships.confidenceIntensity" mode="inline" /></label>
|
||||
<input class="form-range" name="InitialIntensity" type="range" min="1" max="10" step="1" value="5" oninput="this.previousElementSibling.querySelector('output').value = this.value" />
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-check mt-4">
|
||||
<input type="hidden" name="IsReciprocal" value="false" />
|
||||
<input class="form-check-input" name="IsReciprocal" type="checkbox" value="true" checked />
|
||||
<span class="form-check-label">Reciprocal <help-icon key="characters.relationships.reciprocal" mode="inline" /></span>
|
||||
</label>
|
||||
<label class="form-check">
|
||||
<input type="hidden" name="ReaderInitiallyKnows" value="false" />
|
||||
<input class="form-check-input" name="ReaderInitiallyKnows" type="checkbox" value="true" checked />
|
||||
<span class="form-check-label">Reader initially knows <help-icon key="characters.relationships.readerInitiallyKnows" mode="inline" /></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Notes <help-icon key="characters.relationships.notes" mode="inline" /></label>
|
||||
<textarea class="form-control form-control-sm" name="Notes" rows="2"></textarea>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<button class="btn btn-outline-primary btn-sm" type="submit">Add initial relationship</button>
|
||||
</div>
|
||||
</form>
|
||||
</details>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section id="character-gallery" class="list-section mt-3">
|
||||
<div class="d-flex align-items-start justify-content-between gap-3 flex-wrap mb-3">
|
||||
<div>
|
||||
<h2>Character Images <help-icon key="characters.images" /></h2>
|
||||
<p class="muted mb-0">Keep portraits, full-body references, clothing notes, expressions, and inspiration images together.</p>
|
||||
</div>
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Character.AvatarImagePath))
|
||||
{
|
||||
<form asp-action="RemoveAvatar" method="post" class="archive-button-form" data-confirm-message="Remove this character avatar? The gallery images will be kept.">
|
||||
<input type="hidden" name="id" value="@Model.Character.CharacterID" />
|
||||
<button class="btn btn-outline-secondary btn-sm" type="submit">Remove avatar</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
|
||||
<form asp-action="UploadImage" method="post" enctype="multipart/form-data" class="character-gallery-upload mb-3">
|
||||
<input type="hidden" name="CharacterID" value="@Model.Character.CharacterID" />
|
||||
<div>
|
||||
<label class="form-label" for="ImageUpload">Add image</label>
|
||||
<input class="form-control" id="ImageUpload" name="ImageUpload" type="file" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="form-label" for="Caption">Caption</label>
|
||||
<input class="form-control" id="Caption" name="Caption" maxlength="500" placeholder="Optional description" />
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">Upload</button>
|
||||
</form>
|
||||
|
||||
@if (!Model.Images.Any())
|
||||
{
|
||||
<p class="muted">No gallery images yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="character-gallery-grid">
|
||||
@foreach (var image in Model.Images)
|
||||
{
|
||||
var isAvatarSource = Model.Character.AvatarSourceCharacterImageID == image.CharacterImageID;
|
||||
<article class="character-gallery-card">
|
||||
<img src="@image.ThumbnailPath" alt="" loading="lazy" />
|
||||
<div class="character-gallery-card__body">
|
||||
<strong>@(string.IsNullOrWhiteSpace(image.Caption) ? "Character reference" : image.Caption)</strong>
|
||||
<span class="muted">Uploaded @image.UploadedDateUTC.ToLocalTime().ToString("yyyy-MM-dd")</span>
|
||||
@if (isAvatarSource)
|
||||
{
|
||||
<span class="status-pill">Avatar source</span>
|
||||
}
|
||||
</div>
|
||||
<div class="button-row character-gallery-card__actions">
|
||||
<a class="btn btn-outline-primary btn-sm" asp-action="CropAvatar" asp-route-imageId="@image.CharacterImageID">Create Avatar</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" href="@image.ImagePath" target="_blank" rel="noopener">Open</a>
|
||||
<form asp-action="DeleteImage" method="post" class="archive-button-form" data-confirm-message="Remove this image from the character gallery?">
|
||||
<input type="hidden" name="imageId" value="@image.CharacterImageID" />
|
||||
<input type="hidden" name="characterId" value="@Model.Character.CharacterID" />
|
||||
<button class="btn btn-outline-danger btn-sm" type="submit">Remove</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section id="character-relationships" class="list-section mt-3">
|
||||
<h2>Current Relationships <help-icon key="characters.currentRelationships" /></h2>
|
||||
@if (!Model.CurrentRelationships.Any())
|
||||
{
|
||||
<p class="muted">No current relationship state yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="asset-mini-list">
|
||||
@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))
|
||||
{
|
||||
<h3 class="eyebrow">@categoryGroup.Key.RelationshipCategoryName</h3>
|
||||
@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;
|
||||
<div class="asset-mini-item">
|
||||
<strong>@relatedCharacterName</strong>
|
||||
<span>@relationship.RelationshipTypeName <span class="status-pill">@relationship.RelationshipCategoryName</span> / Current: @current.CurrentStateName</span>
|
||||
<span>Reciprocal: @(relationship.IsReciprocal ? "Yes" : "No") / Confidence / intensity: @(current.CurrentIntensity?.ToString() ?? "Unknown")</span>
|
||||
@if (!string.IsNullOrWhiteSpace(current.CurrentNotes))
|
||||
{
|
||||
<span>@current.CurrentNotes</span>
|
||||
}
|
||||
<a asp-action="Details" asp-route-id="@relatedCharacterId">Open related character</a>
|
||||
<a asp-controller="Dynamics" asp-action="Relationship" asp-route-id="@relationship.CharacterRelationshipID">Evolution</a>
|
||||
<details>
|
||||
<summary>View History</summary>
|
||||
<div class="asset-mini-list mt-2">
|
||||
<div class="asset-mini-item">
|
||||
<strong>Initial: @relationship.RelationshipTypeName <span class="status-pill">@relationship.RelationshipCategoryName</span></strong>
|
||||
<span>@(relationship.InitialRelationshipStateName ?? "No awareness state")@if (relationship.InitialIntensity.HasValue) { <text> / Intensity @relationship.InitialIntensity</text> }</span>
|
||||
<span>Reader initially knows: @(relationship.ReaderInitiallyKnows ? "Yes" : "No")</span>
|
||||
@if (!string.IsNullOrWhiteSpace(relationship.Notes))
|
||||
{
|
||||
<span>@relationship.Notes</span>
|
||||
}
|
||||
</div>
|
||||
@foreach (var item in current.Events)
|
||||
{
|
||||
<div class="asset-mini-item">
|
||||
<strong>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</strong>
|
||||
<span>@item.RelationshipStateName <span class="status-pill">@item.RelationshipCategoryName</span> / Intensity @(item.Intensity?.ToString() ?? "Unknown")</span>
|
||||
<span>Awareness: @(item.IsKnownToOtherCharacter ? "known to other character" : "not known to other character")</span>
|
||||
@if (!string.IsNullOrWhiteSpace(item.Description))
|
||||
{
|
||||
<span>@item.Description</span>
|
||||
}
|
||||
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open scene</a>
|
||||
</div>
|
||||
}
|
||||
<div class="asset-mini-item">
|
||||
<strong>Current: @current.CurrentStateName</strong>
|
||||
<span>Confidence / intensity: @(current.CurrentIntensity?.ToString() ?? "Unknown")</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
<section class="list-section mt-3">
|
||||
<h2>Relationship Events <help-icon key="characters.relationshipEvents" /></h2>
|
||||
@if (!Model.RelationshipEvents.Any())
|
||||
{
|
||||
<p class="muted">No relationship events yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="asset-mini-list">
|
||||
@foreach (var item in Model.RelationshipEvents)
|
||||
{
|
||||
<div class="asset-mini-item">
|
||||
<strong>@item.CharacterAName -> @item.CharacterBName: @item.RelationshipStateName</strong>
|
||||
<span>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</span>
|
||||
<span>@item.RelationshipTypeName <span class="status-pill">@item.RelationshipCategoryName</span> / Awareness: @(item.IsKnownToOtherCharacter ? "known to other character" : "not known to other character")</span>
|
||||
<span>Reciprocal: @(item.IsReciprocal ? "Yes" : "No") / Confidence / intensity: @(item.Intensity?.ToString() ?? "Unknown")</span>
|
||||
@if (!string.IsNullOrWhiteSpace(item.Description))
|
||||
{
|
||||
<span>@item.Description</span>
|
||||
}
|
||||
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
|
||||
<a asp-action="Details" asp-route-id="@(item.CharacterAID == Model.Character.CharacterID ? item.CharacterBID : item.CharacterAID)">Open related character</a>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section id="character-appearances" class="list-section mt-3">
|
||||
<h2>Scene appearances <help-icon key="characters.sceneAppearances" /></h2>
|
||||
@if (!Model.Appearances.Any())
|
||||
{
|
||||
<p class="muted">No scene appearances yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="asset-mini-list">
|
||||
@foreach (var appearance in Model.Appearances)
|
||||
{
|
||||
<div class="asset-mini-item">
|
||||
<strong>@appearance.BookDisplayTitle / Ch @appearance.ChapterNumber / Scene @appearance.SceneNumber: @appearance.SceneTitle</strong>
|
||||
<span>@appearance.RoleInSceneTypeName / @appearance.PresenceTypeName</span>
|
||||
<span>@appearance.OutfitDescription @appearance.PhysicalCondition @appearance.EmotionalState</span>
|
||||
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@appearance.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="list-section mt-3">
|
||||
<h2>Attribute history <help-icon key="characters.attributeHistory" /></h2>
|
||||
@if (!Model.AttributeEvents.Any())
|
||||
{
|
||||
<p class="muted">No attribute events yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="asset-mini-list">
|
||||
@foreach (var item in Model.AttributeEvents)
|
||||
{
|
||||
<div class="asset-mini-item">
|
||||
<strong>@item.AttributeName: @item.AttributeValue</strong>
|
||||
<span>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</span>
|
||||
<span>@item.Description</span>
|
||||
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="list-section mt-3">
|
||||
<h2>Knowledge <help-icon key="characters.knowledge" /></h2>
|
||||
@if (!Model.KnowledgeItems.Any())
|
||||
{
|
||||
<p class="muted">No knowledge entries yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="asset-mini-list">
|
||||
@foreach (var item in Model.KnowledgeItems)
|
||||
{
|
||||
<div class="asset-mini-item">
|
||||
<strong>@item.KnowledgeStateName: @(item.AssetName ?? item.ThreadTitle)</strong>
|
||||
<span>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</span>
|
||||
<span>@item.Description</span>
|
||||
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
|
||||
@section Scripts {
|
||||
<script src="~/js/character-enrichment-detail.js" asp-append-version="true"></script>
|
||||
<script>
|
||||
(() => {
|
||||
document.querySelectorAll("[data-relationship-editor]").forEach((editor) => {
|
||||
const read = editor.querySelector("[data-relationship-read]");
|
||||
const form = editor.querySelector("[data-relationship-form]");
|
||||
editor.querySelector("[data-relationship-edit]")?.addEventListener("click", () => {
|
||||
read?.classList.add("d-none");
|
||||
form?.classList.remove("d-none");
|
||||
});
|
||||
editor.querySelector("[data-relationship-cancel]")?.addEventListener("click", () => {
|
||||
form?.classList.add("d-none");
|
||||
read?.classList.remove("d-none");
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
@foreach(var key in new[]{"ImageMessage","RelationshipMessage","CharacterMessage"}){if(TempData[key] is string message){<span hidden data-toast-message="success">@message</span>}}
|
||||
@if(TempData["ImageError"] is string error){<div class="alert alert-warning">@error</div>}
|
||||
@section Scripts{
|
||||
<link rel="stylesheet" href="~/css/character-workspace.css" asp-append-version="true"/>
|
||||
<script src="~/js/context-relationship-layout.js" asp-append-version="true"></script>
|
||||
<script src="~/js/character-workspace-graph.js" asp-append-version="true"></script>
|
||||
<script src="~/js/character-workspace.js" asp-append-version="true"></script>
|
||||
<script src="~/js/character-enrichment-detail.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
||||
11
PlotLine/Views/Characters/_WorkspaceAdd.cshtml
Normal file
11
PlotLine/Views/Characters/_WorkspaceAdd.cshtml
Normal file
@ -0,0 +1,11 @@
|
||||
@model CharacterDetailViewModel
|
||||
<form method="post" asp-controller="CharacterWorkspace" asp-action="Add" asp-route-id="@Model.Character.CharacterID" data-workspace-operation-form>
|
||||
<h2 id="character-operation-title">Add an initial relationship</h2><p>Author-established definition for @Model.Character.CharacterName. For a scene-based development, use the source scene editor.</p><div asp-validation-summary="All" class="text-danger" role="alert"></div>
|
||||
<input type="hidden" name="CharacterID" value="@Model.Character.CharacterID"/><input type="hidden" name="ReturnCharacterID" value="@Model.Character.CharacterID"/>
|
||||
<label>Find the other character<input class="form-control" type="search" data-workspace-target-search maxlength="120"/></label><label>Other character<select class="form-select" name="RelatedCharacterID" required data-workspace-target><option value="">Search and select a character</option>@foreach(var item in Model.CharacterOptions){<option value="@item.Value" selected="@(Model.NewInitialRelationship.RelatedCharacterID.ToString()==item.Value)">@item.Text</option>}</select></label>
|
||||
<label>Relationship type<select class="form-select" name="RelationshipTypeID" required><option value="">Choose a recorded type</option>@foreach(var item in Model.RelationshipTypeOptions){<option value="@item.Value" selected="@(Model.NewInitialRelationship.RelationshipTypeID.ToString()==item.Value)">@item.Text</option>}</select></label>
|
||||
<label>Initial state<select class="form-select" name="InitialRelationshipStateID"><option value="">Not recorded</option>@foreach(var item in Model.RelationshipStateOptions){<option value="@item.Value" selected="@(Model.NewInitialRelationship.InitialRelationshipStateID?.ToString()==item.Value)">@item.Text</option>}</select></label>
|
||||
<label>Initial book<select class="form-select" name="InitialBookID"><option value="">Project initial reference</option>@foreach(var item in Model.BookOptions){<option value="@item.Value" selected="@(Model.NewInitialRelationship.InitialBookID?.ToString()==item.Value)">@item.Text</option>}</select></label>
|
||||
<label>Intensity<input class="form-control" type="number" min="1" max="10" name="InitialIntensity" value="@Model.NewInitialRelationship.InitialIntensity"/></label><label class="character-checkbox"><input type="checkbox" name="IsReciprocal" value="true" checked="@Model.NewInitialRelationship.IsReciprocal"/> Reciprocal (one shared record)</label><label class="character-checkbox"><input type="checkbox" name="ReaderInitiallyKnows" value="true" checked="@Model.NewInitialRelationship.ReaderInitiallyKnows"/> Reader initially knows</label>
|
||||
<label>Notes<textarea class="form-control" name="Notes" maxlength="4000" rows="6">@Model.NewInitialRelationship.Notes</textarea></label><div class="button-row"><button class="btn btn-primary">Save</button><button type="button" class="btn btn-outline-secondary" data-workspace-cancel>Cancel</button></div>
|
||||
</form>
|
||||
64
PlotLine/Views/Characters/_WorkspaceGallery.cshtml
Normal file
64
PlotLine/Views/Characters/_WorkspaceGallery.cshtml
Normal file
@ -0,0 +1,64 @@
|
||||
@model CharacterDetailViewModel
|
||||
<section id="character-gallery" class="list-section mt-3">
|
||||
<div class="d-flex align-items-start justify-content-between gap-3 flex-wrap mb-3">
|
||||
<div>
|
||||
<h2>Character Images <help-icon key="characters.images" /></h2>
|
||||
<p class="muted mb-0">Keep portraits, full-body references, clothing notes, expressions, and inspiration images together.</p>
|
||||
</div>
|
||||
@if (Model.WorkspaceCanEdit && !string.IsNullOrWhiteSpace(Model.Character.AvatarImagePath))
|
||||
{
|
||||
<form asp-action="RemoveAvatar" method="post" class="archive-button-form" data-confirm-message="Remove this character avatar? The gallery images will be kept." asp-controller="Characters">
|
||||
<input type="hidden" name="id" value="@Model.Character.CharacterID" />
|
||||
<button class="btn btn-outline-secondary btn-sm" type="submit">Remove avatar</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
|
||||
<form hidden="@(!Model.WorkspaceCanEdit)" asp-action="UploadImage" method="post" enctype="multipart/form-data" class="character-gallery-upload mb-3" asp-controller="Characters">
|
||||
<input type="hidden" name="CharacterID" value="@Model.Character.CharacterID" />
|
||||
<div>
|
||||
<label class="form-label" for="ImageUpload">Add image</label>
|
||||
<input class="form-control" id="ImageUpload" name="ImageUpload" type="file" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="form-label" for="Caption">Caption</label>
|
||||
<input class="form-control" id="Caption" name="Caption" maxlength="500" placeholder="Optional description" />
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">Upload</button>
|
||||
</form>
|
||||
|
||||
@if (!Model.Images.Any())
|
||||
{
|
||||
<p class="muted">No gallery images yet.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="character-gallery-grid">
|
||||
@foreach (var image in Model.Images)
|
||||
{
|
||||
var isAvatarSource = Model.Character.AvatarSourceCharacterImageID == image.CharacterImageID;
|
||||
<article class="character-gallery-card">
|
||||
<img src="@image.ThumbnailPath" alt="" loading="lazy" />
|
||||
<div class="character-gallery-card__body">
|
||||
<strong>@(string.IsNullOrWhiteSpace(image.Caption) ? "Character reference" : image.Caption)</strong>
|
||||
<span class="muted">Uploaded @image.UploadedDateUTC.ToLocalTime().ToString("yyyy-MM-dd")</span>
|
||||
@if (isAvatarSource)
|
||||
{
|
||||
<span class="status-pill">Avatar source</span>
|
||||
}
|
||||
</div>
|
||||
<div class="button-row character-gallery-card__actions">
|
||||
<a hidden="@(!Model.WorkspaceCanEdit)" class="btn btn-outline-primary btn-sm" asp-action="CropAvatar" asp-route-imageId="@image.CharacterImageID" asp-controller="Characters">Create Avatar</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" href="@image.ImagePath" target="_blank" rel="noopener">Open</a>
|
||||
<form hidden="@(!Model.WorkspaceCanEdit)" asp-action="DeleteImage" method="post" class="archive-button-form" data-confirm-message="Remove this image from the character gallery?" asp-controller="Characters">
|
||||
<input type="hidden" name="imageId" value="@image.CharacterImageID" />
|
||||
<input type="hidden" name="characterId" value="@Model.Character.CharacterID" />
|
||||
<button class="btn btn-outline-danger btn-sm" type="submit">Remove</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
21
PlotLine/Views/Characters/_WorkspaceOperation.cshtml
Normal file
21
PlotLine/Views/Characters/_WorkspaceOperation.cshtml
Normal file
@ -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;}
|
||||
<form method="post" asp-controller="CharacterWorkspace" asp-action="Operation" asp-route-id="@Model.CharacterID" data-workspace-operation-form>
|
||||
<h2 id="character-operation-title">@(Model.Action=="archive"?"Remove relationship":Model.Action=="event-remove"?"Remove one relationship event":Model.Action=="definition"?"Edit relationship definition":"Edit one relationship event")</h2>
|
||||
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
|
||||
<input asp-for="CharacterID" type="hidden"/><input asp-for="RelationshipID" type="hidden"/><input asp-for="EventID" type="hidden"/><input asp-for="Action" type="hidden"/><input asp-for="Version" type="hidden"/>
|
||||
<p><strong>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName</strong> · @r.RelationshipTypeName · @r.RelationshipCategoryName</p>
|
||||
@if(Model.Action=="archive"){
|
||||
<p>This removes the <strong>underlying relationship definition</strong> from active Family, Story and Timeline views. It archives one canonical record; it does not permanently delete it.</p><p><strong>@Model.Record.EventCount dependent scene events will be retained</strong>, including their source/history. Restore the definition through Archived Items to make them active again.</p><p>@(r.IsReciprocal?"Both directions of this reciprocal flag belong to this one record and will be removed together.":"This is a directional record.")</p>@if(Model.Record.OtherPairRecords>0){<p class="alert alert-warning">@Model.Record.OtherPairRecords separately recorded relationship(s) between these characters will remain. They are independent authored records; review them separately.</p>}
|
||||
}else if(Model.Action=="event-remove"){
|
||||
<p>This permanently removes <strong>only event #@Model.EventID</strong> at scene #@Model.Event?.Record.SceneID. The relationship definition and other events remain. Its derived state will be recalculated from the remaining records.</p>
|
||||
}
|
||||
@if(linked){<p class="alert alert-warning">This event has manuscript evidence, review provenance or source dependencies. Direct modification/removal is blocked so that evidence is not orphaned. Use its source/review workflow.</p><a asp-controller="Scenes" asp-action="Edit" asp-route-id="@Model.Event?.Record.SceneID">Open source scene</a>}
|
||||
else if(!destructive){
|
||||
<p class="small">@(Model.Action=="definition"?"The pair, type, direction, book and narrative start/end remain unchanged. Use the full Relationships Editor for structural changes.":"This changes one recorded development at its original scene, not the definition or other events.")</p>
|
||||
@if(Model.Action!="definition"||r.IsInitialRelationship){<label asp-for="StateID">@(Model.Action=="definition"?"Initial state":"Recorded event state")</label><select asp-for="StateID" asp-items="Model.States" class="form-select"><option value="">Not recorded</option></select><label asp-for="Intensity">Intensity (1–10)</label><input asp-for="Intensity" type="number" min="1" max="10" class="form-control"/><label class="character-checkbox"><input asp-for="Awareness"/> @(Model.Action=="definition"?"Reader initially knows":"Known to the other character at this event")</label>}
|
||||
<label asp-for="Notes">@(Model.Action=="definition"?"Definition notes":"Event description")</label><textarea asp-for="Notes" rows="7" maxlength="4000" class="form-control"></textarea>
|
||||
}
|
||||
@if(destructive&&!linked){<label class="character-checkbox"><input asp-for="Confirmed" required/> I confirm the scope and consequences above.</label>}
|
||||
<div class="button-row">@if(!linked){<button type="submit" class="btn @(destructive?"btn-danger":"btn-primary")">@(destructive?"Confirm removal":"Save")</button>}<button type="button" class="btn btn-outline-secondary" data-workspace-cancel>Cancel</button><a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@r.ProjectID" asp-route-focusCharacterId="@Model.CharacterID">Full Relationships Editor</a></div>
|
||||
</form>
|
||||
61
PlotLine/Views/Characters/_WorkspaceProfile.cshtml
Normal file
61
PlotLine/Views/Characters/_WorkspaceProfile.cshtml
Normal file
@ -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();}
|
||||
<div class="character-dossier"><div><article class="plain-card">
|
||||
<h2>Profile</h2>
|
||||
<p><strong>Preferred name:</strong> @Model.Character.CharacterName</p>
|
||||
<p><strong>Life status:</strong> @(Model.Character.IsDeceased == true ? "Deceased" : Model.Character.IsDeceased == false ? "Living" : "Unrecorded") <small class="d-block muted">Global author reference; no death scene is implied.</small></p>
|
||||
<p><strong>Sex:</strong> @Model.Character.Sex</p>
|
||||
<p><strong>Date of birth:</strong> <span data-character-birth-date>@(Model.Character.BirthDate?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) ?? "Not recorded")</span></p>
|
||||
<p><strong>Age:</strong> <span data-character-profile-age>@Model.DisplayAge</span>
|
||||
<small class="d-block muted">@Model.AgeContext
|
||||
@if (Model.AgeReferenceScene is { } ageScene)
|
||||
{
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@ageScene.SceneID">@ageScene.SceneTitle · @ageScene.StartDateTime?.ToString("d MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-GB"))</a>
|
||||
}
|
||||
</small>
|
||||
</p>
|
||||
<p><strong>Height:</strong> @Model.Character.Height</p>
|
||||
<p><strong>Eye colour:</strong> @Model.Character.EyeColour</p>
|
||||
<p><strong>Story importance:</strong> @storyImportance</p>
|
||||
<hr />
|
||||
<p><strong>Character analysis:</strong> <span data-character-analysis-status>@analysisStatus</span></p>
|
||||
<p><strong>Last analysed:</strong> <span data-character-analysis-last>@(lastAnalysed ?? "Not analysed")</span></p>
|
||||
@if (!string.IsNullOrWhiteSpace(analysis.CurrentMessage))
|
||||
{
|
||||
<p class="muted" data-character-analysis-message>@analysis.CurrentMessage</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="muted" data-character-analysis-message></p>
|
||||
}
|
||||
</article><article class="plain-card"><h2>Biography and description</h2>@if(Model.Character.DefaultDescription?.Length>800){<p class="character-long-text">@Model.Character.DefaultDescription[..600]…</p><details><summary>Read full recorded description</summary><p class="character-long-text">@Model.Character.DefaultDescription</p></details>}else{<p class="character-long-text">@(string.IsNullOrWhiteSpace(Model.Character.DefaultDescription)?"No description recorded.":Model.Character.DefaultDescription)</p>}@if(Model.WorkspaceCanEdit){<a asp-action="Edit" asp-route-id="@Model.Character.CharacterID" asp-controller="Characters">Edit profile and background</a>}</article><article class="plain-card">
|
||||
<h2>Known names</h2>
|
||||
<details open="@(knownNames.Length<=6)"><summary>Recorded names and aliases (@knownNames.Length)</summary><div class="asset-mini-list">
|
||||
@foreach (var name in knownNames)
|
||||
{
|
||||
var isPreferred = string.Equals(name, Model.Character.CharacterName, StringComparison.OrdinalIgnoreCase);
|
||||
<div class="asset-mini-item">
|
||||
<strong>@name</strong>
|
||||
@if (isPreferred)
|
||||
{
|
||||
<span class="status-pill">Preferred</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form asp-action="SetPreferredName" method="post" hidden="@(!Model.WorkspaceCanEdit)" asp-controller="Characters">
|
||||
<input type="hidden" name="id" value="@Model.Character.CharacterID" />
|
||||
<input type="hidden" name="preferredName" value="@name" />
|
||||
<button class="btn btn-outline-secondary btn-sm" type="submit">Set as preferred</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div></details>
|
||||
</article><p class="small">Showing up to 50 aliases. The full character editor retains every recorded name and alias.</p></div><aside><article class="plain-card"><h2>At a glance</h2><p>Recorded totals across the project. These are author records, not inferred viewpoint knowledge.</p><p><strong>Recorded family</strong><br/>@(Model.WorkspaceCounts.FamilyConnections??"No family connections recorded.")</p><p><strong>Recorded story relationships</strong><br/>@(Model.WorkspaceCounts.StoryConnections??"No story relationships recorded.")</p><p class="small">Up to three definitions per group; explore all connections in <a data-workspace-go="relationships" href="?tab=relationships">Relationships</a>.</p><div class="character-glance">@foreach(var item in new[]{("relationships","Relationships",Model.WorkspaceCounts.Relationships),("evolution","Attribute changes",Model.WorkspaceCounts.Attributes),("appearances","Scene appearances",Model.WorkspaceCounts.Appearances),("knowledge","Knowledge records",Model.WorkspaceCounts.Knowledge)}){<a data-workspace-go="@item.Item1" href="?tab=@item.Item1"><strong>@item.Item3</strong> @item.Item2</a>}</div></article><article class="plain-card" data-character-generated-analysis>
|
||||
<h2>Story Intelligence Analysis</h2>
|
||||
<p class="@(string.IsNullOrWhiteSpace(analysis.Summary) ? "muted" : string.Empty)" data-character-analysis-summary>@(analysis.Summary ?? "No generated character analysis yet.")</p>
|
||||
<p><strong>Date of birth:</strong> <span data-character-analysis-dob>@(analysis.DateOfBirth ?? "Unknown")</span></p>
|
||||
<p><strong>Age at start of series:</strong> <span data-character-analysis-age>@(analysis.AgeAtStartOfSeries ?? "Unknown")</span></p>
|
||||
<p><strong>Height:</strong> <span data-character-analysis-height>@(analysis.Height ?? "Unknown")</span></p>
|
||||
<p><strong>Eye colour:</strong> <span data-character-analysis-eye>@(analysis.EyeColour ?? "Unknown")</span></p>
|
||||
</article></aside></div>
|
||||
56
PlotLine/Views/Characters/_WorkspaceTab.cshtml
Normal file
56
PlotLine/Views/Characters/_WorkspaceTab.cshtml
Normal file
@ -0,0 +1,56 @@
|
||||
@model CharacterWorkspacePage
|
||||
@{var c=Model.Profile.Character;var q=Model.Query;var totalPages=Math.Max(1,(Model.Total+24)/25);}
|
||||
<div data-character-tab-content="@q.Tab" data-page="@q.Page" data-total="@Model.Total" data-scene="@q.SceneID">
|
||||
@if(q.Tab=="overview"){
|
||||
<partial name="/Views/Characters/_WorkspaceProfile.cshtml" model="Model.Profile"/>
|
||||
<section class="plain-card"><h2>Recent recorded changes</h2>@if(!Model.Entries.Any()){<p class="muted">No changes recorded yet.</p>}else{foreach(var entry in Model.Entries){<p><strong>@entry.Heading</strong> · @entry.State <span class="small">@entry.BookDisplayTitle · @entry.SceneTitle</span></p>}}<a data-workspace-go="evolution" href="?tab=evolution">Explore evolution</a></section>
|
||||
<details id="character-gallery" data-workspace-gallery><summary>Portraits and reference gallery (@Model.Profile.WorkspaceCounts.Images)</summary><div data-gallery-content>@{Model.Profile.Images=Model.Images;}<partial name="/Views/Characters/_WorkspaceGallery.cshtml" model="Model.Profile"/>@if(Model.Profile.WorkspaceCounts.Images>25){<button type="button" class="btn btn-outline-secondary" data-gallery-page="2">More gallery images</button>}</div></details>
|
||||
}else if(q.Tab=="gallery"){
|
||||
Model.Profile.Images=Model.Images;<partial name="/Views/Characters/_WorkspaceGallery.cshtml" model="Model.Profile"/>
|
||||
<div class="button-row">@if(q.Page>1){<button type="button" class="btn btn-outline-secondary" data-gallery-page="@(q.Page-1)">Previous images</button>}<span>Page @q.Page of @totalPages</span>@if(q.Page<totalPages){<button type="button" class="btn btn-outline-secondary" data-gallery-page="@(q.Page+1)">Next images</button>}</div>
|
||||
}else{
|
||||
<div class="character-tab-heading"><div><h2>@(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")</h2><p class="small">@(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.")</p></div>
|
||||
@if(q.Tab=="evolution"){<a class="btn btn-outline-secondary" asp-controller="Dynamics" asp-action="Character" asp-route-id="@c.CharacterID">Advanced arc, charts and continuity</a>}
|
||||
@if(q.Tab=="knowledge"){<a class="btn btn-outline-secondary" asp-controller="Dynamics" asp-action="Knowledge" asp-route-id="@c.CharacterID">Knowledge timeline and continuity</a>}
|
||||
@if(q.Tab=="relationships"&&Model.Profile.WorkspaceCanEdit){<button class="btn btn-primary" type="button" data-workspace-add>Add initial relationship</button>}
|
||||
</div>
|
||||
@if(q.Tab is "relationships" or "knowledge"){
|
||||
<div class="character-position"><strong>@(q.SceneID.HasValue?Model.PointLabel:"Latest recorded author reference")</strong><button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-position>Choose story point</button>@if(q.SceneID.HasValue){<button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-clear-position>All recorded / latest</button>}</div>
|
||||
}
|
||||
<form data-workspace-filter class="character-workspace-filters" action="@Url.Action("Tab","CharacterWorkspace",new{id=c.CharacterID})" method="get">
|
||||
<input type="hidden" name="Tab" value="@q.Tab"/><input type="hidden" name="SceneID" value="@q.SceneID"/><input type="hidden" name="RelationshipID" value="@q.RelationshipID"/>
|
||||
<label>Search<input class="form-control" name="Search" value="@q.Search" maxlength="120" placeholder="Recorded names, values or notes"/></label>
|
||||
@if(q.Tab!="relationships"){<label>Book<select class="form-select" name="BookID"><option value="">All books</option>@foreach(var book in Model.Books){<option value="@book.Value" selected="@(q.BookID?.ToString()==book.Value)">@book.Text</option>}</select></label>}
|
||||
@if(q.Tab=="evolution"){<label>Category<select class="form-select" name="Category"><option value="">All recorded changes</option>@foreach(var category in new[]{"attributes","relationships","knowledge","appearances"}){<option value="@category" selected="@(q.Category==category)">@category</option>}</select></label>}
|
||||
@if(q.Tab=="knowledge"){<label>Canonical state<input class="form-control" name="Category" value="@q.Category" placeholder="Exact recorded state, or blank" list="knowledge-states"/><datalist id="knowledge-states">@foreach(var state in Model.Entries.Select(e=>e.State).Where(s=>!string.IsNullOrEmpty(s)).Distinct()){<option value="@state"/>}</datalist></label>}
|
||||
<button class="btn btn-outline-primary">Apply filters</button></form>
|
||||
@if(q.Tab=="relationships"){
|
||||
<div class="character-relationship-lenses" role="group" aria-label="Relationship lens"><button class="btn btn-outline-primary" type="button" data-character-lens="family" aria-pressed="true">Family</button><button class="btn btn-outline-primary" type="button" data-character-lens="story" aria-pressed="false">Story</button></div>
|
||||
<div class="character-graph-toolbar"><button type="button" class="btn btn-outline-secondary" data-character-zoom="in" aria-label="Zoom in">+</button><button type="button" class="btn btn-outline-secondary" data-character-zoom="out" aria-label="Zoom out">−</button><button type="button" class="btn btn-outline-secondary" data-character-graph-centre>Centre selected person</button><button type="button" class="btn btn-outline-secondary" data-character-graph-reset>Centre this character</button><span data-character-graph-status role="status"></span></div>
|
||||
<div data-character-graph tabindex="0" role="group" aria-label="Character relationship diagram. Drag to pan; zoom with buttons. Arrow keys pan; plus and minus zoom."></div><div data-character-graph-selection class="small"></div><div class="character-graph-legend">Family: parent · biological · adoptive (dashed) · step (dotted) · partnership. Story: friendship (green), hostility (red), romance (purple), professional/social (blue).</div>
|
||||
<p class="small">Only recorded connections are shown. A relationship does not establish a first meeting, mutual trust or viewpoint knowledge.</p>
|
||||
<section data-character-relationship-records aria-label="Relationship records">
|
||||
@foreach(var current in Model.Relationships){var r=current.Relationship;var other=r.CharacterAID==c.CharacterID?r.CharacterBID:r.CharacterAID;var name=r.CharacterAID==c.CharacterID?r.CharacterBName:r.CharacterAName;
|
||||
<article class="character-record" data-workspace-relationship="@r.CharacterRelationshipID"><div><h3><a asp-controller="Characters" asp-action="Details" asp-route-id="@other" data-character-link>@name</a></h3><p>@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName · <strong>@r.RelationshipTypeName</strong> <span class="status-pill">@r.RelationshipCategoryName</span></p><p>@(q.SceneID.HasValue?"Selected-point state":"Latest recorded state"): @current.CurrentStateName @if(current.CurrentIntensity.HasValue&¤t.LatestEvent?.RelationshipStateName!="Not established / ended at this point"){<span>· Intensity @current.CurrentIntensity</span>}</p><p class="character-long-text">@current.CurrentNotes</p><p class="small">@(r.IsInitialRelationship?"Initial author definition":"Scene-established definition") · @(r.IsReciprocal?"One reciprocal record covers both directions":"Directional record")</p></div>
|
||||
<div class="button-row"><button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-select-relationship="@r.CharacterRelationshipID">Inspect connection</button><button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-history="@r.CharacterRelationshipID">History</button>
|
||||
@if(Model.Profile.WorkspaceCanEdit){<button class="btn btn-outline-primary btn-sm" type="button" data-workspace-operation="definition" data-relationship="@r.CharacterRelationshipID">Edit definition</button><button class="btn btn-outline-danger btn-sm" type="button" data-workspace-operation="archive" data-relationship="@r.CharacterRelationshipID">Remove relationship</button>}
|
||||
<a class="small" asp-controller="Dynamics" asp-action="Relationship" asp-route-id="@r.CharacterRelationshipID">Advanced evolution</a><a class="small" asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@c.ProjectID" asp-route-focusCharacterId="@c.CharacterID">Full Relationships Editor</a></div></article>}
|
||||
@if(!Model.Relationships.Any()){<p class="muted">No matching relationship definitions recorded. Add an initial relationship or use the scene editor for a scene-based development.</p>}
|
||||
</section><div data-character-history></div>
|
||||
}else{
|
||||
@if(!Model.Entries.Any()){<p class="muted">No matching records at this point. Change the filters or record information in its scene/source editor.</p>}
|
||||
@foreach(var group in Model.Entries.GroupBy(e=>new{e.BookID,e.BookDisplayTitle,e.ChapterNumber,e.SceneID,e.SceneTitle,e.SceneNumber})){
|
||||
<section class="character-history-group"><h3>@group.Key.BookDisplayTitle · Chapter @group.Key.ChapterNumber · Scene @group.Key.SceneNumber: @group.Key.SceneTitle</h3>
|
||||
@foreach(var item in group){<article class="character-record" data-workspace-entry="@item.ID" data-kind="@item.Kind"><details><summary><strong>@item.Heading</strong> · @item.State @if(item.IsPov){<span class="status-pill">POV</span>}<span class="small"> · @item.Kind · @item.EvidenceState</span></summary><div class="character-record-detail">
|
||||
@if(!string.IsNullOrWhiteSpace(item.Previous)){<p>Previous recorded value: @item.Previous</p>}<p class="character-long-text">@item.Notes</p>
|
||||
@if(item.EvidenceState is not (null or "Verified" or "Author record")){<p class="text-warning">Source evidence needs review; this is not established knowledge or a verified relationship development.</p>}
|
||||
@if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Open scene / source editor</a><a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@c.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@c.CharacterID" asp-route-navigateFocus="true">Timeline</a>}
|
||||
@if(item.RelatedCharacterID.HasValue){<a asp-controller="Characters" asp-action="Details" asp-route-id="@item.RelatedCharacterID" data-character-link>Related character</a>}
|
||||
@if(item.Kind=="relationships"&&Model.Profile.WorkspaceCanEdit&&item.RelationshipID.HasValue){<button type="button" class="btn btn-outline-secondary btn-sm" data-workspace-operation="event-edit" data-relationship="@item.RelationshipID" data-event="@item.ID">Edit this event</button><button type="button" class="btn btn-outline-danger btn-sm" data-workspace-operation="event-remove" data-relationship="@item.RelationshipID" data-event="@item.ID">Remove this event</button>}
|
||||
@if(q.Tab=="scenes"){<button type="button" class="btn btn-primary btn-sm" data-workspace-set-position="@item.SceneID">Use this story point</button>}
|
||||
</div></details></article>}
|
||||
</section>}
|
||||
}
|
||||
<div class="character-workspace-pagination"><span>@Model.Total recorded results · page @q.Page of @totalPages</span>@if(q.Page>1){<button type="button" class="btn btn-outline-secondary" data-workspace-page="@(q.Page-1)">Previous</button>}@if(q.Page<totalPages){<button type="button" class="btn btn-outline-secondary" data-workspace-page="@(q.Page+1)">Next</button>}</div>
|
||||
}
|
||||
</div>
|
||||
1
PlotLine/wwwroot/css/character-workspace.css
Normal file
1
PlotLine/wwwroot/css/character-workspace.css
Normal file
@ -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;}}
|
||||
@ -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;
|
||||
}
|
||||
|
||||
19
PlotLine/wwwroot/js/character-workspace-graph.js
Normal file
19
PlotLine/wwwroot/js/character-workspace-graph.js
Normal file
@ -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()<suppress){e.stopPropagation();e.preventDefault();}},{capture:true});listen(svg,'pointerdown',e=>{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();}};
|
||||
}};
|
||||
})();
|
||||
50
PlotLine/wwwroot/js/character-workspace.js
Normal file
50
PlotLine/wwwroot/js/character-workspace.js
Normal file
@ -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`);
|
||||
})();
|
||||
@ -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;}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user