From c63925c6485686b3376672bc14b5cacee163cd8c Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 22 Nov 2026 15:30:05 +0000 Subject: [PATCH] Add Context Names lookup, reference suggestions and focused alias editing --- .../Unified-Context-Enhancements-20261122.md | 10 ++++++ PlotLine.Tests/Browser/context-names.cjs | 15 ++++++++ PlotLine.Tests/ContextCharacterTests.cs | 17 +++++++++ PlotLine.Tests/ToolbarBrowserHost.cs | 3 +- PlotLine/Controllers/WritingController.cs | 16 ++++++++- PlotLine/Data/Repositories.cs | 7 ++++ PlotLine/Program.cs | 1 + .../Context/ContextCharacterEditing.cs | 36 ++++++++++++++++--- PlotLine/Services/Context/ContextNames.cs | 23 ++++++++++++ PlotLine/Sql/298_ContextCharacterAliases.sql | 16 +++++++++ PlotLine/ViewModels/CoreViewModels.cs | 1 + PlotLine/Views/Writing/Context.cshtml | 3 +- .../Writing/_ContextNameSuggestions.cshtml | 6 ++++ PlotLine/Views/Writing/_ContextNames.cshtml | 18 ++++++++++ PlotLine/wwwroot/js/context-tools.js | 17 +++++++++ 15 files changed, 182 insertions(+), 7 deletions(-) create mode 100644 PlotLine.Tests/Browser/context-names.cjs create mode 100644 PlotLine/Services/Context/ContextNames.cs create mode 100644 PlotLine/Sql/298_ContextCharacterAliases.sql create mode 100644 PlotLine/Views/Writing/_ContextNameSuggestions.cshtml create mode 100644 PlotLine/Views/Writing/_ContextNames.cshtml diff --git a/Docs/Writer/Unified-Context-Enhancements-20261122.md b/Docs/Writer/Unified-Context-Enhancements-20261122.md index e75d6243..e5ba252d 100644 --- a/Docs/Writer/Unified-Context-Enhancements-20261122.md +++ b/Docs/Writer/Unified-Context-Enhancements-20261122.md @@ -37,3 +37,13 @@ Compact scene-first Characters explorer uses canonical timeline/appearance reads 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. + +Phase 2 deployed commit `6e6c7fd`; archived `context-enhancement-phase2-6e6c7fd-20261122T152545Z`. Published/live assembly and assets SHA-256 matched; informational version matched commit; local and public TLS GET200; authenticated Characters canonical partial passed. + +### Phase 3 + +Names uses existing canonical characters, aliases, Unicode normalisation and `INameIntelligenceService.BuildLibraryAsync` (book locale/era defaults and related forms). New migration298 provides one authenticated project alias read instead of per-character catalogue reads. Shared normalized spellings across different IDs are explicitly review hints; aliases belonging to one character do not create false duplicate identities. No general near-name detector was found; existing related forms are offered as spelling hints, without a replacement generator or inferred identity merge. + +Focused canonical rename retains the previous spelling as an alias through the existing character service. Individual alias add/correct/remove uses existing canonical repository saves after full book/project/role checks, fingerprint validation and alias ownership verification. Canonical alias cannot be deleted through alias correction; use the name action. Names→Characters sends structured `character.focus` and never switches an unrelated tab. Full Names and Character editors remain linked. + +Qualification: clean build, 17 focused character/name assertions including Unicode-equivalent shared spelling and legitimate aliases; compiled Razor browser passes canonical/alias filtering, collision review, structured focus, focused alias form/cancel, independent same-tool panes and mobile widths. Migration298 applied/verified after `context-enhancement-phase3-20261122.bak` backup and VERIFYONLY. No character/name rows bulk changed. diff --git a/PlotLine.Tests/Browser/context-names.cjs b/PlotLine.Tests/Browser/context-names.cjs new file mode 100644 index 00000000..bd1c4977 --- /dev/null +++ b/PlotLine.Tests/Browser/context-names.cjs @@ -0,0 +1,15 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'); +const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();let step='setup';try{ + const context=await browser.newContext({viewport:{width:1366,height:768}});let posts=0,fail=true; + await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))})); + for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await context.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}})); + await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});}); + await context.route('**/Writing/Context/EditCharacter*',async r=>{const post=r.request().method()==='POST';if(post)posts++;if(post&&!fail)return r.fulfill({json:{saved:true,bookId:12}});const response=await r.fetch({url:base+'/context-edit-fixture?field=description'+(post?'&invalid=true':''),method:'GET'});await r.fulfill({status:post?422:200,contentType:'text/html',body:await response.text()});}); + 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='canonical names aliases and shared spellings';await page.selectOption('[data-context-tab]','names');await page.waitForSelector('[data-context-names]');assert.match(await page.locator('[data-context-names]').textContent(),/Known variant/);assert.match(await page.locator('[data-context-names]').textContent(),/Shared spelling/);await page.locator('[data-name-filter]').fill('Known variant');assert.equal(await page.locator('[data-name-row]:visible').count(),1);await page.locator('[data-name-row]:visible summary').click(); + step='structured character focus without replacing names';await page.evaluate(()=>{window.sent=[];document.querySelector('[data-context-workspace]').addEventListener('context-command',e=>sent.push(e.detail));});await page.locator('[data-name-focus="5"]').click();assert.equal(await page.evaluate(()=>sent[0].characterID),5);assert.equal(await page.locator('[data-context-tab]').first().inputValue(),'names'); + step='focused alias modal and full editor access';await page.locator('[data-context-edit="alias:11"]').click();await page.waitForSelector('[data-context-edit-form]');await page.click('[data-context-edit-cancel]');assert.equal(posts,0);assert(await page.locator('a[href*="/Names?projectId=7"]').count()); + step='mobile and same-tool independence';await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','names');await page.locator('[data-context-pane="1"] [data-name-filter]').fill('name 10');assert.equal(await page.locator('[data-context-pane="0"] [data-name-filter]').inputValue(),'Known variant');for(const width of [1366,760,390]){await page.setViewportSize({width,height:800});await page.waitForTimeout(50);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));} + assert.deepEqual(errors,[]);console.log('PASS Names browser: canonical/alias lookup, shared spelling review, structured focus, focused alias form/cancel, full workspace link, mobile and independent panes'); +} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await browser.close();}})(); diff --git a/PlotLine.Tests/ContextCharacterTests.cs b/PlotLine.Tests/ContextCharacterTests.cs index 7535e626..0f84d036 100644 --- a/PlotLine.Tests/ContextCharacterTests.cs +++ b/PlotLine.Tests/ContextCharacterTests.cs @@ -29,8 +29,18 @@ internal static class ContextCharacterTests 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 aliases=new List{new(){CharacterAliasID=11,CharacterID=5,Alias="Kept alias",SortOrder=10}}; + var repository=NativeWorkflowTests.Proxy((name,args)=>name switch{ + "ListAliasesAsync"=>Task.FromResult>(aliases.ToList()), + "AddAliasAsync"=>AddAlias((string)args![1]!), + "UpdateAliasAsync"=>UpdateAlias((int)args![0]!, (string)args[1]!), + "DeleteAliasAsync"=>DeleteAlias((int)args![0]!),_=>throw new Exception(name)}); + Task AddAlias(string value){aliases.Add(new(){CharacterAliasID=12,CharacterID=5,Alias=value});return Task.FromResult(12);} + Task UpdateAlias(int id,string value){aliases.Single(a=>a.CharacterAliasID==id).Alias=value;return Task.CompletedTask;} + Task DeleteAlias(int id){aliases.RemoveAll(a=>a.CharacterAliasID==id);return Task.CompletedTask;} var edit=new ContextCharacterEditing(service, NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){Position=new(7,12,10,22),Scene=new(){SceneID=22,SceneCharacters=[appearance]}})), + repository, 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)); @@ -38,6 +48,13 @@ internal static class ContextCharacterTests 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"); + var rename=await edit.Read(12,22,5,"name");rename.Value="New canonical";await edit.Save(rename);Check(character.CharacterName=="New canonical"&&character.Aliases.Contains("Preserve name"),"canonical rename retains the old spelling as an alias"); + var add=await edit.Read(12,22,5,"alias-add");add.Value="New variant";await edit.Save(add);Check(aliases.Any(a=>a.Alias=="New variant"),"focused alias add reuses existing alias persistence"); + var correction=await edit.Read(12,22,5,"alias:11");correction.Value="Corrected alias";await edit.Save(correction);Check(aliases.Single(a=>a.CharacterAliasID==11).Alias=="Corrected alias","individual alias correction preserves identity"); + var remove=await edit.Read(12,22,5,"alias:11");remove.Value="";await edit.Save(remove);Check(aliases.All(a=>a.CharacterAliasID!=11),"explicit empty alias correction removes only the selected alias"); + var nameRows=ContextNames.Compose([new(){CharacterID=5,CharacterName="Éva"},new(){CharacterID=6,CharacterName="Another"}],[new(){CharacterID=5,Alias="Éva"},new(){CharacterID=6,Alias="E\u0301VA"}]); + Check(nameRows.All(r=>r.SharedSpellings.Any()),"existing Unicode normalisation detects cross-character shared spellings including aliases"); + Check(ContextNames.Compose([new(){CharacterID=5,CharacterName="Person"}],[new(){CharacterID=5,Alias="PERSON"}]).Single().SharedSpellings.Count==0,"legitimate aliases of one identity are not duplicate identities"); 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/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 51f4d911..d3c4a4ac 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -417,10 +417,11 @@ internal static class ToolbarBrowserHost var appearances=scene.SceneCharacters.Concat(new SceneCharacter[]{new(){CharacterID=5,SceneID=21,PresenceTypeName="Present",LocationID=78},new(){CharacterID=5,SceneID=23,PresenceTypeName="Present",LocationID=79}}).ToList(); model.CharacterExplorer=PlotLine.Services.Context.ContextCharacterPanels.Compose(model,catalogue,appearances,[new(){LocationID=77,LocationName="Saved room"},new(){LocationID=78,LocationName="Earlier hall"},new(){LocationID=79,LocationName="Following garden"}],true); + model.NamePanel=new PlotLine.Services.Context.ContextNamePanel(7,12,true,PlotLine.Services.Context.ContextNames.Compose(catalogue,[new(){CharacterAliasID=11,CharacterID=5,Alias="Known variant"},new(){CharacterAliasID=12,CharacterID=6,Alias="Fixture participant"}]),new(){Results=[new(){DisplayName="Reference suggestion",RelatedForms="Known spelling variant"}]}); var action=new ActionContext(context,new RouteData(),new ActionDescriptor()); var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextTab.cshtml",false); using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; - data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()=="characters"?"_WritingContextPeople":"_WritingContextOverview"; + data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()switch{"characters"=>"_WritingContextPeople","names"=>"_ContextNames",_=>"_WritingContextOverview"}; await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); }); diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index a574feea..61255cce 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,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null) : Controller + ILogger logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null,PlotLine.Services.Context.ContextNames? contextNames=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) @@ -103,6 +103,19 @@ public sealed class WritingController( public Task ContextCharacters(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId = null, Guid? sessionId = null) => RenderContextTab("_WritingContextPeople", projectId, bookId, chapterId, sceneId, instanceId, sessionId); + [HttpGet("Context/Tabs/names")] + public Task ContextNamesTab(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId=null,Guid? sessionId=null) + =>RenderContextTab("_ContextNames",projectId,bookId,chapterId,sceneId,instanceId,sessionId); + [HttpGet("Context/NameSuggestions")] + public async Task ContextNameSuggestions(int bookId,string? search,[FromServices] IBookRepository books) + { + if(contextNames==null||companion==null)return BadRequest(); + var structure=await companion.GetBookStructureAsync(bookId,WritingUser);if(structure==null)return Forbid(); + var book=await books.GetAsync(bookId);if(book==null)return NotFound(); + var model=await contextNames.Build(book.ProjectID,bookId,search?.Length>100?search[..100]:search); + return PartialView("~/Views/Writing/_ContextNameSuggestions.cshtml",model); + } + private async Task RenderContextTab(string partial, int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId, Guid? sessionId) { if (!ModelState.IsValid || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest(); @@ -116,6 +129,7 @@ public sealed class WritingController( if (model?.HasScene != true) return NotFound(); if (projectAccess == null || !await projectAccess.CanAccessProjectAsync(model.Context!.Position.ProjectId)) return Forbid(); if(partial=="_WritingContextPeople"&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model); + if(partial=="_ContextNames"&&contextNames!=null)model.NamePanel=await contextNames.Build(model.Context!.Position.ProjectId,model.Context.Position.BookId!.Value); ViewData["ContextTabPartial"] = partial; return PartialView("_ContextTab", model); } diff --git a/PlotLine/Data/Repositories.cs b/PlotLine/Data/Repositories.cs index 71f7b5db..af67adde 100644 --- a/PlotLine/Data/Repositories.cs +++ b/PlotLine/Data/Repositories.cs @@ -217,6 +217,7 @@ public interface ICharacterRepository Task GetCharacterAsync(int characterId); Task SaveCharacterAsync(Character character); Task> ListAliasesAsync(int characterId); + Task> ListProjectAliasesAsync(int projectId,int userId); Task AddAliasAsync(int characterId, string alias, int? sortOrder); Task UpdateAliasAsync(int characterAliasId, string alias, int? sortOrder); Task DeleteAliasAsync(int characterAliasId); @@ -3772,6 +3773,12 @@ public sealed class CharacterRepository(ISqlConnectionFactory connectionFactory, commandType: CommandType.StoredProcedure); } + public async Task> ListProjectAliasesAsync(int projectId,int userId) + { + using var connection=connectionFactory.CreateConnection(); + return (await connection.QueryAsync("dbo.CharacterAlias_ListByProjectForUser",new{ProjectID=projectId,UserID=userId},commandType:CommandType.StoredProcedure)).ToList(); + } + public async Task> ListAliasesAsync(int characterId) { using var connection = connectionFactory.CreateConnection(); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 4b10f578..495c2c75 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -292,6 +292,7 @@ public class Program builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Services/Context/ContextCharacterEditing.cs b/PlotLine/Services/Context/ContextCharacterEditing.cs index 4f0c3c80..40c105ba 100644 --- a/PlotLine/Services/Context/ContextCharacterEditing.cs +++ b/PlotLine/Services/Context/ContextCharacterEditing.cs @@ -15,7 +15,7 @@ public sealed class ContextCharacterEditForm public string Label{get;set;}="";public string CharacterName{get;set;}=""; public IReadOnlyList Options{get;set;}=[]; } -public sealed class ContextCharacterEditing(ICharacterService characters,IStoryContextService stories, +public sealed class ContextCharacterEditing(ICharacterService characters,IStoryContextService stories,ICharacterRepository repository, 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(); @@ -33,20 +33,24 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC 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"}}; + var aliases=await repository.ListAliasesAsync(characterId); + var selectedAlias=field.StartsWith("alias:")&&int.TryParse(field[6..],out var aliasId)?aliases.SingleOrDefault(a=>a.CharacterAliasID==aliasId):null; + labels["name"]="Canonical name (previous spelling retained as an alias)";labels["alias-add"]="Add one alias"; + if(selectedAlias!=null)labels[field]="Correct alias (clear to remove this alias)"; 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}; + var value=field switch{"classification"=>character.CharacterImportance?.ToString(),"description"=>character.DefaultDescription,"emotion"=>appearance?.EmotionalState,"condition"=>appearance?.PhysicalCondition,"location"=>appearance?.LocationID?.ToString(),"name"=>character.CharacterName,"alias-add"=>"",_=>selectedAlias?.Alias}; 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}); + 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,AliasRecords=aliases}); 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) @@ -56,7 +60,31 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC 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"){ + if(input.Field=="name"||input.Field.StartsWith("alias")){ + var value=input.Value?.Trim()??""; + if(value.Length>200)throw new ArgumentException("Use 200 characters or fewer for a name or alias."); + if(input.Field=="name"){ + if(value.Length==0)throw new ArgumentException("Enter the canonical name."); + frame.Character.Aliases=frame.Character.Aliases.Append(frame.Character.CharacterName).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + frame.Character.CharacterName=value;await characters.SaveCharacterAsync(frame.Character); + }else{ + var aliases=await repository.ListAliasesAsync(input.CharacterID); + if(input.Field=="alias-add"){ + if(value.Length==0)throw new ArgumentException("Enter an alias."); + if(aliases.Count>=50)throw new ArgumentException("Review the full character editor before adding more than 50 aliases."); + if(aliases.Any(a=>string.Equals(a.Alias,value,StringComparison.OrdinalIgnoreCase)))throw new ArgumentException("This character already has that alias."); + await repository.AddAliasAsync(input.CharacterID,value,null); + }else{ + var alias=aliases.Single(a=>a.CharacterAliasID==int.Parse(input.Field[6..])); + if(string.Equals(alias.Alias,frame.Character.CharacterName,StringComparison.OrdinalIgnoreCase))throw new ArgumentException("Correct the canonical name using its own action."); + if(value.Length==0)await repository.DeleteAliasAsync(alias.CharacterAliasID); + else{ + if(aliases.Any(a=>a.CharacterAliasID!=alias.CharacterAliasID&&string.Equals(a.Alias,value,StringComparison.OrdinalIgnoreCase)))throw new ArgumentException("This character already has that alias."); + await repository.UpdateAliasAsync(alias.CharacterAliasID,value,alias.SortOrder); + } + } + } + }else 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);} diff --git a/PlotLine/Services/Context/ContextNames.cs b/PlotLine/Services/Context/ContextNames.cs new file mode 100644 index 00000000..b3ef54a4 --- /dev/null +++ b/PlotLine/Services/Context/ContextNames.cs @@ -0,0 +1,23 @@ +using PlotLine.Data; +using PlotLine.Models; +namespace PlotLine.Services.Context; +public sealed record ContextNameEntry(Character Character,IReadOnlyList Aliases,IReadOnlyList SharedSpellings); +public sealed record ContextNamePanel(int ProjectID,int BookID,bool CanEdit,IReadOnlyList Entries,PlotLine.ViewModels.NamesLibraryViewModel? Library); +public sealed class ContextNames(ICharacterRepository characters,IProjectRepository projects,ICurrentUserService user,INameIntelligenceService names) +{ + public async Task Build(int projectId,int bookId,string? search=null) + { + var author=user.UserId??throw new UnauthorizedAccessException(); + var project=await projects.GetForUserAsync(projectId,author)??throw new UnauthorizedAccessException(); + var people=await characters.ListCharactersAsync(projectId);var aliases=await characters.ListProjectAliasesAsync(projectId,author); + var library=await names.BuildLibraryAsync(new(){ProjectID=projectId,BookID=bookId,Search=search,PageSize=12}); + return new(projectId,bookId,ContextEditPolicy.CanEdit(project),Compose(people,aliases),library); + } + public static IReadOnlyList Compose(IReadOnlyList people,IReadOnlyList aliases) + { + var active=people.Where(c=>!c.IsArchived).ToList();var ids=active.Select(c=>c.CharacterID).ToHashSet(); + var all=active.Select(c=>(c.CharacterID,Name:c.CharacterName)).Concat(aliases.Where(a=>ids.Contains(a.CharacterID)).Select(a=>(a.CharacterID,Name:a.Alias))).ToList(); + var shared=all.GroupBy(a=>NameIntelligenceService.NormaliseName(a.Name)).Where(g=>g.Select(a=>a.CharacterID).Distinct().Count()>1).Select(g=>g.Key).ToHashSet(); + return active.OrderBy(c=>c.CharacterName).Select(c=>new ContextNameEntry(c,aliases.Where(a=>a.CharacterID==c.CharacterID).ToList(),all.Where(a=>a.CharacterID==c.CharacterID&&shared.Contains(NameIntelligenceService.NormaliseName(a.Name))).Select(a=>a.Name).Distinct().ToList())).ToList(); + } +} diff --git a/PlotLine/Sql/298_ContextCharacterAliases.sql b/PlotLine/Sql/298_ContextCharacterAliases.sql new file mode 100644 index 00000000..535a26e0 --- /dev/null +++ b/PlotLine/Sql/298_ContextCharacterAliases.sql @@ -0,0 +1,16 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.CharacterAlias_ListByProjectForUser @ProjectID int,@UserID int +AS +BEGIN + SET NOCOUNT ON; + SELECT a.CharacterAliasID,a.CharacterID,a.Alias,a.SortOrder,a.CreatedUtc + FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID + WHERE c.ProjectID=@ProjectID AND c.IsArchived=0 AND EXISTS + (SELECT 1 FROM dbo.ProjectUserAccess pua JOIN dbo.Projects p ON p.ProjectID=pua.ProjectID + WHERE pua.ProjectID=@ProjectID AND pua.UserID=@UserID AND pua.IsActive=1 AND p.IsArchived=0) + ORDER BY c.CharacterID,a.SortOrder,a.CharacterAliasID; +END; +GO diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 0d0552f8..ee86bd94 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.ContextNamePanel? NamePanel{get;set;} public PlotLine.Services.Context.ContextCharacterExplorer? CharacterExplorer {get;set;} public StoryPointSnapshot? AtPoint => Context?.Narrative?.Snapshot; public IReadOnlyList RelevantThreads => Context==null?[]:WritingContextRelevance.Threads(Context); diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index b59958c3..8315bf5c 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -6,7 +6,8 @@ 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 = "characters", 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" } }, + new { id = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() } }; } diff --git a/PlotLine/Views/Writing/_ContextNameSuggestions.cshtml b/PlotLine/Views/Writing/_ContextNameSuggestions.cshtml new file mode 100644 index 00000000..0249f461 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextNameSuggestions.cshtml @@ -0,0 +1,6 @@ +@model PlotLine.Services.Context.ContextNamePanel +
+

Existing reference library, using the book’s recorded locale and era where available. Related forms are spelling hints, not proof of a shared identity.

+@if(Model.Library?.Results.Any()==true){
    @foreach(var row in Model.Library.Results){
  • @row.DisplayName @row.LocaleDisplayName @if(!string.IsNullOrWhiteSpace(row.RelatedForms)){· Related forms: @row.RelatedForms}@if(row.UsedCount>0){· Already used (@row.UsedCount)}
  • }
} +else{

No reference suggestions found. Try the full naming workspace for broader filters.

} +
diff --git a/PlotLine/Views/Writing/_ContextNames.cshtml b/PlotLine/Views/Writing/_ContextNames.cshtml new file mode 100644 index 00000000..181c6a67 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextNames.cshtml @@ -0,0 +1,18 @@ +@model WritingContextDisplayViewModel +@{var panel=Model.NamePanel;} +@if(panel==null){

Names reference unavailable. Reopen this tool.

}else{ +
+ +

Canonical names and aliases are separate identities only when the author records them that way. Shared spellings may be intentional; no identities are merged.

+
+@foreach(var entry in panel.Entries){
a.Alias)))">@entry.Character.CharacterName@if(entry.SharedSpellings.Any()){Shared spelling · review} +
+@if(entry.SharedSpellings.Any()){

Also recorded for another character: @string.Join(", ",entry.SharedSpellings). This can be a legitimate shared name.

} +@if(panel.CanEdit){} +
    @foreach(var alias in entry.Aliases){
  • @alias.Alias (alias / known variant)@if(panel.CanEdit&&!string.Equals(alias.Alias,entry.Character.CharacterName,StringComparison.OrdinalIgnoreCase)){}
  • }
+@if(panel.CanEdit){} +Full character editor
} +
+
Name suggestions and related forms
+

Open full Names workspace +
} diff --git a/PlotLine/wwwroot/js/context-tools.js b/PlotLine/wwwroot/js/context-tools.js index b7a547c3..7d800d29 100644 --- a/PlotLine/wwwroot/js/context-tools.js +++ b/PlotLine/wwwroot/js/context-tools.js @@ -33,3 +33,20 @@ } }; })(); +(() => { + const states=new Map(),mounted=new WeakMap(); + window.PlotDirectorContextLifecycles.names={ + mount(element,{paneId}){ + const host=element.querySelector('[data-context-names]');if(!host)return;const abort=new AbortController(),signal=abort.signal;mounted.set(element,{abort,host,paneId}); + const input=host.querySelector('[data-name-filter]');input.value=states.get(paneId)||''; + function filter(){const value=input.value.toLocaleLowerCase();let count=0;host.querySelectorAll('[data-name-row]').forEach(row=>{row.hidden=!row.dataset.filterName.toLocaleLowerCase().includes(value);if(!row.hidden)count++;});host.querySelector('[data-name-no-matches]').hidden=count>0;} + filter();input.addEventListener('input',filter,{signal}); + host.addEventListener('click',e=>{const button=e.target.closest('[data-name-focus]');if(button)host.dispatchEvent(new CustomEvent('context-command',{bubbles:true,detail:{action:'character.focus',characterID:Number(button.dataset.nameFocus)}}));},{signal}); + let request; + host.querySelector('[data-name-suggestions-form]').addEventListener('submit',async e=>{e.preventDefault();request?.abort();request=new AbortController();const target=host.querySelector('[data-name-suggestions]');target.textContent='Looking up existing reference names…'; + try{const url=new URL('/Writing/Context/NameSuggestions',location.origin);url.searchParams.set('bookId',host.dataset.book);url.searchParams.set('search',new FormData(e.target).get('search'));const response=await fetch(url,{signal:request.signal,cache:'no-store'});if(!response.ok||response.redirected)throw Error('Name reference is unavailable.');const doc=new DOMParser().parseFromString(await response.text(),'text/html'),result=doc.querySelector('[data-name-suggestion-results]');if(!result)throw Error('Name reference is unavailable.');target.replaceChildren(result);}catch(error){if(error.name!=='AbortError')target.textContent=error.message;} + },{signal});signal.addEventListener('abort',()=>request?.abort(),{once:true}); + }, + dispose(element){const state=mounted.get(element);if(state){states.set(state.paneId,state.host.querySelector('[data-name-filter]').value);state.abort.abort();mounted.delete(element);}} + }; +})();