From 6e6c7fdcd95223c5197c31fd8b1b4ccd0d7ed631 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 22 Nov 2026 15:25:06 +0000 Subject: [PATCH] Build compact scene-aware Context character explorer and focused corrections --- .../Unified-Context-Enhancements-20261122.md | 12 +++ PlotLine.Tests/Browser/context-characters.cjs | 18 +++++ PlotLine.Tests/Browser/context-my-windows.cjs | 1 + .../Browser/context-workspace-foundation.cjs | 2 +- PlotLine.Tests/ContextCharacterTests.cs | 43 +++++++++++ PlotLine.Tests/Program.cs | 2 + PlotLine.Tests/ToolbarBrowserHost.cs | 15 ++++ .../Controllers/ContextToolsController.cs | 29 +++++++ PlotLine/Controllers/WritingController.cs | 13 +++- PlotLine/Program.cs | 2 + .../Context/ContextCharacterEditing.cs | 76 +++++++++++++++++++ .../Context/ContextCharacterPanels.cs | 59 ++++++++++++++ PlotLine/Services/CoreServices.cs | 2 +- PlotLine/Services/MapStoryService.cs | 5 +- .../Sql/297_ContextCharacterImportDefault.sql | 18 +++++ PlotLine/ViewModels/CoreViewModels.cs | 1 + PlotLine/Views/Writing/Context.cshtml | 4 +- .../Writing/_ContextCharacterDetail.cshtml | 18 +++++ .../Writing/_ContextCharacterEdit.cshtml | 13 ++++ .../Writing/_ContextCharacterReference.cshtml | 6 ++ .../Writing/_WritingContextPeople.cshtml | 73 +++++------------- PlotLine/wwwroot/css/context-workspace.css | 13 ++++ PlotLine/wwwroot/js/context-editing.js | 25 ++++++ PlotLine/wwwroot/js/context-tools.js | 26 +++++++ PlotLine/wwwroot/js/context-workspace.js | 6 +- 25 files changed, 422 insertions(+), 60 deletions(-) create mode 100644 PlotLine.Tests/Browser/context-characters.cjs create mode 100644 PlotLine.Tests/ContextCharacterTests.cs create mode 100644 PlotLine/Controllers/ContextToolsController.cs create mode 100644 PlotLine/Services/Context/ContextCharacterEditing.cs create mode 100644 PlotLine/Services/Context/ContextCharacterPanels.cs create mode 100644 PlotLine/Sql/297_ContextCharacterImportDefault.sql create mode 100644 PlotLine/Views/Writing/_ContextCharacterDetail.cshtml create mode 100644 PlotLine/Views/Writing/_ContextCharacterEdit.cshtml create mode 100644 PlotLine/Views/Writing/_ContextCharacterReference.cshtml create mode 100644 PlotLine/wwwroot/js/context-editing.js diff --git a/Docs/Writer/Unified-Context-Enhancements-20261122.md b/Docs/Writer/Unified-Context-Enhancements-20261122.md index 9a9948c5..e75d6243 100644 --- a/Docs/Writer/Unified-Context-Enhancements-20261122.md +++ b/Docs/Writer/Unified-Context-Enhancements-20261122.md @@ -25,3 +25,15 @@ Contract: version, book ID, originating pane, action, canonical character/locati My Windows shows current capabilities and offers a scene-focus demonstration. Overview and Characters are minimal non-destructive handlers; later phases extend them. Pinned snapshots retain their existing no-live-connection semantics and explicitly explain that My Windows requires a live Context window. Reconnect re-registers current visible capability state and recovers manuscript authority through the existing foundation mechanisms; missed commands are not replayed. Qualification and deployment evidence will be appended as each phase completes. Physical cross-device/Word/installed-PWA acceptance is not implied by browser-session automation. + +### Phase 1 qualification + +Commit `16c0505`, Development release `context-enhancement-phase1-16c0505-20261122T150659Z`. Clean build; 13 routing assertions; actual SignalR transport in isolated host and two independently authenticated Development browser contexts passed targeted delivery, exactly one recipient read, no unrelated pane mutation/Word navigation, cross-user/book/story-point rejection, no-handler, reconnect. This qualifies separate authenticated sessions, not physical devices or Word. + +### Phase 2 + +Compact scene-first Characters explorer uses canonical timeline/appearance reads, existing story-point knowledge and Map location rules. Catalogue search, independent pane filters, POV/participation/classification, Previous→Now→Next, canonical-ID location interactions and focused classification/description/emotion/condition/location corrections. Correction facade hydrates existing models and uses existing save services; checks authenticated book, character project, scene membership and Owner/Collaborator role. Unknown/read-only roles denied. Fingerprints reject stale forms within a process; existing persistence has no cross-process atomic row version, so this does not establish fully transactional concurrent editing across main editors. + +Manual creation defaults Supporting (6); import migration297 changes only the literal default for newly discovered characters from Major (8) to Minor (2). No existing row reclassification. Development backup `context-enhancement-phase2-20261122.bak` succeeded and was independently VERIFYONLY checked using administrator because application principal cannot perform VERIFYONLY. Migration applied with Development guard; pre/post existing CharacterID/classification set unchanged. + +Qualification: clean solution build; 11 focused narrative/edit/permission assertions; actual compiled Razor browser with 12 long-name characters, independent same-tool panes, full/half/stacked/mobile and 125% zoom; focused modal existing values, rejected discard, cancelled persistence, inline failed-save draft retention and one success toast. Browser save responses isolated; canonical persistence tested at service boundary, live persistence acceptance continues in integration. Previous/next scoped to the selected book; future information explicitly author reference. No unsupported presence/location inferred. Existing unknown/unrecorded participation displayed explicitly. diff --git a/PlotLine.Tests/Browser/context-characters.cjs b/PlotLine.Tests/Browser/context-characters.cjs new file mode 100644 index 00000000..168e5403 --- /dev/null +++ b/PlotLine.Tests/Browser/context-characters.cjs @@ -0,0 +1,18 @@ +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()});}); + 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='scene-first compact long catalogue';assert.equal(await page.locator('[data-context-character]').count(),12);assert.match(await page.locator('[data-context-character="5"]').innerText(),/POV/);assert.match(await page.locator('[data-context-character="6"] summary').innerText(),/Mentioned only/);assert.match(await page.locator('[data-context-character="5"]').innerText(),/Earlier hall[\s\S]*Saved room[\s\S]*Following garden/); + step='independent same-tool panes';await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.locator('[data-context-pane="1"] [data-character-filter]').fill('name 10');assert.equal(await page.locator('[data-context-pane="1"] [data-context-character]:visible').count(),1);assert.equal(await page.locator('[data-context-pane="0"] [data-context-character]:visible').count(),12); + step='container widths, stacked, mobile, zoom';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(60);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}} + await page.evaluate(()=>document.documentElement.style.zoom='1.25');assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await page.evaluate(()=>document.documentElement.style.zoom='1'); + step='correct values, cancel and draft protection';await page.selectOption('[data-context-layout]','single');await page.locator('[data-context-pane="0"] [data-context-edit="description"]').first().click();await page.waitForSelector('[data-context-edit-form]');assert.equal(await page.locator('[name=Value]').inputValue(),'Saved value');await page.locator('[name=Value]').fill('Entered draft');page.once('dialog',d=>d.dismiss());await page.click('[data-context-edit-cancel]');assert(await page.locator('[data-context-edit-dialog]').isVisible());assert.equal(posts,0); + step='failed save retains modal and draft inline';await page.click('[data-context-edit-form] [type=submit]');await page.waitForSelector('[data-context-edit-form] .validation-summary-errors');assert.equal(await page.locator('[name=Value]').inputValue(),'Entered draft');assert(await page.locator('[data-context-edit-dialog]').isVisible()); + step='successful save closes with one success toast';fail=false;await page.evaluate(()=>{window.successes=0;window.PlotDirector.toast.success=()=>successes++;});await page.click('[data-context-edit-form] [type=submit]');await page.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);assert.equal(await page.evaluate(()=>successes),1);assert.equal(posts,2); + assert.deepEqual(errors,[]);console.log('PASS Characters browser: twelve characters, independent panes, container layouts/mobile/zoom, modal values/cancel/unsaved protection/inline failure/single success (isolated HTTP save fixture; canonical persistence separately tested)'); +} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await browser.close();}})(); diff --git a/PlotLine.Tests/Browser/context-my-windows.cjs b/PlotLine.Tests/Browser/context-my-windows.cjs index ea2d01e6..cfea9d7f 100644 --- a/PlotLine.Tests/Browser/context-my-windows.cjs +++ b/PlotLine.Tests/Browser/context-my-windows.cjs @@ -11,6 +11,7 @@ const live=!!process.env.PD_CONTEXT_IDENTITY,base=live?'https://dev.plotdirector if(!live){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'))}));await context.route('**/native-companion/status',r=>r.fulfill({json:[]}));await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}}));await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false,position:null}}));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})});});} const page=await context.newPage();pages.push(page);const count={hub:0,word:0,reads:0};counts.push(count);page.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))count.hub++;if(r.url().includes('/Writing/Context/Navigate')||r.url().includes('/WriterWord/Navigate'))count.word++;if(r.url().includes('/Writing/Context/Tabs/'))count.reads++;}); if(live){await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(who.Email);await page.locator('[name=Password]').fill(who.Password);await Promise.all([page.waitForURL(u=>u.pathname!=='/Account/Login'),page.locator('button[type=submit]').click()]);} + count.hub=0;count.word=0;count.reads=0; await page.goto(`${base}/Writing/Context?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`);await page.waitForSelector('[data-context-tab-fragment]');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected'); } const [source,destination]=pages; diff --git a/PlotLine.Tests/Browser/context-workspace-foundation.cjs b/PlotLine.Tests/Browser/context-workspace-foundation.cjs index e8a05bf3..b2a15e99 100644 --- a/PlotLine.Tests/Browser/context-workspace-foundation.cjs +++ b/PlotLine.Tests/Browser/context-workspace-foundation.cjs @@ -35,7 +35,7 @@ const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sess await page.locator('[data-context-pane="1"] [data-context-tab-fragment]').waitFor(); assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Fixture participant/); assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Uncertain/); - assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Hall.*Garden/s); + assert.match(await page.locator('[data-context-pane="1"]').innerText(),/future record/); if(process.env.PD_CONTEXT_EVIDENCE){fs.mkdirSync(process.env.PD_CONTEXT_EVIDENCE,{recursive:true});await page.screenshot({path:process.env.PD_CONTEXT_EVIDENCE+'/columns-1366.png'});} step='same tab twice and shared HTTP request';requests=[]; await page.selectOption('[data-context-pane="1"] [data-context-tab]','overview'); diff --git a/PlotLine.Tests/ContextCharacterTests.cs b/PlotLine.Tests/ContextCharacterTests.cs new file mode 100644 index 00000000..7535e626 --- /dev/null +++ b/PlotLine.Tests/ContextCharacterTests.cs @@ -0,0 +1,43 @@ +using System.Text.Json; +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 ContextCharacterTests +{ + private static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Context characters: "+message);} + public static async Task Run() + { + var scene=new SceneEditViewModel{SceneID=30,ChapterID=10,POVCharacterID=5,SceneTitle="Current",SceneCharacters=[new(){SceneID=30,CharacterID=5,PresenceTypeName="Present",LocationID=2},new(){SceneID=30,CharacterID=6,PresenceTypeName="Mentioned Only",LocationID=2}]}; + var ordered=new[]{new Scene{SceneID=90,ChapterID=10,SceneTitle="Earlier different"},new Scene{SceneID=10,ChapterID=10,SceneTitle="Earlier duplicate"},new Scene{SceneID=30,ChapterID=10,SceneTitle="Current"},new Scene{SceneID=2,ChapterID=10,SceneTitle="Future"}}; + SceneCharacter[] appearances=[new(){CharacterID=5,SceneID=90,PresenceTypeName="Present",LocationID=1},new(){CharacterID=5,SceneID=10,PresenceTypeName="Present",LocationID=2},..scene.SceneCharacters,new(){CharacterID=5,SceneID=2,PresenceTypeName="Present",LocationID=3,EmotionalState="Future emotion"}]; + var model=new WritingContextDisplayViewModel{Context=new(){Position=new(7,12,10,30),Scene=scene,Narrative=new(){Chapters=[new(){ChapterID=10,BookID=12}],Scenes=ordered}}}; + var projection=ContextCharacterPanels.Compose(model,[new(){CharacterID=5,CharacterName="Person",CharacterImportance=6},new(){CharacterID=6,CharacterName="Mentioned",CharacterImportance=10}],appearances,[new(){LocationID=1,LocationName="First"},new(){LocationID=2,LocationName="Now"},new(){LocationID=3,LocationName="Next"}],true); + var row=projection.Rows.Single(r=>r.Character.CharacterID==5);Check(row.Previous?.SceneID==90,"previous skips duplicate current locations using canonical order, not numeric IDs");Check(row.Now?.LocationID==2&&row.Next?.SceneID==2,"next is the nearest recorded following location, independently labelled by the view");Check(row.Emotion==null,"future emotional state never fills a current blank");Check(projection.Rows.Single(r=>r.Character.CharacterID==6).Now==null,"mentioned-only is never represented as physically present");Check(row.IsPov&&row.Classification=="Supporting","POV and canonical character importance remain independent"); + Check(!ContextEditPolicy.CanEdit(new(){AccessRole="Viewer"})&&!ContextEditPolicy.CanEdit(null),"unknown/read-only access cannot edit"); + var character=new CharacterEditViewModel{CharacterID=5,ProjectID=7,CharacterName="Preserve name",Aliases=["Kept alias"],CharacterImportance=8,DefaultDescription="Preserve description"}; + var appearance=new SceneCharacter{SceneCharacterID=8,SceneID=22,CharacterID=5,RoleInSceneTypeID=1,PresenceTypeID=1,LocationID=2,PhysicalCondition="Preserve physical",EmotionalState="Before",KnowledgeNotes="Preserve knowledge"}; + var role="Owner";var writes=0;SceneCharacterEditViewModel? savedAppearance=null; + var service=NativeWorkflowTests.Proxy((name,args)=>name switch{ + "GetEditCharacterAsync"=>Task.FromResult(JsonSerializer.Deserialize(JsonSerializer.Serialize(character))), + "SaveCharacterAsync"=>Save((CharacterEditViewModel)args![0]!), + "UpdateSceneCharacterAsync"=>SaveAppearance((SceneCharacterEditViewModel)args![0]!),_=>throw new Exception(name)}); + Task Save(CharacterEditViewModel input){writes++;character=input;return Task.FromResult(new CharacterSaveResult(5));} + Task SaveAppearance(SceneCharacterEditViewModel input){writes++;savedAppearance=input;return Task.FromResult(8);} + var client=NativeWorkflowTests.Proxy((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy((_,_)=>client);var hub=NativeWorkflowTests.Proxy>((_,_)=>clients); + var edit=new ContextCharacterEditing(service, + NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){Position=new(7,12,10,22),Scene=new(){SceneID=22,SceneCharacters=[appearance]}})), + 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((_,_)=>7),new ContextWorkspaceNotifications(hub,NullLogger.Instance)); + var form=await edit.Read(12,22,5,"classification");Check(form.Value=="8"&&form.Options.Any(o=>o.Value=="8"),"existing deliberate classification survives form loading"); + var old=form.Fingerprint;form.Value="6";await edit.Save(form);Check(character.CharacterImportance==6&&character.CharacterName=="Preserve name"&&character.Aliases.SequenceEqual(["Kept alias"]),"focused classification save preserves unrelated canonical identity fields"); + try{form.Fingerprint=old;await edit.Save(form);throw new Exception("Stale save accepted");}catch(InvalidOperationException){Check(true,"stale drafts are rejected rather than overwriting a newer correction");} + var state=await edit.Read(12,22,5,"emotion");state.Value="After";await edit.Save(state);Check(savedAppearance?.EmotionalState=="After"&&savedAppearance.PhysicalCondition=="Preserve physical"&&savedAppearance.KnowledgeNotes=="Preserve knowledge"&&savedAppearance.LocationID==2,"focused scene-state save preserves the rest of the participation record"); + role="Viewer";var before=writes;try{await edit.Read(12,22,5,"description");throw new Exception("Viewer permitted");}catch(UnauthorizedAccessException){Check(writes==before,"read-only account cannot load an editing form or write");} + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 6653c4c2..d58f7242 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -182,10 +182,12 @@ 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-characters")){await ContextCharacterTests.Run();return;} if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;} var tests = new (string Name, Action Test)[] { + ("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), ("Shared boundary topology preserves map and project contracts",MapTopologyTests.Run), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 83f5ca6b..51f4d911 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -394,6 +394,13 @@ internal static class ToolbarBrowserHost await RenderFullAsync(context,"Writing","Context",page,new Dictionary { ["NativeSnapshot"]=pinned }); }).WithOrder(-1); app.MapGet("/Writing/Intent",context=>{context.Response.Redirect("/Writing/Context"+context.Request.QueryString);return Task.CompletedTask;}).WithOrder(-1); + app.MapGet("/context-edit-fixture",async context=>{ + var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false); + var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"}; + using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; + if(context.Request.Query["invalid"]=="true"){data.ModelState.AddModelError("Value","Synthetic validation: draft retained.");model.Value="Entered draft";} + 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-tab-fixture/{tool}",async context=> { var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22; @@ -402,6 +409,14 @@ internal static class ToolbarBrowserHost Project=new(){ProjectID=7,ProjectName="Fixture project"},Book=new(){BookID=12,BookTitle="Fixture book"},Chapter=new(){ChapterID=10,ChapterNumber=1,ChapterTitle="Opening"}, SceneCharacters=[new(){CharacterID=5,CharacterName="Fixture participant",RoleInSceneTypeName="Observer",EmotionalState="Uncertain",PhysicalCondition="Tired",LocationName="Saved room",EntryLocationName="Hall",ExitLocationName="Garden"}] }; var model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene} }; + scene.POVCharacterID=5; + var catalogue=Enumerable.Range(5,12).Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id==5?"Fixture participant":"A long established character name "+id,CharacterImportance=id==5?6:2}).ToList(); + scene.SceneCharacters=catalogue.Select(c=>new SceneCharacter{SceneCharacterID=c.CharacterID,CharacterID=c.CharacterID,SceneID=sceneId,CharacterName=c.CharacterName,PresenceTypeName=c.CharacterID==6?"Mentioned Only":"Present",RoleInSceneTypeName="Observer",EmotionalState=c.CharacterID==5?"Uncertain":null,PhysicalCondition="Tired",LocationID=77}).ToList(); + + model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene,Narrative=new(){Chapters=[new(){ChapterID=10,BookID=12},new(){ChapterID=11,BookID=12}],Scenes=[new(){SceneID=21,ChapterID=10,SceneTitle="Earlier"},new(){SceneID=22,ChapterID=10,SceneTitle="Current"},new(){SceneID=23,ChapterID=11,SceneTitle="Following"}]}} }; + 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); + 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}; diff --git a/PlotLine/Controllers/ContextToolsController.cs b/PlotLine/Controllers/ContextToolsController.cs new file mode 100644 index 00000000..58b9ae6f --- /dev/null +++ b/PlotLine/Controllers/ContextToolsController.cs @@ -0,0 +1,29 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Services.Context; +namespace PlotLine.Controllers; + +[Authorize,Route("Writing/Context"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] +public sealed class ContextToolsController(ContextCharacterEditing editing):Controller +{ + [HttpGet("EditCharacter")] + public async Task EditCharacter(int bookId,int sceneId,int characterId,string field) + {try{return PartialView("~/Views/Writing/_ContextCharacterEdit.cshtml",await editing.Read(bookId,sceneId,characterId,field));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException){return BadRequest();}} + [HttpPost("EditCharacter"),ValidateAntiForgeryToken] + public async Task SaveCharacter(ContextCharacterEditForm model) + { + try{ + if(ModelState.IsValid){await editing.Save(model);return Ok(new{saved=true,bookId=model.BookID});} + return await Invalid(model,"Check the correction below."); + }catch(UnauthorizedAccessException){return Forbid();} + 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.");} + } + private async Task Invalid(ContextCharacterEditForm input,string error) + { + ContextCharacterEditForm frame; + try{frame=await editing.Read(input.BookID,input.SceneID,input.CharacterID,input.Field);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException){return BadRequest();} + frame.Value=input.Value;frame.Fingerprint=input.Fingerprint;ModelState.AddModelError(nameof(input.Value),error);Response.StatusCode=422; + return PartialView("~/Views/Writing/_ContextCharacterEdit.cshtml",frame); + } +} diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index 5f47541e..a574feea 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -18,7 +18,7 @@ public sealed class WritingController( IStoryContextService storyContext, IRelationshipMapService relationshipMap, IFloorPlanService floorPlans, - ILogger logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null) : Controller + ILogger logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null) : Controller { [HttpGet("Context")] public async Task Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) @@ -115,10 +115,21 @@ 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); ViewData["ContextTabPartial"] = partial; return PartialView("_ContextTab", model); } + [HttpGet("Context/CharacterReference")] + public async Task CharacterReference(int bookId,int sceneId,int characterId) + { + if(!ModelState.IsValid||characterPanels==null)return BadRequest(); + var display=await BuildDisplayAsync(null,bookId,null,sceneId,"Saved reference"); + if(display?.HasScene!=true||projectAccess==null||!await projectAccess.CanAccessProjectAsync(display.Context!.Position.ProjectId))return NotFound(); + var explorer=await characterPanels.Build(display);var row=explorer.Rows.SingleOrDefault(r=>r.Character.CharacterID==characterId); + return row==null?NotFound():PartialView("_ContextCharacterReference",(explorer,row)); + } + [HttpGet("Context/Position")] public async Task ContextPosition([FromServices] IWordCompanionPresenceService office, int? bookId, int? projectId) { diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 06a619a5..4b10f578 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -291,6 +291,8 @@ public class Program builder.Services.Configure>(options => options.MaximumReceiveMessageSize = 16384); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); diff --git a/PlotLine/Services/Context/ContextCharacterEditing.cs b/PlotLine/Services/Context/ContextCharacterEditing.cs new file mode 100644 index 00000000..4f0c3c80 --- /dev/null +++ b/PlotLine/Services/Context/ContextCharacterEditing.cs @@ -0,0 +1,76 @@ +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.ViewModels; +namespace PlotLine.Services.Context; + +public sealed class ContextCharacterEditForm +{ + public int BookID{get;set;}public int SceneID{get;set;}public int CharacterID{get;set;} + public string Field{get;set;}="";public string Fingerprint{get;set;}=""; + [StringLength(4000)]public string? Value{get;set;} + public string Label{get;set;}="";public string CharacterName{get;set;}=""; + public IReadOnlyList Options{get;set;}=[]; +} +public sealed class ContextCharacterEditing(ICharacterService characters,IStoryContextService stories, + 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(ContextCharacterEditForm Form,CharacterEditViewModel Character,SceneEditViewModel? Scene,PlotLine.Models.SceneCharacter? Appearance); + private static string Hash(object value)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value)))); + public async Task Read(int bookId,int sceneId,int characterId,string field)=>(await Load(bookId,sceneId,characterId,field)).Form; + private async Task Load(int bookId,int sceneId,int characterId,string field) + { + var author=user.UserId??throw new UnauthorizedAccessException(); + var structure=await access.GetBookStructureAsync(bookId,author)??throw new UnauthorizedAccessException(); + var book=await books.GetAsync(bookId)??throw new UnauthorizedAccessException(); + var project=await projects.GetForUserAsync(book.ProjectID,author); + if(!ContextEditPolicy.CanEdit(project))throw new UnauthorizedAccessException(); + var character=await characters.GetEditCharacterAsync(characterId)??throw new UnauthorizedAccessException(); + if(character.ProjectID!=book.ProjectID)throw new UnauthorizedAccessException(); + SceneEditViewModel? scene=null;PlotLine.Models.SceneCharacter? appearance=null; + var labels=new Dictionary{{"classification","Character classification"},{"description","Character description"},{"emotion","Emotional state in this scene"},{"condition","Physical condition in this scene"},{"location","Recorded location in this scene"}}; + if(!labels.ContainsKey(field))throw new ArgumentException("Unsupported correction."); + if(sceneId>0&&!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))throw new UnauthorizedAccessException(); + if(field is "emotion" or "condition" or "location"){ + scene=(await stories.GetForSceneAsync(sceneId,book.ProjectID,bookId,forWriting:true,includeNarrative:false))?.Scene??throw new UnauthorizedAccessException(); + appearance=scene.SceneCharacters.SingleOrDefault(a=>a.CharacterID==characterId)??throw new UnauthorizedAccessException(); + } + var value=field switch{"classification"=>character.CharacterImportance?.ToString(),"description"=>character.DefaultDescription,"emotion"=>appearance?.EmotionalState,"condition"=>appearance?.PhysicalCondition,"location"=>appearance?.LocationID?.ToString(),_=>null}; + IReadOnlyList options=[]; + if(field=="classification"){ + var choices=new List{new("Unclassified",""),new("Major · author choice","10"),new("Supporting","6"),new("Minor","2")}; + if(value!=null&&choices.All(c=>c.Value!=value))choices.Add(new("Current recorded classification ("+value+")",value));options=choices; + } + if(field=="location")options=[new("No recorded location",""),..scene!.LocationOptions]; + var hash=appearance!=null?Hash(new{appearance.SceneCharacterID,appearance.SceneID,appearance.CharacterID,appearance.RoleInSceneTypeID,appearance.PresenceTypeID,appearance.LocationID,appearance.EntryLocationID,appearance.ExitLocationID,appearance.AppearanceNotes,appearance.OutfitDescription,appearance.EmotionalState,appearance.PhysicalCondition,appearance.KnowledgeNotes}):Hash(new{character.CharacterID,character.CharacterName,character.Aliases,character.CharacterImportance,character.DefaultDescription,character.SexValueID,character.Sex,character.BirthDate,character.AgeAtSeriesStart,character.Height,character.EyeColour,character.ShowInQuickAddBar,character.ImagePath,character.ThumbnailPath}); + return new(new(){BookID=bookId,SceneID=sceneId,CharacterID=characterId,Field=field,Value=value,Label=labels[field],CharacterName=character.CharacterName,Fingerprint=hash,Options=options},character,scene,appearance); + } + public async Task Save(ContextCharacterEditForm input) + { + var mutex=Locks[(input.CharacterID&int.MaxValue)%Locks.Length];await mutex.WaitAsync(); + try{ + var frame=await Load(input.BookID,input.SceneID,input.CharacterID,input.Field); + if(frame.Form.Fingerprint!=input.Fingerprint)throw new InvalidOperationException("This record changed in another window. Your draft is retained; cancel and reopen to load current values."); + if(input.Value?.Length>4000)throw new ArgumentException("Use 4,000 characters or fewer."); + if(input.Field=="classification"){ + int? importance=null;if(!string.IsNullOrWhiteSpace(input.Value)){if(!int.TryParse(input.Value,out var parsed)||(!new[]{2,6,10}.Contains(parsed)&&parsed!=frame.Character.CharacterImportance))throw new ArgumentException("Choose a recorded classification.");importance=parsed;} + frame.Character.CharacterImportance=importance;await characters.SaveCharacterAsync(frame.Character); + }else if(input.Field=="description"){frame.Character.DefaultDescription=input.Value;await characters.SaveCharacterAsync(frame.Character);} + else{ + var a=frame.Appearance!;var edit=new SceneCharacterEditViewModel{SceneCharacterID=a.SceneCharacterID,SceneID=a.SceneID,CharacterID=a.CharacterID,RoleInSceneTypeID=a.RoleInSceneTypeID,PresenceTypeID=a.PresenceTypeID,LocationID=a.LocationID,EntryLocationID=a.EntryLocationID,ExitLocationID=a.ExitLocationID,AppearanceNotes=a.AppearanceNotes,OutfitDescription=a.OutfitDescription,PhysicalCondition=a.PhysicalCondition,EmotionalState=a.EmotionalState,KnowledgeNotes=a.KnowledgeNotes}; + if(input.Field=="emotion")edit.EmotionalState=input.Value; + if(input.Field=="condition")edit.PhysicalCondition=input.Value; + if(input.Field=="location"){ + if(!string.IsNullOrWhiteSpace(input.Value)&&!frame.Form.Options.Any(o=>o.Value==input.Value))throw new ArgumentException("Choose a location from this project."); + edit.LocationID=string.IsNullOrWhiteSpace(input.Value)?null:int.Parse(input.Value); + } + await characters.UpdateSceneCharacterAsync(edit); + } + await notifications.Invalidate(user.UserId!.Value,input.BookID); + }finally{mutex.Release();} + } +} diff --git a/PlotLine/Services/Context/ContextCharacterPanels.cs b/PlotLine/Services/Context/ContextCharacterPanels.cs new file mode 100644 index 00000000..1b906d09 --- /dev/null +++ b/PlotLine/Services/Context/ContextCharacterPanels.cs @@ -0,0 +1,59 @@ +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.ViewModels; +namespace PlotLine.Services.Context; + +public sealed record ContextPlace(int LocationID,string Name,int SceneID,int ChapterID,string SceneTitle); +public sealed record ContextCharacterRow(Character Character,SceneCharacter? Appearance,bool IsPov,ContextPlace? Previous,ContextPlace? Now,ContextPlace? Next, + string? Emotion,string? Condition,IReadOnlyList Knowledge) +{ + public bool InScene=>Appearance!=null||IsPov; + public string Classification=>Character.CharacterImportance is >=8?"Major":Character.CharacterImportance is >=4?"Supporting":Character.CharacterImportance.HasValue?"Minor":"Unclassified"; + public string Participation=>Appearance?.RoleInSceneTypeName=="Mentioned Only"||Appearance?.PresenceTypeName=="Mentioned Only"?"Mentioned only":Appearance?.PresenceTypeName??"Participation not recorded"; +} +public sealed class ContextCharacterExplorer +{ + public int ProjectID{get;init;}public int BookID{get;init;}public int ChapterID{get;init;}public int SceneID{get;init;}public string SceneTitle{get;init;}=""; + public bool CanEdit{get;init;}public IReadOnlyList Rows{get;init;}=[]; +} +public static class ContextEditPolicy +{ + public static bool CanEdit(Project? project)=>project!=null&&(string.Equals(project.AccessRole,"Owner",StringComparison.OrdinalIgnoreCase)||string.Equals(project.AccessRole,"Collaborator",StringComparison.OrdinalIgnoreCase)); +} +// Presentation projection over existing canonical timeline, appearance and Story Point reads. +public sealed class ContextCharacterPanels(ICharacterRepository characters,ILocationRepository locations,IProjectRepository projects,ICurrentUserService user) +{ + public async Task Build(WritingContextDisplayViewModel display) + { + var position=display.Context!.Position; + var data=await characters.GetTimelineAsync(position.ProjectId,null); + var places=await locations.ListByProjectAsync(position.ProjectId); + var project=user.UserId.HasValue?await projects.GetForUserAsync(position.ProjectId,user.UserId.Value):null; + return Compose(display,data.Characters,data.Appearances,places,ContextEditPolicy.CanEdit(project)); + } + public static ContextCharacterExplorer Compose(WritingContextDisplayViewModel display,IReadOnlyList characters,IReadOnlyList appearances,IReadOnlyList locations,bool canEdit) + { + var scene=display.Context!.Scene!;var position=display.Context.Position; + var ordered=(display.Context.Narrative?.Scenes??[new Scene{SceneID=scene.SceneID,ChapterID=scene.ChapterID,PrimaryLocationID=scene.PrimaryLocationID}]).ToList(); + var chapterIds=display.Context.Narrative?.Chapters.Where(c=>c.BookID==position.BookId).Select(c=>c.ChapterID).ToHashSet()??[scene.ChapterID]; + ordered=ordered.Where(s=>chapterIds.Contains(s.ChapterID)).ToList(); + var indexes=ordered.Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i);var at=indexes.GetValueOrDefault(scene.SceneID,-1); + var byScene=ordered.ToDictionary(s=>s.SceneID);var placeNames=locations.ToDictionary(l=>l.LocationID,l=>string.IsNullOrWhiteSpace(l.LocationPath)?l.LocationName:l.LocationPath); + var byPerson=appearances.Where(a=>indexes.ContainsKey(a.SceneID)).GroupBy(a=>a.CharacterID).ToDictionary(g=>g.Key,g=>g.OrderBy(a=>indexes[a.SceneID]).ThenBy(a=>a.UpdatedDate).ToList()); + ContextPlace? Place(SceneCharacter? appearance){if(appearance==null||appearance.RoleInSceneTypeName=="Mentioned Only"||appearance.PresenceTypeName=="Mentioned Only")return null; + var s=byScene[appearance.SceneID];var id=MapStoryComposer.RecordedAppearanceLocation(appearance,s.PrimaryLocationID); + return id.HasValue&&placeNames.TryGetValue(id.Value,out var name)?new(id.Value,name,s.SceneID,s.ChapterID,s.SceneTitle):null;} + var rows=new List(); + foreach(var person in characters.Where(c=>!c.IsArchived)){ + var all=byPerson.GetValueOrDefault(person.CharacterID,[]);var current=all.LastOrDefault(a=>a.SceneID==scene.SceneID)??scene.SceneCharacters.FirstOrDefault(a=>a.CharacterID==person.CharacterID); + var now=Place(current);var preceding=all.Where(a=>indexes[a.SceneID]p!=null&&(now==null||p.LocationID!=now.LocationID)); + var next=all.Where(a=>indexes[a.SceneID]>at).Select(Place).FirstOrDefault(p=>p!=null); + // Current scene state only: do not fill blanks from future or unrelated appearances. + var knowledge=display.AtPoint?.Characters.FirstOrDefault(c=>c.Appearance.CharacterID==person.CharacterID)?.Knowledge??[]; + rows.Add(new(person,current,scene.POVCharacterID==person.CharacterID,previous,now,next,current?.EmotionalState,current?.PhysicalCondition,knowledge)); + } + return new(){ProjectID=position.ProjectId,BookID=position.BookId!.Value,ChapterID=position.ChapterId!.Value,SceneID=scene.SceneID,SceneTitle=scene.SceneTitle,CanEdit=canEdit, + Rows=rows.OrderByDescending(r=>r.IsPov).ThenByDescending(r=>r.InScene).ThenBy(r=>r.Participation=="Mentioned only").ThenBy(r=>r.Character.CharacterName).ToList()}; + } +} diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 91727225..77c0e644 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -9634,7 +9634,7 @@ public sealed class CharacterService( var project = await projects.GetAsync(projectId); return project is null ? null - : await PopulateCharacterEditOptionsAsync(new CharacterEditViewModel { ProjectID = projectId, Project = project }); + : await PopulateCharacterEditOptionsAsync(new CharacterEditViewModel { ProjectID = projectId, Project = project, CharacterImportance = 6 }); } public async Task GetEditCharacterAsync(int characterId) diff --git a/PlotLine/Services/MapStoryService.cs b/PlotLine/Services/MapStoryService.cs index 8420102b..440a877b 100644 --- a/PlotLine/Services/MapStoryService.cs +++ b/PlotLine/Services/MapStoryService.cs @@ -99,9 +99,10 @@ public static class MapStoryComposer public static bool PhysicalAppearance(SceneCharacter appearance) => appearance.RoleInSceneTypeName != "Mentioned Only" && appearance.PresenceTypeName is not ("Mentioned Only" or "Off-screen"); - private static int? AppearanceLocation(SceneCharacter a, MapStoryScene s) => + public static int? RecordedAppearanceLocation(SceneCharacter a,int? primaryLocationId) => a.PresenceTypeName == "Unknown" ? null : a.ExitLocationID ?? a.LocationID ?? - (a.PresenceTypeName is "Present" or "Arrives" or "Leaves" or "Nearby" or "Hidden" or "Overhearing" ? s.PrimaryLocationID : null); + (a.PresenceTypeName is "Present" or "Arrives" or "Leaves" or "Nearby" or "Hidden" or "Overhearing" ? primaryLocationId : null); + private static int? AppearanceLocation(SceneCharacter a,MapStoryScene s)=>RecordedAppearanceLocation(a,s.PrimaryLocationID); public static MapStoryProjection Compose(MapStoryData data, PlotLineWorkspaceData plots, int mapId) { diff --git a/PlotLine/Sql/297_ContextCharacterImportDefault.sql b/PlotLine/Sql/297_ContextCharacterImportDefault.sql new file mode 100644 index 00000000..3173bf30 --- /dev/null +++ b/PlotLine/Sql/297_ContextCharacterImportDefault.sql @@ -0,0 +1,18 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- Forward-only correction of the structural import default. Existing rows/author decisions are untouched. +DECLARE @body nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Onboarding_ManuscriptBuild_Create')); +IF @body IS NULL THROW 51000,'Core import procedure is unavailable; no default was changed.',1; +DECLARE @old nvarchar(200)=N'VALUES (@ProjectID, @Title, NULL, 8, 1, NULL);'; +DECLARE @new nvarchar(200)=N'VALUES (@ProjectID, @Title, NULL, 2, 1, NULL);'; +IF CHARINDEX(@old,@body)>0 +BEGIN + IF CHARINDEX(@old,@body,CHARINDEX(@old,@body)+1)>0 THROW 51000,'Ambiguous import default; inspect the procedure before applying.',1; + SET @body=REPLACE(@body,@old,@new); + SET @body=N'ALTER '+SUBSTRING(@body,CHARINDEX(N'PROCEDURE',UPPER(@body)),LEN(@body)); + EXEC sys.sp_executesql @body; +END +ELSE IF CHARINDEX(@new,@body)=0 THROW 51000,'Unrecognised import default; existing procedure was preserved.',1; +GO diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 75e0baed..0d0552f8 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -478,6 +478,7 @@ public sealed class WritingContextPageViewModel public sealed class WritingContextDisplayViewModel { + public PlotLine.Services.Context.ContextCharacterExplorer? CharacterExplorer {get;set;} public StoryPointSnapshot? AtPoint => Context?.Narrative?.Snapshot; public IReadOnlyList RelevantThreads => Context==null?[]:WritingContextRelevance.Threads(Context); public IReadOnlyList NearbyScenes {get;set;}=[]; diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index dc538f54..b59958c3 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -6,7 +6,7 @@ var position = Model.Display?.Context?.Position; 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 = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "character.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" } } }; } @@ -40,6 +40,7 @@ } +

Focused correction

My Context windows

Only your connected windows for this book appear. Commands focus a reference tool; they do not navigate Word.

@@ -54,4 +55,5 @@ + } diff --git a/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml b/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml new file mode 100644 index 00000000..55b3d432 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml @@ -0,0 +1,18 @@ +@using PlotLine.Services.Context +@model ValueTuple +@{var explorer=Model.Item1;var row=Model.Item2;} +
+
+ @foreach(var item in new[]{("Previous",row.Previous),("Now",row.Now),("Next · future record",row.Next)}){ +
@item.Item1@if(item.Item2 is {} place){Source scene} + else{@(item.Item1=="Now"?(row.Participation=="Mentioned only"?"Mentioned only · no physical presence implied":"No recorded location here"):"No recorded location")}
+ } +
+
Emotional state
@(string.IsNullOrWhiteSpace(row.Emotion)?"Not recorded in this scene":row.Emotion)
Physical condition
@(string.IsNullOrWhiteSpace(row.Condition)?"Not recorded in this scene":row.Condition)
Reference
@(string.IsNullOrWhiteSpace(row.Character.DefaultDescription)?"No character description recorded":row.Character.DefaultDescription)
+ @if(row.Knowledge.Any()){

@(row.IsPov?"Verified viewpoint knowledge at this point":"Author reference: this character’s established knowledge; not necessarily viewpoint knowledge")

    @foreach(var fact in row.Knowledge.Take(4)){
  • @fact.KnowledgeStateName: @fact.Description Source
  • }
} + @if(explorer.CanEdit){
+ @foreach(var field in new[]{("classification","Classification"),("description","Description")}){} + @if(row.Appearance!=null){@foreach(var field in new[]{("emotion","Emotional state"),("condition","Physical condition"),("location","Current location")}){}} +
}else{

Read-only reference.

} + Open character workspace +
diff --git a/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml b/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml new file mode 100644 index 00000000..03e84a2b --- /dev/null +++ b/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml @@ -0,0 +1,13 @@ +@model PlotLine.Services.Context.ContextCharacterEditForm +
+ @Html.AntiForgeryToken() + +

@Model.CharacterName · @Model.Label

+ + +

Only this correction is saved. Other character and scene fields are retained.

+ +
diff --git a/PlotLine/Views/Writing/_ContextCharacterReference.cshtml b/PlotLine/Views/Writing/_ContextCharacterReference.cshtml new file mode 100644 index 00000000..29dd3de0 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextCharacterReference.cshtml @@ -0,0 +1,6 @@ +@using PlotLine.Services.Context +@model ValueTuple +
+

@Model.Item2.Character.CharacterName

Saved reference at @Model.Item1.SceneTitle. The active manuscript scene is unchanged.

+ +
diff --git a/PlotLine/Views/Writing/_WritingContextPeople.cshtml b/PlotLine/Views/Writing/_WritingContextPeople.cshtml index ba603e39..c45c446f 100644 --- a/PlotLine/Views/Writing/_WritingContextPeople.cshtml +++ b/PlotLine/Views/Writing/_WritingContextPeople.cshtml @@ -1,56 +1,25 @@ @model WritingContextDisplayViewModel +@using PlotLine.Services.Context @{ - var scene = Model.Context!.Scene!; - var povCharacterId = scene.POVCharacterID; - static string TextOr(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value.Trim(); + var explorer=Model.CharacterExplorer??ContextCharacterPanels.Compose(Model, + Model.Context!.Scene!.SceneCharacters.Select(a=>new Character{CharacterID=a.CharacterID,ProjectID=a.ProjectID,CharacterName=a.CharacterName,ImagePath=a.CharacterImagePath,ThumbnailPath=a.CharacterThumbnailPath}).ToList(),Model.Context.Scene.SceneCharacters,[],false); } - -@if (!scene.SceneCharacters.Any()) -{ -
-

No characters recorded for this scene

-

When scene participants are added, their current state will appear here.

-
-} -else -{ -
- @foreach (var character in scene.SceneCharacters.OrderByDescending(x => x.CharacterID == povCharacterId).ThenBy(x => x.CharacterName)) - { - var known = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID); - var knowledge = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID)?.Knowledge.ToList() ?? []; - var attributes = scene.CharacterAttributeEvents.Where(x => x.CharacterID == character.CharacterID).ToList(); -
-
- -
-

@character.CharacterName

-

@(character.CharacterID == povCharacterId ? "POV" : character.RoleInSceneTypeName ?? character.PresenceTypeName ?? "In scene")

-
-
-
-
Location
@TextOr(character.LocationPath ?? character.LocationName, "Unknown")
-
Last recorded location
@(known?.State?.CurrentLocation ?? "Not recorded")
-
Emotional state
@TextOr(character.EmotionalState, "Not recorded")
-
Physical condition
@TextOr(character.PhysicalCondition, "Not recorded")
-
Outfit
@TextOr(character.OutfitDescription ?? character.AppearanceNotes, "Not recorded")
-
Movement
@TextOr(string.Join(" -> ", new[] { character.EntryLocationName, character.ExitLocationName }.Where(x => !string.IsNullOrWhiteSpace(x))), "No entry or exit recorded")
-
-

@(character.CharacterID==povCharacterId?"Verified viewpoint knowledge at this narrative point":"Author reference: this character’s knowledge, not necessarily the viewpoint character’s")

- @if (knowledge.Any() || attributes.Any()) - { -
- @foreach (var item in knowledge.Take(3)) - { -

@item.KnowledgeStateName: @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.") Source scene

- } - @foreach (var item in attributes.Take(3)) - { -

@item.AttributeName: @item.AttributeValue

- } -
- } -
- } +
+
+ +
-} + @if(!explorer.Rows.Any(r=>r.InScene)){

No characters recorded for this scene. The catalogue remains available.

} +

Previous and next locations are recorded appearances in this book’s narrative order. Next is a future author reference, not an intention or viewpoint knowledge.

+
+ @foreach(var row in explorer.Rows){ + + } +
+ +

+ Open full Characters workspace +
diff --git a/PlotLine/wwwroot/css/context-workspace.css b/PlotLine/wwwroot/css/context-workspace.css index 638ecea3..ca8338d9 100644 --- a/PlotLine/wwwroot/css/context-workspace.css +++ b/PlotLine/wwwroot/css/context-workspace.css @@ -35,3 +35,16 @@ body:has([data-context-workspace])>.writing-window-bar { flex:none; } .context-windows-dialog { width:min(38rem,calc(100vw - 2rem));max-height:85dvh;overflow:auto;background:var(--plotline-panel);color:var(--plotline-ink);border:1px solid var(--plotline-line);border-radius:.7rem;padding:1rem; } .context-windows-dialog::backdrop { background:#0006; } .context-reference-focus { outline:3px solid var(--plotline-accent);outline-offset:-3px; } +.context-explorer-controls,.context-edit-actions { display:flex;flex-wrap:wrap;gap:.5rem;align-items:end;margin-block:.5rem; } +.context-explorer-controls label { flex:1 1 10rem;min-width:0; } +.context-character-row { border-block-end:1px solid var(--plotline-line);padding:.5rem 0; } +.context-character-row[hidden]{display:none;} +.context-character-row>summary { display:flex;flex-wrap:wrap;align-items:center;gap:.5rem;cursor:pointer;list-style:revert; } +.context-character-row>summary strong{flex:1;min-width:6rem;overflow-wrap:anywhere;} +.context-character-row>summary span{font-size:.85rem;}.context-character-row>summary small{color:var(--plotline-muted);} +.context-character-detail{padding:.65rem .25rem;} +.context-location-rail{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.5rem;margin-block:.5rem;} +.context-location-rail>div{display:flex;flex-direction:column;min-width:0;border:1px solid var(--plotline-line);padding:.5rem;border-radius:.4rem;} +.context-location-rail button{white-space:normal;text-align:start;overflow-wrap:anywhere;padding:.2rem 0;} +.context-location-rail strong{font-size:.8rem;} +@container(max-width:420px){.context-location-rail{grid-template-columns:minmax(0,1fr);}.context-location-rail>div{display:grid;grid-template-columns:5rem minmax(0,1fr);}.context-location-rail>div>a{grid-column:2;}} diff --git a/PlotLine/wwwroot/js/context-editing.js b/PlotLine/wwwroot/js/context-editing.js new file mode 100644 index 00000000..e5566048 --- /dev/null +++ b/PlotLine/wwwroot/js/context-editing.js @@ -0,0 +1,25 @@ +(() => { + 'use strict';const root=document.querySelector('[data-context-workspace]');if(!root)return; + const dialog=root.querySelector('[data-context-edit-dialog]'),host=dialog.querySelector('[data-context-edit-content]'),status=dialog.querySelector('[data-context-edit-status]');let pane,dirty=false,busy=false,originalFocus,load; + 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); + 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);}} + finally{busy=false;state();} + }); + dialog.addEventListener('input',()=>{dirty=true;state();});dialog.addEventListener('change',()=>{dirty=true;state();}); + dialog.addEventListener('submit',async event=>{const form=event.target.closest('[data-context-edit-form]');if(!form)return;event.preventDefault();if(busy)return;busy=true;state();status.textContent='Saving correction…';form.querySelectorAll('button').forEach(button=>button.disabled=true); + try{const response=await fetch(form.action,{method:'POST',body:new URLSearchParams(new FormData(form)),headers:{'X-Requested-With':'XMLHttpRequest'},credentials:'same-origin'}); + if(response.ok&&!response.redirected&&response.headers.get('content-type')?.includes('application/json')){const result=await response.json();if(!result.saved)throw Error('The save was not confirmed.');busy=false;close(true);root.contextController.invalidate({bookId:result.bookId});window.PlotDirector?.toast?.success('Correction saved.');return;} + if(response.status===422&&!response.redirected){install(await response.text());dirty=true;status.textContent='Correct the inline error and retry. Your entered value is retained.';window.PlotDirector?.toast?.error('Correction could not be saved.');} + else throw Error('Correction could not be saved. Check sign-in and editing permission; your draft is retained.'); + }catch(error){status.textContent=error.message;dirty=true;window.PlotDirector?.toast?.error(error.message);} + finally{busy=false;host.querySelectorAll('button').forEach(button=>button.disabled=false);if(dialog.open)state();} + }); + dialog.addEventListener('click',event=>{if(event.target.closest('[data-context-edit-cancel],[data-context-edit-close]'))close();});dialog.addEventListener('cancel',event=>{event.preventDefault();close();}); + window.addEventListener('beforeunload',event=>{if(dirty||busy){event.preventDefault();event.returnValue='';}}); +})(); diff --git a/PlotLine/wwwroot/js/context-tools.js b/PlotLine/wwwroot/js/context-tools.js index 9003ba89..b7a547c3 100644 --- a/PlotLine/wwwroot/js/context-tools.js +++ b/PlotLine/wwwroot/js/context-tools.js @@ -7,3 +7,29 @@ return 'not-visible'; }}}; })(); +(() => { + 'use strict';const saved=new Map(),mounted=new WeakMap(); + function focus(node){node.classList.add('context-reference-focus');node.scrollIntoView({block:'nearest'});node.focus({preventScroll:true});} + function apply(node){const filter=node.querySelector('[data-character-filter]')?.value.toLocaleLowerCase()||'',scope=node.querySelector('[data-character-scope]')?.value; + let count=0;node.querySelectorAll('[data-context-character]').forEach(row=>{row.hidden=(scope==='scene'&&row.dataset.inScene!=='true')||!row.dataset.filterName.toLocaleLowerCase().includes(filter);if(!row.hidden)count++;}); + const empty=node.querySelector('[data-character-empty]');if(empty)empty.hidden=scope!=='scene'||filter.length>0;node.querySelector('[data-character-no-matches]').hidden=count>0; + } + window.PlotDirectorContextLifecycles.characters={ + mount(node,environment){const prior=saved.get(environment.paneId),explorer=node.querySelector('[data-character-explorer]');if(!explorer)return; + const state={paneId:environment.paneId,abort:new AbortController()};mounted.set(node,state); + if(prior){explorer.querySelector('[data-character-filter]').value=prior.filter;explorer.querySelector('[data-character-scope]').value=prior.scope;node.querySelectorAll('[data-context-character]').forEach(row=>row.open=prior.open.includes(row.dataset.contextCharacter));} + else{const first=node.querySelector('[data-context-character][data-in-scene=true]');if(first)first.open=true;} + const update=()=>apply(node);node.addEventListener('input',update,{signal:state.abort.signal});node.addEventListener('change',update,{signal:state.abort.signal}); + node.addEventListener('click',event=>{const button=event.target.closest('[data-context-location]');if(!button)return;button.dispatchEvent(new CustomEvent('context-command',{bubbles:true,detail:{action:'location.focusAtStoryPoint',locationID:Number(button.dataset.contextLocation),storyPoint:{chapterID:Number(button.dataset.locationChapter),sceneID:Number(button.dataset.locationScene)}}}));},{signal:state.abort.signal});apply(node); + }, + dispose(node){const state=mounted.get(node);if(!state)return;saved.set(state.paneId,{filter:node.querySelector('[data-character-filter]')?.value||'',scope:node.querySelector('[data-character-scope]')?.value||'scene',open:[...node.querySelectorAll('[data-context-character][open]')].map(row=>row.dataset.contextCharacter)});state.abort.abort();mounted.delete(node);}, + async onInteraction(node,command,environment){if(command.action!=='character.focus')return 'not-visible';const state=mounted.get(node);if(!state)return 'unavailable'; + const scene=Number(command.storyPoint?.sceneID||node.dataset.sceneId),row=node.querySelector(`[data-context-character="${Number(command.characterID)}"]`); + if(scene===Number(node.dataset.sceneId)&&row){node.querySelector('[data-character-filter]').value='';node.querySelector('[data-character-scope]').value=row.dataset.inScene==='true'?'scene':'catalogue';apply(node);row.open=true;focus(row);return 'focused';} + const url=new URL('/Writing/Context/CharacterReference',location.origin);url.searchParams.set('bookId',node.dataset.bookId);url.searchParams.set('sceneId',scene);url.searchParams.set('characterId',command.characterID); + environment.pane.element.dispatchEvent(new CustomEvent('context-panel-state',{detail:{busy:true}})); + try{const response=await fetch(url,{signal:state.abort.signal,cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)return 'unavailable';const parsed=new DOMParser().parseFromString(await response.text(),'text/html'),reference=parsed.querySelector('[data-character-reference]');if(!reference||!node.isConnected||state.abort.signal.aborted)return 'unavailable';node.querySelector('[data-character-inspection]').replaceChildren(reference);focus(reference);return 'focused';} + finally{if(node.isConnected)environment.pane.element.dispatchEvent(new CustomEvent('context-panel-state',{detail:{busy:false}}));} + } + }; +})(); diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js index 5bb21c9c..f9bb67c9 100644 --- a/PlotLine/wwwroot/js/context-workspace.js +++ b/PlotLine/wwwroot/js/context-workspace.js @@ -18,6 +18,8 @@ let position = { ...scope, chapterId:number(root.dataset.chapterId), sceneId:number(root.dataset.sceneId), paragraphId:null }; let nativeLeases = [], generation = 0, stopped = false, connection, connectionStarting = false, recoveryGeneration = 0; let navigationRequest, manualGeneration = 0, recoveryPending = false, recoveryAgain = false; + let windowBusy=false; + root.addEventListener("context-window-state",event=>{windowBusy=!!event.detail?.busy;announce();}); const requests = new Map(); const lifecycles = { reference: { mount() {}, dispose() {} }, ...(window.PlotDirectorContextLifecycles || {}) }; const read = (name,key) => { try { return window[name].getItem(key); } catch { return null; } }; @@ -208,7 +210,7 @@ }); pane.host.addEventListener('scroll',()=>{remember(pane);save();},{passive:true}); pane.element.addEventListener('context-panel-state',event=>{ - const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale)void refreshPane(pane);announce(); + const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale&&!event.detail?.deferRefresh)void refreshPane(pane);announce(); }); } async function navigate(sceneId,sendWord=false) { @@ -267,7 +269,7 @@ if(message.kind==='occupied'&&message.target===pageToken){windowId=uuid();panes.forEach(pane=>{dispose(current(pane));pane.revision++;pane.records.clear();pane.host.replaceChildren();});state=defaults();selectedDocument=root.dataset.wordInstance&&root.dataset.wordSession?`${root.dataset.wordInstance}/${root.dataset.wordSession}`:'';save();const url=new URL(location.href);url.searchParams.set('contextWindow',windowId);history.replaceState(null,'',url);applyLayout();} };channel.postMessage({kind:'claim',id:windowId,token:pageToken});} const observer=new ResizeObserver(()=>applyLayout());observer.observe(grid); - root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks }; + root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks }; window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();}); save();applyLayout(); if(pinned)status.textContent='Saved PlotDirector snapshot · manual selection · live follow disabled';