Build compact scene-aware Context character explorer and focused corrections

This commit is contained in:
Nick Beckley 2026-11-22 15:25:06 +00:00
parent 16c05055fa
commit 6e6c7fdcd9
25 changed files with 422 additions and 60 deletions

View File

@ -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.

View File

@ -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();}})();

View File

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

View File

@ -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');

View File

@ -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<ICharacterService>((name,args)=>name switch{
"GetEditCharacterAsync"=>Task.FromResult<CharacterEditViewModel?>(JsonSerializer.Deserialize<CharacterEditViewModel>(JsonSerializer.Serialize(character))),
"SaveCharacterAsync"=>Save((CharacterEditViewModel)args![0]!),
"UpdateSceneCharacterAsync"=>SaveAppearance((SceneCharacterEditViewModel)args![0]!),_=>throw new Exception(name)});
Task<CharacterSaveResult> Save(CharacterEditViewModel input){writes++;character=input;return Task.FromResult(new CharacterSaveResult(5));}
Task<int> SaveAppearance(SceneCharacterEditViewModel input){writes++;savedAppearance=input;return Task.FromResult(8);}
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var edit=new ContextCharacterEditing(service,
NativeWorkflowTests.Proxy<IStoryContextService>((_,_)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=new(){SceneID=22,SceneCharacters=[appearance]}})),
NativeWorkflowTests.Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})),
NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),
NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>7),new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.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");}
}
}

View File

@ -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),

View File

@ -394,6 +394,13 @@ internal static class ToolbarBrowserHost
await RenderFullAsync(context,"Writing","Context",page,new Dictionary<string,object?> { ["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<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false);
var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"};
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<ITempDataProvider>()),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<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextTab.cshtml",false);
using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};

View File

@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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);
}
}

View File

@ -18,7 +18,7 @@ public sealed class WritingController(
IStoryContextService storyContext,
IRelationshipMapService relationshipMap,
IFloorPlanService floorPlans,
ILogger<WritingController> logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null) : Controller
ILogger<WritingController> 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<IActionResult> 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<IActionResult> 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<IActionResult> ContextPosition([FromServices] IWordCompanionPresenceService office, int? bookId, int? projectId)
{

View File

@ -291,6 +291,8 @@ public class Program
builder.Services.Configure<Microsoft.AspNetCore.SignalR.HubOptions<PlotLine.Hubs.NativeCompanionPresenceHub>>(options => options.MaximumReceiveMessageSize = 16384);
builder.Services.AddSingleton<ContextWorkspaceNotifications>();
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterPanels>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterEditing>();
builder.Services.AddSingleton<IManuscriptScanPreviewStore, ManuscriptScanPreviewStore>();
builder.Services.AddSingleton<IOnboardingStoryIntelligenceBatchStore, OnboardingStoryIntelligenceBatchStore>();
builder.Services.AddHostedService<WordCompanionPresenceMonitor>();

View File

@ -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<SelectListItem> 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<ContextCharacterEditForm> Read(int bookId,int sceneId,int characterId,string field)=>(await Load(bookId,sceneId,characterId,field)).Form;
private async Task<Frame> 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<string,string>{{"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<SelectListItem> options=[];
if(field=="classification"){
var choices=new List<SelectListItem>{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();}
}
}

View File

@ -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<CharacterKnowledgeItem> 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<ContextCharacterRow> 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<ContextCharacterExplorer> 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<Character> characters,IReadOnlyList<SceneCharacter> appearances,IReadOnlyList<LocationItem> 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<ContextCharacterRow>();
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]<at).Reverse().ToList();
var previous=preceding.Select(Place).FirstOrDefault(p=>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()};
}
}

View File

@ -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<CharacterEditViewModel?> GetEditCharacterAsync(int characterId)

View File

@ -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)
{

View File

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

View File

@ -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<StoryPointThread> RelevantThreads => Context==null?[]:WritingContextRelevance.Threads(Context);
public IReadOnlyList<StoryCalendarSceneViewModel> NearbyScenes {get;set;}=[];

View File

@ -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" } }
};
}
<link rel="stylesheet" href="~/css/context-workspace.css" asp-append-version="true" />
@ -40,6 +40,7 @@
</section>
}
</div>
<dialog data-context-edit-dialog class="context-windows-dialog"><h2 class="h5">Focused correction</h2><div data-context-edit-content></div><p data-context-edit-status role="status"></p><button type="button" data-context-edit-close class="btn btn-outline-secondary">Close</button></dialog>
<dialog data-context-windows-dialog class="context-windows-dialog">
<h2 class="h5">My Context windows</h2><p>Only your connected windows for this book appear. Commands focus a reference tool; they do not navigate Word.</p>
<div data-context-window-list></div>
@ -54,4 +55,5 @@
<script src="~/js/context-tools.js" asp-append-version="true"></script>
<script src="~/js/context-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-windows.js" asp-append-version="true"></script>
<script src="~/js/context-editing.js" asp-append-version="true"></script>
}

View File

@ -0,0 +1,18 @@
@using PlotLine.Services.Context
@model ValueTuple<ContextCharacterExplorer,ContextCharacterRow>
@{var explorer=Model.Item1;var row=Model.Item2;}
<div class="context-character-detail" data-character-detail="@row.Character.CharacterID">
<div class="context-location-rail" aria-label="Recorded character locations">
@foreach(var item in new[]{("Previous",row.Previous),("Now",row.Now),("Next · future record",row.Next)}){
<div><strong>@item.Item1</strong>@if(item.Item2 is {} place){<button type="button" class="btn btn-link btn-sm" data-context-location="@place.LocationID" data-location-scene="@place.SceneID" data-location-chapter="@place.ChapterID">@place.Name</button><a href="/Scenes/Edit/@place.SceneID" target="_blank" rel="noopener" class="small">Source scene</a>}
else{<span>@(item.Item1=="Now"?(row.Participation=="Mentioned only"?"Mentioned only · no physical presence implied":"No recorded location here"):"No recorded location")</span>}</div>
}
</div>
<dl class="writing-context-facts"><dt>Emotional state</dt><dd>@(string.IsNullOrWhiteSpace(row.Emotion)?"Not recorded in this scene":row.Emotion)</dd><dt>Physical condition</dt><dd>@(string.IsNullOrWhiteSpace(row.Condition)?"Not recorded in this scene":row.Condition)</dd><dt>Reference</dt><dd>@(string.IsNullOrWhiteSpace(row.Character.DefaultDescription)?"No character description recorded":row.Character.DefaultDescription)</dd></dl>
@if(row.Knowledge.Any()){<p class="small">@(row.IsPov?"Verified viewpoint knowledge at this point":"Author reference: this character’s established knowledge; not necessarily viewpoint knowledge")</p><ul>@foreach(var fact in row.Knowledge.Take(4)){<li>@fact.KnowledgeStateName: @fact.Description <a href="/Scenes/Edit/@fact.SceneID" target="_blank" rel="noopener">Source</a></li>}</ul>}
@if(explorer.CanEdit){<div class="context-edit-actions">
@foreach(var field in new[]{("classification","Classification"),("description","Description")}){<button class="btn btn-outline-secondary btn-sm" type="button" data-context-edit="@field.Item1" data-character-id="@row.Character.CharacterID">Correct @field.Item2</button>}
@if(row.Appearance!=null){@foreach(var field in new[]{("emotion","Emotional state"),("condition","Physical condition"),("location","Current location")}){<button class="btn btn-outline-secondary btn-sm" type="button" data-context-edit="@field.Item1" data-character-id="@row.Character.CharacterID">Correct @field.Item2</button>}}
</div>}else{<p class="small">Read-only reference.</p>}
<a href="/Characters/Details/@row.Character.CharacterID" target="_blank" rel="noopener">Open character workspace</a>
</div>

View File

@ -0,0 +1,13 @@
@model PlotLine.Services.Context.ContextCharacterEditForm
<form action="/Writing/Context/EditCharacter" method="post" data-context-edit-form>
@Html.AntiForgeryToken()
<input asp-for="BookID" type="hidden" /><input asp-for="SceneID" type="hidden" /><input asp-for="CharacterID" type="hidden" /><input asp-for="Field" type="hidden" /><input asp-for="Fingerprint" type="hidden" />
<p><strong>@Model.CharacterName</strong> · @Model.Label</p>
<div asp-validation-summary="All" class="text-danger" role="alert"></div>
<label>@Model.Label
@if(Model.Options.Count>0){<select asp-for="Value" asp-items="Model.Options" class="form-select"></select>}
else{<textarea asp-for="Value" class="form-control" maxlength="4000" rows="4"></textarea>}
</label>
<p class="small text-muted">Only this correction is saved. Other character and scene fields are retained.</p>
<button type="submit" class="btn btn-primary">Save correction</button><button type="button" class="btn btn-outline-secondary" data-context-edit-cancel>Cancel</button>
</form>

View File

@ -0,0 +1,6 @@
@using PlotLine.Services.Context
@model ValueTuple<ContextCharacterExplorer,ContextCharacterRow>
<div data-character-reference data-context-tab-fragment data-book-id="@Model.Item1.BookID" data-scene-id="@Model.Item1.SceneID" tabindex="-1">
<h3 class="h5">@Model.Item2.Character.CharacterName</h3><p>Saved reference at @Model.Item1.SceneTitle. The active manuscript scene is unchanged.</p>
<partial name="~/Views/Writing/_ContextCharacterDetail.cshtml" model="Model" />
</div>

View File

@ -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())
{
<section class="writing-context-empty">
<h3>No characters recorded for this scene</h3>
<p>When scene participants are added, their current state will appear here.</p>
</section>
}
else
{
<div class="writing-context-people-grid">
@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();
<article class="writing-context-card writing-context-person-card" data-context-character="@character.CharacterID" tabindex="-1">
<div class="writing-context-person-heading">
<partial name="~/Views/Shared/_Avatar.cshtml" model="@(new AvatarViewModel { DisplayName = character.CharacterName, ImagePath = character.CharacterImagePath, ThumbnailPath = character.CharacterThumbnailPath, Size = "md" })" />
<div>
<h3>@character.CharacterName</h3>
<p>@(character.CharacterID == povCharacterId ? "POV" : character.RoleInSceneTypeName ?? character.PresenceTypeName ?? "In scene")</p>
</div>
</div>
<dl class="writing-context-facts">
<dt>Location</dt><dd>@TextOr(character.LocationPath ?? character.LocationName, "Unknown")</dd>
<dt>Last recorded location</dt><dd>@(known?.State?.CurrentLocation ?? "Not recorded")</dd>
<dt>Emotional state</dt><dd>@TextOr(character.EmotionalState, "Not recorded")</dd>
<dt>Physical condition</dt><dd>@TextOr(character.PhysicalCondition, "Not recorded")</dd>
<dt>Outfit</dt><dd>@TextOr(character.OutfitDescription ?? character.AppearanceNotes, "Not recorded")</dd>
<dt>Movement</dt><dd>@TextOr(string.Join(" -> ", new[] { character.EntryLocationName, character.ExitLocationName }.Where(x => !string.IsNullOrWhiteSpace(x))), "No entry or exit recorded")</dd>
</dl>
<p class="small text-muted">@(character.CharacterID==povCharacterId?"Verified viewpoint knowledge at this narrative point":"Author reference: this character’s knowledge, not necessarily the viewpoint character’s")</p>
@if (knowledge.Any() || attributes.Any())
{
<div class="writing-context-mini-section">
@foreach (var item in knowledge.Take(3))
{
<p><strong>@item.KnowledgeStateName:</strong> @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.") <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Source scene</a></p>
}
@foreach (var item in attributes.Take(3))
{
<p><strong>@item.AttributeName:</strong> @item.AttributeValue</p>
}
</div>
}
</article>
}
<div data-character-explorer data-book="@explorer.BookID" data-scene="@explorer.SceneID">
<div class="context-explorer-controls">
<label>Find a character <input type="search" class="form-control form-control-sm" data-character-filter autocomplete="off" /></label>
<label>Show <select class="form-select form-select-sm" data-character-scope><option value="scene">Scene participants (@explorer.Rows.Count(r=>r.InScene))</option><option value="catalogue">Character catalogue (@explorer.Rows.Count)</option></select></label>
</div>
}
@if(!explorer.Rows.Any(r=>r.InScene)){<p data-character-empty>No characters recorded for this scene. The catalogue remains available.</p>}
<p class="small text-muted">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.</p>
<div class="context-character-list">
@foreach(var row in explorer.Rows){
<details class="context-character-row" data-context-character="@row.Character.CharacterID" data-in-scene="@row.InScene.ToString().ToLowerInvariant()" data-filter-name="@row.Character.CharacterName" tabindex="-1" hidden="@(!row.InScene)">
<summary><partial name="~/Views/Shared/_Avatar.cshtml" model="@(new AvatarViewModel{DisplayName=row.Character.CharacterName,ImagePath=row.Character.ImagePath,ThumbnailPath=row.Character.ThumbnailPath,Size="sm"})" /><strong>@row.Character.CharacterName</strong><span>@(row.IsPov?"POV · ":"")@row.Participation</span><small>@row.Classification</small></summary>
<partial name="~/Views/Writing/_ContextCharacterDetail.cshtml" model="(explorer,row)" />
</details>
}
</div>
<p data-character-no-matches hidden>No matching characters. Try the catalogue or a different spelling.</p>
<div data-character-inspection></div><p data-context-interaction-status role="status"></p>
<a href="/Characters?projectId=@explorer.ProjectID" target="_blank" rel="noopener">Open full Characters workspace</a>
</div>

View File

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

View File

@ -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')||/<!doctype/i.test(html))throw Error('Sign in again before editing.');host.replaceChildren(form);}
function close(saved=false){if(busy)return;if(dirty&&!saved&&!confirm('Discard this unsaved correction?'))return;load?.abort();dialog.close();dirty=false;state(saved);pane=null;host.replaceChildren();status.textContent='';originalFocus?.isConnected&&originalFocus.focus({preventScroll:true});}
root.addEventListener('click',async event=>{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='';}});
})();

View File

@ -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}}));}
}
};
})();

View File

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