Add Context Names lookup, reference suggestions and focused alias editing
This commit is contained in:
parent
6e6c7fdcd9
commit
c63925c648
@ -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.
|
||||
|
||||
15
PlotLine.Tests/Browser/context-names.cjs
Normal file
15
PlotLine.Tests/Browser/context-names.cjs
Normal file
@ -0,0 +1,15 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');
|
||||
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
|
||||
(async()=>{const 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();}})();
|
||||
@ -29,8 +29,18 @@ internal static class ContextCharacterTests
|
||||
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 aliases=new List<CharacterAlias>{new(){CharacterAliasID=11,CharacterID=5,Alias="Kept alias",SortOrder=10}};
|
||||
var repository=NativeWorkflowTests.Proxy<ICharacterRepository>((name,args)=>name switch{
|
||||
"ListAliasesAsync"=>Task.FromResult<IReadOnlyList<CharacterAlias>>(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<int> 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<IStoryContextService>((_,_)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=new(){SceneID=22,SceneCharacters=[appearance]}})),
|
||||
repository,
|
||||
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));
|
||||
@ -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");}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<ICompositeViewEngine>().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<ITempDataProvider>()),writer,new HtmlHelperOptions()));
|
||||
context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
|
||||
});
|
||||
|
||||
@ -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,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null) : Controller
|
||||
ILogger<WritingController> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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);
|
||||
}
|
||||
|
||||
@ -217,6 +217,7 @@ public interface ICharacterRepository
|
||||
Task<Character?> GetCharacterAsync(int characterId);
|
||||
Task<int> SaveCharacterAsync(Character character);
|
||||
Task<IReadOnlyList<CharacterAlias>> ListAliasesAsync(int characterId);
|
||||
Task<IReadOnlyList<CharacterAlias>> ListProjectAliasesAsync(int projectId,int userId);
|
||||
Task<int> 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<IReadOnlyList<CharacterAlias>> ListProjectAliasesAsync(int projectId,int userId)
|
||||
{
|
||||
using var connection=connectionFactory.CreateConnection();
|
||||
return (await connection.QueryAsync<CharacterAlias>("dbo.CharacterAlias_ListByProjectForUser",new{ProjectID=projectId,UserID=userId},commandType:CommandType.StoredProcedure)).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<CharacterAlias>> ListAliasesAsync(int characterId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
|
||||
@ -292,6 +292,7 @@ public class Program
|
||||
builder.Services.AddSingleton<ContextWorkspaceNotifications>();
|
||||
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterPanels>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextNames>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterEditing>();
|
||||
builder.Services.AddSingleton<IManuscriptScanPreviewStore, ManuscriptScanPreviewStore>();
|
||||
builder.Services.AddSingleton<IOnboardingStoryIntelligenceBatchStore, OnboardingStoryIntelligenceBatchStore>();
|
||||
|
||||
@ -15,7 +15,7 @@ public sealed class ContextCharacterEditForm
|
||||
public string Label{get;set;}="";public string CharacterName{get;set;}="";
|
||||
public IReadOnlyList<SelectListItem> 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<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"}};
|
||||
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<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});
|
||||
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);}
|
||||
|
||||
23
PlotLine/Services/Context/ContextNames.cs
Normal file
23
PlotLine/Services/Context/ContextNames.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.Context;
|
||||
public sealed record ContextNameEntry(Character Character,IReadOnlyList<CharacterAlias> Aliases,IReadOnlyList<string> SharedSpellings);
|
||||
public sealed record ContextNamePanel(int ProjectID,int BookID,bool CanEdit,IReadOnlyList<ContextNameEntry> Entries,PlotLine.ViewModels.NamesLibraryViewModel? Library);
|
||||
public sealed class ContextNames(ICharacterRepository characters,IProjectRepository projects,ICurrentUserService user,INameIntelligenceService names)
|
||||
{
|
||||
public async Task<ContextNamePanel> 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<ContextNameEntry> Compose(IReadOnlyList<Character> people,IReadOnlyList<CharacterAlias> 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();
|
||||
}
|
||||
}
|
||||
16
PlotLine/Sql/298_ContextCharacterAliases.sql
Normal file
16
PlotLine/Sql/298_ContextCharacterAliases.sql
Normal file
@ -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
|
||||
@ -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<StoryPointThread> RelevantThreads => Context==null?[]:WritingContextRelevance.Threads(Context);
|
||||
|
||||
@ -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<string>() }
|
||||
};
|
||||
}
|
||||
<link rel="stylesheet" href="~/css/context-workspace.css" asp-append-version="true" />
|
||||
|
||||
6
PlotLine/Views/Writing/_ContextNameSuggestions.cshtml
Normal file
6
PlotLine/Views/Writing/_ContextNameSuggestions.cshtml
Normal file
@ -0,0 +1,6 @@
|
||||
@model PlotLine.Services.Context.ContextNamePanel
|
||||
<div data-name-suggestion-results>
|
||||
<p class="small">Existing reference library, using the book’s recorded locale and era where available. Related forms are spelling hints, not proof of a shared identity.</p>
|
||||
@if(Model.Library?.Results.Any()==true){<ul>@foreach(var row in Model.Library.Results){<li><strong>@row.DisplayName</strong> @row.LocaleDisplayName @if(!string.IsNullOrWhiteSpace(row.RelatedForms)){<span>· Related forms: @row.RelatedForms</span>}@if(row.UsedCount>0){<small>· Already used (@row.UsedCount)</small>}</li>}</ul>}
|
||||
else{<p>No reference suggestions found. Try the full naming workspace for broader filters.</p>}
|
||||
</div>
|
||||
18
PlotLine/Views/Writing/_ContextNames.cshtml
Normal file
18
PlotLine/Views/Writing/_ContextNames.cshtml
Normal file
@ -0,0 +1,18 @@
|
||||
@model WritingContextDisplayViewModel
|
||||
@{var panel=Model.NamePanel;}
|
||||
@if(panel==null){<p>Names reference unavailable. Reopen this tool.</p>}else{
|
||||
<div data-context-names data-book="@panel.BookID">
|
||||
<label>Find an established name or alias <input type="search" data-name-filter class="form-control form-control-sm" autocomplete="off" /></label>
|
||||
<p class="small">Canonical names and aliases are separate identities only when the author records them that way. Shared spellings may be intentional; no identities are merged.</p>
|
||||
<div class="context-character-list">
|
||||
@foreach(var entry in panel.Entries){<details class="context-character-row" data-name-row data-filter-name="@(entry.Character.CharacterName+" "+string.Join(" ",entry.Aliases.Select(a=>a.Alias)))"><summary><strong>@entry.Character.CharacterName</strong>@if(entry.SharedSpellings.Any()){<span class="text-warning">Shared spelling · review</span>}</summary>
|
||||
<div class="context-character-detail"><button type="button" class="btn btn-link btn-sm" data-name-focus="@entry.Character.CharacterID">Focus character in My Windows</button>
|
||||
@if(entry.SharedSpellings.Any()){<p>Also recorded for another character: @string.Join(", ",entry.SharedSpellings). This can be a legitimate shared name.</p>}
|
||||
@if(panel.CanEdit){<button type="button" class="btn btn-outline-secondary btn-sm" data-context-edit="name" data-character-id="@entry.Character.CharacterID">Correct canonical name</button>}
|
||||
<ul>@foreach(var alias in entry.Aliases){<li>@alias.Alias <small>(alias / known variant)</small>@if(panel.CanEdit&&!string.Equals(alias.Alias,entry.Character.CharacterName,StringComparison.OrdinalIgnoreCase)){<button type="button" class="btn btn-link btn-sm" data-context-edit="alias:@alias.CharacterAliasID" data-character-id="@entry.Character.CharacterID">Correct or remove</button>}</li>}</ul>
|
||||
@if(panel.CanEdit){<button type="button" class="btn btn-outline-secondary btn-sm" data-context-edit="alias-add" data-character-id="@entry.Character.CharacterID">Add alias</button>}
|
||||
<a href="/Characters/Details/@entry.Character.CharacterID" target="_blank" rel="noopener">Full character editor</a></div></details>}
|
||||
</div><p data-name-no-matches hidden>No established name or alias matches this spelling.</p>
|
||||
<details class="mt-3"><summary>Name suggestions and related forms</summary><form data-name-suggestions-form><label>Reference lookup <input name="search" maxlength="100" class="form-control form-control-sm" /></label><button type="submit" class="btn btn-outline-primary btn-sm">Find suggestions</button></form><div data-name-suggestions><partial name="~/Views/Writing/_ContextNameSuggestions.cshtml" model="panel" /></div></details>
|
||||
<p data-context-interaction-status role="status"></p><a href="/Names?projectId=@panel.ProjectID&bookId=@panel.BookID" target="_blank" rel="noopener">Open full Names workspace</a>
|
||||
</div>}
|
||||
@ -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);}}
|
||||
};
|
||||
})();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user