diff --git a/Docs/Writer/Unified-Context-Enhancements-20261122.md b/Docs/Writer/Unified-Context-Enhancements-20261122.md index e5ba252d..e548e234 100644 --- a/Docs/Writer/Unified-Context-Enhancements-20261122.md +++ b/Docs/Writer/Unified-Context-Enhancements-20261122.md @@ -47,3 +47,13 @@ Names uses existing canonical characters, aliases, Unicode normalisation and `IN Focused canonical rename retains the previous spelling as an alias through the existing character service. Individual alias add/correct/remove uses existing canonical repository saves after full book/project/role checks, fingerprint validation and alias ownership verification. Canonical alias cannot be deleted through alias correction; use the name action. Names→Characters sends structured `character.focus` and never switches an unrelated tab. Full Names and Character editors remain linked. Qualification: clean build, 17 focused character/name assertions including Unicode-equivalent shared spelling and legitimate aliases; compiled Razor browser passes canonical/alias filtering, collision review, structured focus, focused alias form/cancel, independent same-tool panes and mobile widths. Migration298 applied/verified after `context-enhancement-phase3-20261122.bak` backup and VERIFYONLY. No character/name rows bulk changed. + +Phase 3 deployed commit `c63925c`; release `context-enhancement-phase3-c63925c-20261122T153035Z`; assembly/asset hashes and informational commit verified; authenticated Characters/Names HTTP reads passed. + +### Phase 4 + +Relationships reuses the Story Point snapshot / existing `RelationshipMapService.BuildAtScene`: scene participants first, Family separately from other narrative categories, directional versus reciprocal connections, current established state/intensity, recorded notes and up to three developments on demand. Future and unverified events are excluded by the existing canonical projection. Catalogue scope and search are independent per pane. The existing knowledge flag combines initial-reader/event-other-character semantics; the UI explicitly avoids treating it as proof of POV knowledge. No structured first-meeting field exists; explicit meeting notes are displayed, with no co-occurrence inference or invented date. + +One relationship modal supports adding an initial connection or a scene development, correcting existing initial state or the selected scene event. It reuses initial/event services and lookups, validates role/book/scene/character/relationship ownership and duplicates, protects stale drafts and preserves existing direction/type/pair. Ambiguous multiple or unverified same-scene events redirect the author to full-editor review. Existing initial save now hydrates the prior structural flags/start/end before saving, preserving those fields during a focused correction. + +Qualification: clean build; 10 focused assertions cover canonical future exclusion, Family/direction, loaded values, exact event save, stale and invalid pair/direction guards, initial save, foreign relationship/scene and read-only denial. Compiled Razor browser covers category separation, directional display, evidence limitations, saved modal values/cancel, independent same-tool filters and full/half/stacked/mobile layouts. No schema migration needed. diff --git a/PlotLine.Tests/Browser/context-relationships.cjs b/PlotLine.Tests/Browser/context-relationships.cjs new file mode 100644 index 00000000..092065a2 --- /dev/null +++ b/PlotLine.Tests/Browser/context-relationships.cjs @@ -0,0 +1,15 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'); +const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();let step='setup';try{ + const context=await browser.newContext({viewport:{width:1366,height:768}});let posts=0,fail=true; + await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))})); + for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await context.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}})); + await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});}); + await context.route('**/Writing/Context/EditCharacter*',async r=>{const post=r.request().method()==='POST';if(post)posts++;if(post&&!fail)return r.fulfill({json:{saved:true,bookId:12}});const response=await r.fetch({url:base+'/context-edit-fixture?field=description'+(post?'&invalid=true':''),method:'GET'});await r.fulfill({status:post?422:200,contentType:'text/html',body:await response.text()});}); + await context.route('**/Writing/Context/EditRelationship*',async r=>{if(r.request().method()==='POST')posts++;await r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture',method:'GET'})});}); + const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/Writing/Context');await page.selectOption('[data-context-tab]','characters');await page.waitForSelector('[data-character-explorer]'); + step='family and narrative split';await page.selectOption('[data-context-tab]','relationships');await page.waitForSelector('[data-context-relationships]');assert.match(await page.locator('[data-context-relationships]').textContent(),/Family connections[\s\S]*Parent[\s\S]*Narrative connections[\s\S]*Friend/);assert.equal(await page.locator('[data-context-relationship]:visible').count(),2);await page.locator('[data-context-relationship="9"] summary').first().click();assert.match(await page.locator('[data-context-relationship="9"]').innerText(),/Directional connection/);assert.match(await page.locator('[data-context-relationship="9"]').innerText(),/no structured marker/); + step='focused relationship modal';await page.locator('[data-context-relationship="9"] [data-context-relationship-edit="scene"]').click();await page.waitForSelector('[data-context-edit-form]');assert.equal(await page.locator('[name=Notes]').inputValue(),'Saved scene note');await page.click('[data-context-edit-cancel]');assert.equal(posts,0); + step='independent filtering and responsive layouts';await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','relationships');await page.locator('[data-context-pane="1"] [data-relationship-filter]').fill('Friend');assert.equal(await page.locator('[data-context-pane="1"] [data-context-relationship]:visible').count(),1);assert.equal(await page.locator('[data-context-pane="0"] [data-context-relationship]:visible').count(),2);for(const width of [1366,760,390]){await page.setViewportSize({width,height:800});for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(40);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}} + assert.deepEqual(errors,[]);console.log('PASS Relationships browser: family/narrative categories, direction, explicit evidence limits, focused saved-value modal/cancel, independent filters and full/half/stacked/mobile layouts'); +} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await browser.close();}})(); diff --git a/PlotLine.Tests/ContextRelationshipTests.cs b/PlotLine.Tests/ContextRelationshipTests.cs new file mode 100644 index 00000000..0c87148e --- /dev/null +++ b/PlotLine.Tests/ContextRelationshipTests.cs @@ -0,0 +1,27 @@ +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 ContextRelationshipTests +{ + static void Check(bool pass,string message){if(!pass)throw new Exception(message);Console.WriteLine("PASS Context relationships: "+message);} + public static async Task Run() + { + var r=new CharacterRelationship{CharacterRelationshipID=9,ProjectID=7,CharacterAID=5,CharacterBID=6,CharacterAName="From",CharacterBName="To",RelationshipTypeID=1,RelationshipTypeName="Parent",RelationshipCategoryName="Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",InitialIntensity=4}; + var events=new List{new(){RelationshipEventID=10,CharacterRelationshipID=9,SceneID=22,RelationshipStateID=2,RelationshipStateName="Changed",Description="Explicit scene note"},new(){RelationshipEventID=11,CharacterRelationshipID=9,SceneID=23,RelationshipStateID=3,RelationshipStateName="Future"}}; + RelationshipMapData Data()=>new(){Characters=[new(){CharacterID=5,CharacterName="From"},new(){CharacterID=6,CharacterName="To"}],Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10,SceneNumber=1},new(){SceneID=23,ChapterID=10,SceneNumber=2}],Relationships=[r],RelationshipEvents=events}; + var point=RelationshipMapService.BuildAtScene(Data(),new Dictionary{{22,0},{23,1}},22).Single();Check(point.CurrentStateName=="Changed"&&point.RelationshipCategoryName=="Family"&&!point.IsReciprocal,"canonical story-point state excludes future events, preserves Family and direction"); + var role="Owner";RelationshipEventCreateViewModel? saved=null;InitialRelationshipEditViewModel? initial=null; + var repository=NativeWorkflowTests.Proxy((name,_)=>name switch{"GetRelationshipMapAsync"=>Task.FromResult(Data()),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData{RelationshipTypes=[new(){RelationshipTypeID=1,TypeName="Parent",IsActive=true}],RelationshipStates=[new(){RelationshipStateID=1,StateName="Established",IsActive=true},new(){RelationshipStateID=2,StateName="Changed",IsActive=true}]}),_=>throw new Exception(name)}); + var service=NativeWorkflowTests.Proxy((name,args)=>{if(name=="UpdateRelationshipEventAsync"){saved=(RelationshipEventCreateViewModel)args![0]!;return Task.FromResult(10);}if(name=="SaveInitialRelationshipAsync"){initial=(InitialRelationshipEditViewModel)args![0]!;return Task.FromResult(9);}throw new Exception(name);}); + var client=NativeWorkflowTests.Proxy((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy((_,_)=>client);var hub=NativeWorkflowTests.Proxy>((_,_)=>clients); + var edit=new ContextRelationshipEditing(repository,service,NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})),NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){ProjectID=7,AccessRole=role})),NativeWorkflowTests.Proxy((_,_)=>4),new ContextWorkspaceNotifications(hub,NullLogger.Instance)); + var form=await edit.Read(12,22,9,"scene");Check(form.StateID==2&&form.Notes=="Explicit scene note","focused form loads current scene event values");form.Notes="Corrected scene note";await edit.Save(form);Check(saved?.RelationshipEventID==10&&saved.CharacterRelationshipID==9&&saved.CharacterAID==5&&saved.CharacterBID==6&&saved.SceneID==22,"save corrects only selected event using existing service"); + form.TargetID=5;try{await edit.Save(form);throw new Exception("invalid pair accepted");}catch(ArgumentException){Check(true,"invalid self-relationship rejected");}form.TargetID=6; + form.Mutual=true;try{await edit.Save(form);throw new Exception("direction changed");}catch(ArgumentException){Check(true,"existing directional relationship cannot silently become reciprocal");}form.Mutual=false; + events[0].Description="Changed elsewhere";try{await edit.Save(form);throw new Exception("stale accepted");}catch(InvalidOperationException){Check(true,"stale relationship drafts rejected");} + var start=await edit.Read(12,22,9,"initial");start.Notes="Initial correction";await edit.Save(start);Check(initial?.CharacterRelationshipID==9&&initial.InitialRelationshipStateID==1&&initial.CharacterID==5&&initial.RelatedCharacterID==6,"focused initial correction reuses existing initial relationship service"); + try{await edit.Read(12,22,999,"scene");throw new Exception("foreign ID accepted");}catch(UnauthorizedAccessException){Check(true,"unowned relationship ID rejected");} + try{await edit.Read(12,999,9,"scene");throw new Exception("foreign scene accepted");}catch(UnauthorizedAccessException){Check(true,"cross-book scene rejected");} + role="Viewer";try{await edit.Read(12,22,9,"scene");throw new Exception("viewer accepted");}catch(UnauthorizedAccessException){Check(true,"read-only relationship correction rejected");} + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index d58f7242..69278ea6 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -182,11 +182,13 @@ if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text. if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;} +if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;} if(args.Contains("--context-characters")){await ContextCharacterTests.Run();return;} if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;} var tests = new (string Name, Action Test)[] { + ("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()), ("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()), ("Context My Windows routing and lifecycle",ContextWindowsTests.Run), ("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index d3c4a4ac..eeada1f1 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -401,6 +401,11 @@ internal static class ToolbarBrowserHost if(context.Request.Query["invalid"]=="true"){data.ModelState.AddModelError("Value","Synthetic validation: draft retained.");model.Value="Entered draft";} await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); }); + app.MapGet("/context-relationship-edit-fixture",async context=>{ + var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextRelationshipEdit.cshtml",false); + var model=new PlotLine.Services.Context.ContextRelationshipForm{BookID=12,SceneID=22,RelationshipID=9,Mode="scene",SourceID=5,TargetID=6,TypeID=1,StateID=1,Label="Relationship development at selected scene",Notes="Saved scene note",Fingerprint="fixture",Characters=[new("Fixture participant","5"),new("Other character","6")],Types=[new("Family · Parent","1")],States=[new("Established","1")]}; + using var writer=new StringWriter();await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); + }); app.MapGet("/context-tab-fixture/{tool}",async context=> { var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22; @@ -417,11 +422,12 @@ internal static class ToolbarBrowserHost var appearances=scene.SceneCharacters.Concat(new SceneCharacter[]{new(){CharacterID=5,SceneID=21,PresenceTypeName="Present",LocationID=78},new(){CharacterID=5,SceneID=23,PresenceTypeName="Present",LocationID=79}}).ToList(); model.CharacterExplorer=PlotLine.Services.Context.ContextCharacterPanels.Compose(model,catalogue,appearances,[new(){LocationID=77,LocationName="Saved room"},new(){LocationID=78,LocationName="Earlier hall"},new(){LocationID=79,LocationName="Following garden"}],true); + model.RelationshipMap=new(){Relationships=[new(){CharacterRelationshipID=9,CharacterAID=5,CharacterBID=6,CharacterAName="Fixture participant",CharacterBName="A long established character name 6",RelationshipCategoryName="Family",RelationshipTypeName="Parent",CurrentStateName="Established",InitialStateEditable=true,Notes="Explicit recorded family note",History=[new(){SceneID=22,Label="Current scene",StateName="Established",Notes="An explicit development"}]},new(){CharacterRelationshipID=10,CharacterAID=5,CharacterBID=7,CharacterAName="Fixture participant",CharacterBName="Another character",RelationshipCategoryName="Social",RelationshipTypeName="Friend",CurrentStateName="Trusting",IsReciprocal=true}]}; model.NamePanel=new PlotLine.Services.Context.ContextNamePanel(7,12,true,PlotLine.Services.Context.ContextNames.Compose(catalogue,[new(){CharacterAliasID=11,CharacterID=5,Alias="Known variant"},new(){CharacterAliasID=12,CharacterID=6,Alias="Fixture participant"}]),new(){Results=[new(){DisplayName="Reference suggestion",RelatedForms="Known spelling variant"}]}); var action=new ActionContext(context,new RouteData(),new ActionDescriptor()); var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextTab.cshtml",false); using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; - data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()switch{"characters"=>"_WritingContextPeople","names"=>"_ContextNames",_=>"_WritingContextOverview"}; + data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()switch{"characters"=>"_WritingContextPeople","names"=>"_ContextNames","relationships"=>"_ContextRelationships",_=>"_WritingContextOverview"}; await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); }); diff --git a/PlotLine/Controllers/ContextToolsController.cs b/PlotLine/Controllers/ContextToolsController.cs index 58b9ae6f..9a25f951 100644 --- a/PlotLine/Controllers/ContextToolsController.cs +++ b/PlotLine/Controllers/ContextToolsController.cs @@ -4,7 +4,7 @@ using PlotLine.Services.Context; namespace PlotLine.Controllers; [Authorize,Route("Writing/Context"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] -public sealed class ContextToolsController(ContextCharacterEditing editing):Controller +public sealed class ContextToolsController(ContextCharacterEditing editing,ContextRelationshipEditing relationships):Controller { [HttpGet("EditCharacter")] public async Task EditCharacter(int bookId,int sceneId,int characterId,string field) @@ -19,6 +19,24 @@ public sealed class ContextToolsController(ContextCharacterEditing editing):Cont catch(Exception e)when(e is ArgumentException or InvalidOperationException){return await Invalid(model,e.Message);} catch(Microsoft.Data.SqlClient.SqlException){return await Invalid(model,"The correction could not be saved. Your draft is retained; retry when the connection recovers.");} } + [HttpGet("EditRelationship")] + public async Task EditRelationship(int bookId,int sceneId,int relationshipId=0,string mode="scene") + {try{return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",await relationships.Read(bookId,sceneId,relationshipId,mode));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}} + [HttpPost("EditRelationship"),ValidateAntiForgeryToken] + public async Task SaveRelationship(ContextRelationshipForm model) + { + try{if(ModelState.IsValid){await relationships.Save(model);return Ok(new{saved=true,bookId=model.BookID});}return await InvalidRelationship(model,"Check the correction below.");} + catch(UnauthorizedAccessException){return Forbid();} + catch(Exception e)when(e is ArgumentException or InvalidOperationException){return await InvalidRelationship(model,e.Message);} + catch(Microsoft.Data.SqlClient.SqlException){return await InvalidRelationship(model,"Save unavailable. Your draft is retained; retry when the connection recovers.");} + } + private async Task InvalidRelationship(ContextRelationshipForm input,string error) + { + ContextRelationshipForm frame; + try{frame=await relationships.Read(input.BookID,input.SceneID,input.RelationshipID,input.Mode);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);} + frame.SourceID=input.SourceID;frame.TargetID=input.TargetID;frame.TypeID=input.TypeID;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Mutual=input.Mutual;frame.Known=input.Known;frame.Notes=input.Notes;frame.Fingerprint=input.Fingerprint; + ModelState.AddModelError("",error);Response.StatusCode=422;return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",frame); + } private async Task Invalid(ContextCharacterEditForm input,string error) { ContextCharacterEditForm frame; diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index 61255cce..d80122d1 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -103,6 +103,10 @@ public sealed class WritingController( public Task ContextCharacters(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId = null, Guid? sessionId = null) => RenderContextTab("_WritingContextPeople", projectId, bookId, chapterId, sceneId, instanceId, sessionId); + [HttpGet("Context/Tabs/relationships")] + public Task ContextRelationships(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId=null,Guid? sessionId=null) + =>RenderContextTab("_ContextRelationships",projectId,bookId,chapterId,sceneId,instanceId,sessionId); + [HttpGet("Context/Tabs/names")] public Task ContextNamesTab(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId=null,Guid? sessionId=null) =>RenderContextTab("_ContextNames",projectId,bookId,chapterId,sceneId,instanceId,sessionId); @@ -128,7 +132,7 @@ public sealed class WritingController( return Conflict(new { message = "Word position changed while context was loading." }); if (model?.HasScene != true) return NotFound(); if (projectAccess == null || !await projectAccess.CanAccessProjectAsync(model.Context!.Position.ProjectId)) return Forbid(); - if(partial=="_WritingContextPeople"&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model); + if((partial=="_WritingContextPeople"||partial=="_ContextRelationships")&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model); if(partial=="_ContextNames"&&contextNames!=null)model.NamePanel=await contextNames.Build(model.Context!.Position.ProjectId,model.Context.Position.BookId!.Value); ViewData["ContextTabPartial"] = partial; return PartialView("_ContextTab", model); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 495c2c75..1cd57810 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -293,6 +293,7 @@ public class Program builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Services/Context/ContextRelationshipEditing.cs b/PlotLine/Services/Context/ContextRelationshipEditing.cs new file mode 100644 index 00000000..0d7630e4 --- /dev/null +++ b/PlotLine/Services/Context/ContextRelationshipEditing.cs @@ -0,0 +1,66 @@ +using System.ComponentModel.DataAnnotations; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Rendering; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.ViewModels; +namespace PlotLine.Services.Context; +public sealed class ContextRelationshipForm +{ + public int BookID{get;set;}public int SceneID{get;set;}public int RelationshipID{get;set;}public string Mode{get;set;}="scene";public string Fingerprint{get;set;}=""; + public int SourceID{get;set;}public int TargetID{get;set;}public int TypeID{get;set;}public int StateID{get;set;} + [Range(1,10)]public int? Intensity{get;set;}public bool Mutual{get;set;}public bool Known{get;set;}[StringLength(4000)]public string? Notes{get;set;} + public string Label{get;set;}="";public IReadOnlyList Characters{get;set;}=[];public IReadOnlyList Types{get;set;}=[];public IReadOnlyList States{get;set;}=[]; +} +// Focused adapter over existing canonical initial-relationship and event operations. +public sealed class ContextRelationshipEditing(ICharacterRepository repository,ICharacterService characters,IWordCompanionRepository access,IBookRepository books,IProjectRepository projects,ICurrentUserService user,ContextWorkspaceNotifications notifications) +{ + private static readonly SemaphoreSlim[] Locks=Enumerable.Range(0,64).Select(_=>new SemaphoreSlim(1,1)).ToArray(); + private sealed record Frame(ContextRelationshipForm Form,RelationshipMapData Data,CharacterRelationship? Relationship,RelationshipEvent? Event,CharacterLookupData Lookups,int ProjectID); + public async Task Read(int bookId,int sceneId,int relationshipId,string mode)=>(await Load(bookId,sceneId,relationshipId,mode)).Form; + private async Task Load(int bookId,int sceneId,int relationshipId,string mode) + { + var author=user.UserId??throw new UnauthorizedAccessException();var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException(); + if(!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))throw new UnauthorizedAccessException(); + var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException();if(!ContextEditPolicy.CanEdit(await projects.GetForUserAsync(book.ProjectID,author)))throw new UnauthorizedAccessException(); + if(mode is not ("initial" or "scene"))throw new ArgumentException("Choose initial state or a scene development."); + var data=await repository.GetRelationshipMapAsync(book.ProjectID);var lookups=await repository.GetLookupsAsync(book.ProjectID); + var relation=relationshipId>0?data.Relationships.SingleOrDefault(r=>r.CharacterRelationshipID==relationshipId&&!r.IsArchived):null; + if(relationshipId>0&&(relation==null||relation.ProjectID!=book.ProjectID))throw new UnauthorizedAccessException(); + if(mode=="initial"&&relation!=null&&!relation.IsInitialRelationship)throw new ArgumentException("This relationship starts in a scene. Correct its development rather than adding an earlier initial state."); + var events=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==relationshipId&&e.SceneID==sceneId).ToList(); + if(mode=="scene"&&(events.Count>1||events.Any(e=>e.EvidenceState!="Verified")))throw new ArgumentException("Review multiple or unverified scene events in the full Relationships Editor before correcting this relationship."); + var change=mode=="scene"?events.SingleOrDefault():null; + var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i); + var projected=RelationshipMapService.BuildAtScene(data,order,sceneId).SingleOrDefault(r=>r.CharacterRelationshipID==relationshipId); + if(relation!=null&&projected==null)throw new ArgumentException("This relationship is not established at the selected story point."); + var state=mode=="initial"?relation?.InitialRelationshipStateID:change?.RelationshipStateID??lookups.RelationshipStates.FirstOrDefault(s=>s.StateName==projected?.CurrentStateName)?.RelationshipStateID; + var form=new ContextRelationshipForm{BookID=bookId,SceneID=sceneId,RelationshipID=relationshipId,Mode=mode,SourceID=relation?.CharacterAID??0,TargetID=relation?.CharacterBID??0,TypeID=relation?.RelationshipTypeID??0,StateID=state??0, + Intensity=mode=="initial"?relation?.InitialIntensity:change?.Intensity??projected?.CurrentIntensity,Mutual=relation?.IsReciprocal??false,Known=mode=="initial"?relation?.ReaderInitiallyKnows??false:change?.IsKnownToOtherCharacter??false, + Notes=mode=="initial"?relation?.Notes:change?.Description,Label=mode=="initial"?"Initial relationship (before scene developments)":"Relationship development at the selected scene", + Characters=data.Characters.Where(c=>!c.IsArchived).OrderBy(c=>c.CharacterName).Select(c=>new SelectListItem(c.CharacterName,c.CharacterID.ToString())).ToList(), + Types=lookups.RelationshipTypes.Where(t=>t.IsActive||t.RelationshipTypeID==relation?.RelationshipTypeID).Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToList(), + States=lookups.RelationshipStates.Where(s=>s.IsActive||s.RelationshipStateID==state).Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToList()}; + form.Fingerprint=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new{relation,Events=data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==relationshipId).ToList(),Matches=data.Relationships.Select(r=>new{r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID,r.RelationshipTypeID,r.IsReciprocal,r.IsArchived})})))); + return new(form,data,relation,change,lookups,book.ProjectID); + } + public async Task Save(ContextRelationshipForm input) + { + var mutex=Locks[(input.BookID&int.MaxValue)%Locks.Length];await mutex.WaitAsync();try{ + var frame=await Load(input.BookID,input.SceneID,input.RelationshipID,input.Mode);var f=frame.Form;var r=frame.Relationship; + if(f.Fingerprint!=input.Fingerprint)throw new InvalidOperationException("Relationships changed in another window. Your draft is retained; cancel and reopen current values."); + if(input.SourceID==input.TargetID||!f.Characters.Any(c=>c.Value==input.SourceID.ToString())||!f.Characters.Any(c=>c.Value==input.TargetID.ToString())||!f.Types.Any(t=>t.Value==input.TypeID.ToString())||!f.States.Any(s=>s.Value==input.StateID.ToString()))throw new ArgumentException("Choose two different project characters and a recorded relationship type and state."); + if(input.Intensity is <1 or >10||input.Notes?.Length>4000)throw new ArgumentException("Intensity must be 1–10 and notes at most 4,000 characters."); + if(r!=null&&(r.CharacterAID!=input.SourceID||r.CharacterBID!=input.TargetID||r.RelationshipTypeID!=input.TypeID||r.IsReciprocal!=input.Mutual))throw new ArgumentException("Use the full Relationships Editor to change the pair, type or direction of an existing relationship."); + if(r==null&&frame.Data.Relationships.Any(x=>!x.IsArchived&&x.RelationshipTypeID==input.TypeID&&((x.CharacterAID==input.SourceID&&x.CharacterBID==input.TargetID)||(x.IsReciprocal&&x.CharacterAID==input.TargetID&&x.CharacterBID==input.SourceID))))throw new ArgumentException("This relationship already exists. Correct its recorded state or use the full editor."); + if(input.Mode=="initial")await characters.SaveInitialRelationshipAsync(new(){CharacterRelationshipID=r?.CharacterRelationshipID??0,ProjectID=frame.ProjectID,CharacterID=input.SourceID,RelatedCharacterID=input.TargetID,RelationshipTypeID=input.TypeID,InitialBookID=r?.InitialBookID,InitialRelationshipStateID=input.StateID,InitialIntensity=input.Intensity,IsReciprocal=input.Mutual,ReaderInitiallyKnows=input.Known,Notes=input.Notes}); + else{ + var edit=new RelationshipEventCreateViewModel{RelationshipEventID=frame.Event?.RelationshipEventID??0,CharacterRelationshipID=r?.CharacterRelationshipID,SceneID=input.SceneID,CharacterAID=input.SourceID,CharacterBID=input.TargetID,RelationshipTypeID=input.TypeID,RelationshipStateID=input.StateID,Intensity=input.Intensity,IsReciprocal=input.Mutual,IsKnownToOtherCharacter=input.Known,Description=input.Notes,ReturnProjectID=frame.ProjectID,ReturnBookID=input.BookID}; + if(frame.Event==null)await characters.AddRelationshipEventAsync(edit);else await characters.UpdateRelationshipEventAsync(edit); + } + await notifications.Invalidate(user.UserId!.Value,input.BookID); + }finally{mutex.Release();} + } +} diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 77c0e644..666c41ce 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -6059,6 +6059,7 @@ public sealed class RelationshipMapService(IProjectRepository projects, ICharact return new RelationshipMapRelationshipViewModel { + InitialStateEditable = relationship.IsInitialRelationship, CharacterRelationshipID = relationship.CharacterRelationshipID, CharacterAID = relationship.CharacterAID, CharacterAName = relationship.CharacterAName, @@ -10087,6 +10088,7 @@ public sealed class CharacterService( } var isNew = model.CharacterRelationshipID == 0; + var existing=isNew?null:await characters.GetRelationshipAsync(model.CharacterRelationshipID); var relationshipId = await characters.SaveRelationshipAsync(new CharacterRelationship { CharacterRelationshipID = model.CharacterRelationshipID, @@ -10094,7 +10096,9 @@ public sealed class CharacterService( CharacterAID = model.CharacterID, CharacterBID = model.RelatedCharacterID, RelationshipTypeID = model.RelationshipTypeID, - IsPermanent = true, + IsPermanent = existing?.IsPermanent ?? true, + StartSceneID = existing?.StartSceneID, + EndSceneID = existing?.EndSceneID, IsKnownToReader = model.ReaderInitiallyKnows, Notes = model.Notes, IsInitialRelationship = true, diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index ee86bd94..8a29b44b 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -2105,6 +2105,7 @@ public sealed class RelationshipMapLinkViewModel public sealed class RelationshipMapRelationshipViewModel { + public bool InitialStateEditable {get;set;} public bool Known { get; set; } public int CharacterRelationshipID { get; set; } public int CharacterAID { get; set; } diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 8315bf5c..0da5a0dc 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -7,7 +7,8 @@ var tabs = new[] { new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "scene.focus" } }, new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "characters", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "character.focus" } }, - new { id = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() } + new { id = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, + new { id = "relationships", displayName = "Relationships", endpoint = Url.Action("ContextRelationships", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "relationships", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "relationship.focus" } } }; } diff --git a/PlotLine/Views/Writing/_ContextRelationshipEdit.cshtml b/PlotLine/Views/Writing/_ContextRelationshipEdit.cshtml new file mode 100644 index 00000000..2c2331af --- /dev/null +++ b/PlotLine/Views/Writing/_ContextRelationshipEdit.cshtml @@ -0,0 +1,18 @@ +@model PlotLine.Services.Context.ContextRelationshipForm +
+@Html.AntiForgeryToken() + +

@Model.Label

+@if(Model.RelationshipID>0){

@Model.Characters.FirstOrDefault(c=>c.Value==Model.SourceID.ToString())?.Text @(Model.Mutual?"↔":"→") @Model.Characters.FirstOrDefault(c=>c.Value==Model.TargetID.ToString())?.Text · @Model.Types.FirstOrDefault(t=>t.Value==Model.TypeID.ToString())?.Text

} +else{ + + + +} + + + + +

Scene developments apply at this selected narrative point. Knowledge flags do not establish viewpoint knowledge. Notes are retained as author evidence; no first meeting is inferred.

+ +
diff --git a/PlotLine/Views/Writing/_ContextRelationships.cshtml b/PlotLine/Views/Writing/_ContextRelationships.cshtml new file mode 100644 index 00000000..fb24e59e --- /dev/null +++ b/PlotLine/Views/Writing/_ContextRelationships.cshtml @@ -0,0 +1,23 @@ +@model WritingContextDisplayViewModel +@{var position=Model.Context!.Position;var participants=Model.Context.Scene!.SceneCharacters.Select(c=>c.CharacterID).ToHashSet();if(Model.Context.Scene.POVCharacterID is int pov)participants.Add(pov); +var rows=(Model.AtPoint?.Relationships??Model.RelationshipMap?.Relationships??[]).OrderByDescending(r=>participants.Contains(r.CharacterAID)&&participants.Contains(r.CharacterBID)).ThenBy(r=>r.CharacterAName).ToList();var canEdit=Model.CharacterExplorer?.CanEdit==true;} +
+
+

Verified author reference at this scene. Reader and other-character flags are recorded separately by the underlying system; neither proves what the viewpoint character knows. Unverified claims are excluded from this state.

+@foreach(var family in new[]{true,false}){ +

@(family?"Family connections":"Narrative connections")

+@foreach(var r in rows.Where(r=>string.Equals(r.RelationshipCategoryName,"Family",StringComparison.OrdinalIgnoreCase)==family)){ +
+@r.CharacterAName @(r.IsReciprocal?"↔":"→") @r.CharacterBName@r.RelationshipTypeName · @r.CurrentStateName +

@r.RelationshipCategoryName · @(r.IsReciprocal?"Reciprocal connection":"Directional connection: From → To") @if(r.CurrentIntensity.HasValue){· Intensity @r.CurrentIntensity / 10}

+@if(!string.IsNullOrWhiteSpace(r.Notes)){

Recorded notes: @r.Notes

}else{

No author notes recorded for this state.

} +

First meeting: no structured marker is available. Explicit meeting evidence, if recorded, remains in the notes and developments below; earliest co-occurrence is never treated as a meeting.

+
Latest recorded developments (@r.History.Count)
    @foreach(var item in r.History.OrderBy(h=>h.SceneID.HasValue?(Model.Context.Narrative?.Scenes.ToList().FindIndex(s=>s.SceneID==h.SceneID)??-1):-1).Reverse().Take(3)){
  • @item.Label · @item.StateName @item.Notes @if(item.SceneID.HasValue){Source scene}
  • }
+@if(canEdit){
@if(r.InitialStateEditable){}
} +Open in Relationships Editor +
} +
} + +@if(canEdit){
} +

Open in Relationships Editor +
diff --git a/PlotLine/wwwroot/js/context-editing.js b/PlotLine/wwwroot/js/context-editing.js index e5566048..34cfa5e8 100644 --- a/PlotLine/wwwroot/js/context-editing.js +++ b/PlotLine/wwwroot/js/context-editing.js @@ -4,8 +4,8 @@ function state(deferRefresh=false){pane?.dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty,busy,deferRefresh}}));root.dispatchEvent(new CustomEvent('context-window-state',{detail:{busy:dialog.open}}));} function install(html){const doc=new DOMParser().parseFromString(html,'text/html');const form=doc.querySelector('[data-context-edit-form]');if(!form||doc.querySelector('html>head>title')||/{const button=event.target.closest('[data-context-edit]');if(!button||dialog.open)return; - pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const url=new URL('/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',fragment.dataset.sceneId);url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit); + root.addEventListener('click',async event=>{const button=event.target.closest('[data-context-edit],[data-context-relationship-edit]');if(!button||dialog.open)return; + pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const relationship=button.hasAttribute('data-context-relationship-edit');const url=new URL(relationship?'/Writing/Context/EditRelationship':'/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',fragment.dataset.sceneId);if(relationship){url.searchParams.set('relationshipId',button.dataset.relationshipId||'0');url.searchParams.set('mode',button.dataset.contextRelationshipEdit);}else{url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit);} dialog.showModal();dirty=false;busy=true;state();status.textContent='Loading current saved values…';host.replaceChildren();load=new AbortController(); try{const response=await fetch(url,{signal:load.signal,cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error('This correction is unavailable. Check sign-in and editing permission.');install(await response.text());status.textContent='';} catch(error){if(error.name!=='AbortError'){status.textContent=error.message;window.PlotDirector?.toast?.error(error.message);}} diff --git a/PlotLine/wwwroot/js/context-tools.js b/PlotLine/wwwroot/js/context-tools.js index 7d800d29..b2ea5313 100644 --- a/PlotLine/wwwroot/js/context-tools.js +++ b/PlotLine/wwwroot/js/context-tools.js @@ -50,3 +50,12 @@ dispose(element){const state=mounted.get(element);if(state){states.set(state.paneId,state.host.querySelector('[data-name-filter]').value);state.abort.abort();mounted.delete(element);}} }; })(); +(() => { + const saved=new Map(),mounted=new WeakMap(); + function apply(node){const q=node.querySelector('[data-relationship-filter]').value.toLocaleLowerCase(),all=node.querySelector('[data-relationship-scope]').value==='all';let count=0;node.querySelectorAll('[data-context-relationship]').forEach(row=>{row.hidden=(!all&&row.dataset.relevant!=='true')||!row.dataset.filterName.toLocaleLowerCase().includes(q);if(!row.hidden)count++;});node.querySelector('[data-relationship-empty]').hidden=count>0;} + window.PlotDirectorContextLifecycles.relationships={ + mount(node,{paneId}){const host=node.querySelector('[data-context-relationships]');if(!host)return;const abort=new AbortController();mounted.set(node,{paneId,abort});const prior=saved.get(paneId);if(prior){node.querySelector('[data-relationship-filter]').value=prior.filter;node.querySelector('[data-relationship-scope]').value=prior.scope;node.querySelectorAll('[data-context-relationship]').forEach(row=>row.open=prior.open.includes(row.dataset.contextRelationship));}node.addEventListener('input',()=>apply(node),{signal:abort.signal});node.addEventListener('change',()=>apply(node),{signal:abort.signal});apply(node);}, + dispose(node){const state=mounted.get(node);if(state){saved.set(state.paneId,{filter:node.querySelector('[data-relationship-filter]').value,scope:node.querySelector('[data-relationship-scope]').value,open:[...node.querySelectorAll('[data-context-relationship][open]')].map(r=>r.dataset.contextRelationship)});state.abort.abort();mounted.delete(node);}}, + onInteraction(node,command){if(command.action!=='relationship.focus')return 'not-visible';if(command.storyPoint?.sceneID&&command.storyPoint.sceneID!==Number(node.dataset.sceneId))return 'not-visible';const row=node.querySelector(`[data-context-relationship="${Number(command.relationshipID)}"]`);if(!row)return 'not-visible';node.querySelector('[data-relationship-filter]').value='';node.querySelector('[data-relationship-scope]').value='all';apply(node);row.open=true;row.classList.add('context-reference-focus');row.scrollIntoView({block:'nearest'});row.focus({preventScroll:true});return 'focused';} + }; +})();