From 065e70c255e4f4eb88cc7ed5522fc34a1bda3a95 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 26 Nov 2026 14:26:48 +0000 Subject: [PATCH] Build full-width Names workspace with deferred series-wide recorded identity details --- Docs/Codex/NamesWorkspace.md | 25 ++ PlotLine.Tests/Browser/names-workspace.cjs | 21 ++ .../NamesWorkspaceBrowserFixture.cs | 26 ++ PlotLine.Tests/NamesWorkspaceTests.cs | 20 ++ PlotLine.Tests/Program.cs | 3 +- PlotLine.Tests/Sql/NamesRecordedUsage.sql | 23 ++ PlotLine.Tests/ToolbarBrowserHost.cs | 1 + PlotLine/Controllers/NamesController.cs | 19 +- PlotLine/Models/NameIntelligenceModels.cs | 8 + PlotLine/Program.cs | 1 + PlotLine/Services/NameIntelligenceService.cs | 2 +- PlotLine/Services/NamesWorkspace.cs | 16 ++ PlotLine/Services/RibbonPresentation.cs | 2 + PlotLine/Sql/325_NamesRecordedUsage.sql | 155 ++++++++++++ PlotLine/ViewModels/NameDetailsViewModel.cs | 3 + PlotLine/Views/Names/Index.cshtml | 239 +----------------- PlotLine/Views/Shared/_NameDetails.cshtml | 20 ++ PlotLine/Views/Shared/_NamesResults.cshtml | 14 + PlotLine/Views/Shared/_NamesWorkspace.cshtml | 22 ++ PlotLine/wwwroot/css/names-workspace.css | 2 + PlotLine/wwwroot/js/names-workspace.js | 39 +++ 21 files changed, 424 insertions(+), 237 deletions(-) create mode 100644 Docs/Codex/NamesWorkspace.md create mode 100644 PlotLine.Tests/Browser/names-workspace.cjs create mode 100644 PlotLine.Tests/NamesWorkspaceBrowserFixture.cs create mode 100644 PlotLine.Tests/NamesWorkspaceTests.cs create mode 100644 PlotLine.Tests/Sql/NamesRecordedUsage.sql create mode 100644 PlotLine/Services/NamesWorkspace.cs create mode 100644 PlotLine/Sql/325_NamesRecordedUsage.sql create mode 100644 PlotLine/ViewModels/NameDetailsViewModel.cs create mode 100644 PlotLine/Views/Shared/_NameDetails.cshtml create mode 100644 PlotLine/Views/Shared/_NamesResults.cshtml create mode 100644 PlotLine/Views/Shared/_NamesWorkspace.cshtml create mode 100644 PlotLine/wwwroot/css/names-workspace.css create mode 100644 PlotLine/wwwroot/js/names-workspace.js diff --git a/Docs/Codex/NamesWorkspace.md b/Docs/Codex/NamesWorkspace.md new file mode 100644 index 00000000..0cf9aeb3 --- /dev/null +++ b/Docs/Codex/NamesWorkspace.md @@ -0,0 +1,25 @@ +# Names workspace + +## Recorded usage and catalogue audit + +The existing Name Intelligence catalogue stores classification, ambiguous-word flags, notes, locale/era profiles, gender weights, usage/confidence, provenance and related forms. Search ranks exact matches, then usage weight and display name, with bounded pagination. These filters and ordering remain in `GivenName_Search`. + +Previously usage decoration joined primary names and aliases through scene membership, offered Book/Project/Library scope and repeated summaries per appearance. Neither the old main page nor Context retrieved manuscript paragraphs: their usage actions retrieved recorded identity associations. Ordinary catalogue searches do not invoke AI. + +Migration 325 replaces scene-dependent usage with exact canonical comparison of recorded names and aliases in the authorised current series. It excludes an alias duplicating the same character's primary name. Different characters sharing a spelling remain independent associations. Character Type, species and story importance are returned from canonical records. No manuscript word occurrence establishes assignment. + +## Shared presentation + +`_NamesWorkspace`, `_NamesResults`, `_NameDetails`, `NamesWorkspace` and `names-workspace.js` implement the compact results and selected-name panel. Details use existing recognition metadata and the existing association repository only after selection. Catalogue searches retain pagination and never retrieve biographies or per-result occurrence lists. + +The main page opts into the existing full-width shell. The selected panel is sticky, with bounded scrolling; narrow containers show details with Back to Results. Main-page interaction state uses session storage scoped to series. Character actions open canonical records in another window, preserving the search. + +Usage icons come from the existing SVG library: primary name uses the shared Character Type icon (including Animal paw), aliases use `name-alias`, available uses `name-available`. Selected details distinguish confirmed associations from textual matches. Explicit paragraph occurrence lookup and AI verification are subsequent phases of this implementation. + +## Phase gates + +Phase 1: Character Type migration 324 and SQL regression passed on a disposable Development clone. Build and full executable harness passed. Actual Chromium and installed Chromium PWA fixture interactions passed at 10/100/500 characters, including the new Type bulk assignment/Undo and existing interactions. + +Phase 2: migration 325 and recorded-usage SQL regression passed on the disposable clone. Build and full executable harness passed. `Browser/names-workspace.cjs` passed normal and installed Chromium with compiled Razor, synthetic animal/alias details, all seven themes and viewport widths 390/768/1280/1920/2560/3840. Screenshots and measurements are in `/tmp/pd-names-workspace`. These are isolated fixture checks, not authenticated Development deployment acceptance. + +No migrations have been applied to Development and no deployment has occurred during these phase gates. diff --git a/PlotLine.Tests/Browser/names-workspace.cjs b/PlotLine.Tests/Browser/names-workspace.cjs new file mode 100644 index 00000000..c454b05b --- /dev/null +++ b/PlotLine.Tests/Browser/names-workspace.cjs @@ -0,0 +1,21 @@ +// Compiled main Names Razor and shared production scripts; disposable HTTP data only. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +(async()=>{ + const installed=process.argv.includes('--installed'),profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-names-pwa-')):null; + const persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1080}}):null; + const browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null,manifestId='http://127.0.0.1:5238/Projects'; + let page;try{ + if(installed){await persistent.pages()[0].goto('http://127.0.0.1:5238/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:'http://127.0.0.1:5238/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:'http://127.0.0.1:5238/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await browser.newPage({viewport:{width:1920,height:1080}}); + const errors=[],calls={search:0,details:0};page.on('pageerror',e=>errors.push(e.message)); + await page.route('**/Names/Results?*',async route=>{calls.search++;const u=new URL(route.request().url());await route.fulfill({response:await page.request.get('http://127.0.0.1:5238/names-workspace-fixture/results?'+u.searchParams)});}); + await page.route('**/Names/Details?*',async route=>{calls.details++;const u=new URL(route.request().url());await route.fulfill({response:await page.request.get('http://127.0.0.1:5238/names-workspace-fixture/details?'+u.searchParams)});}); + await page.route('**/SharedFocus/**',route=>route.fulfill({json:{success:true}})); + await page.goto('http://127.0.0.1:5238/names-workspace-fixture/page');await page.locator('[data-name-select]').first().waitFor();assert.equal(calls.details,0); + await page.locator('[name=Search]').fill('George');await page.locator('[data-names-search]').evaluate(f=>f.requestSubmit());await page.waitForFunction(()=>document.querySelector('[data-name-select]')?.dataset.nameSelect==='George 1'); + await page.locator('[data-name-select]').first().click();await page.locator('[data-name-details-fragment]').waitFor();assert.equal(await page.locator('.names-association').count(),2);assert((await page.locator('.names-details').innerText()).includes('Cat'));assert((await page.locator('.names-details').innerText()).includes('Known name / alias'));assert.equal(await page.locator('.names-association a').first().getAttribute('href'),'/Characters/Details/501'); + fs.mkdirSync('/tmp/pd-names-workspace',{recursive:true});const measurements=[]; + for(const width of [1280,1920,2560,3840,768,390]){await page.setViewportSize({width,height:1080});const m=await page.evaluate(()=>({width:innerWidth,overflow:document.documentElement.scrollWidth>innerWidth,workspace:document.querySelector('[data-names-workspace]').getBoundingClientRect().width,rowHeight:document.querySelector('.names-result').getBoundingClientRect().height,details:!!document.querySelector('[data-names-details]').getBoundingClientRect().width}));assert(!m.overflow);assert(m.rowHeight<=65);measurements.push(m);if(width===2560||width===390)await page.screenshot({path:`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-${width}.png`});if(width===390){await page.locator('[data-names-back]').click();assert(await page.locator('[data-names-details]').isHidden());await page.locator('[data-name-select]').first().click();await page.locator('[data-name-details-fragment]').waitFor();assert(await page.locator('[data-names-results-host]').isHidden());}} + await page.setViewportSize({width:1920,height:1080});for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);await page.screenshot({path:`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-${theme}.png`});} + await page.reload();await page.locator('[data-name-details-fragment]').waitFor();assert.equal(await page.locator('[name=Search]').inputValue(),'George');assert.equal(await page.locator('[data-name-select][aria-pressed=true]').count(),1);assert.deepEqual(errors,[]);fs.writeFileSync(`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-measurements.json`,JSON.stringify({measurements,calls},null,2));console.log('PASS Names compact results, deferred canonical details, animal/alias associations, navigation, state, themes, wide/narrow layouts',calls); + }finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();} +})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs b/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs new file mode 100644 index 00000000..7439d4b0 --- /dev/null +++ b/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using PlotLine.Models; +using PlotLine.ViewModels; +internal static class NamesWorkspaceBrowserFixture +{ + public static async Task Render(HttpContext context) + { + var part=context.Request.RouteValues["part"]?.ToString();var f=new NameSearchFilter{ProjectID=7}; + foreach(var property in typeof(NameSearchFilter).GetProperties()){if(!context.Request.Query.ContainsKey(property.Name))continue;var value=context.Request.Query[property.Name].ToString();var type=Nullable.GetUnderlyingType(property.PropertyType)??property.PropertyType;property.SetValue(f,string.IsNullOrWhiteSpace(value)&&type!=typeof(string)?null:Convert.ChangeType(value,type,System.Globalization.CultureInfo.InvariantCulture));} + var library=ContextNamesBrowserFixture.Panel(f).Library!; + var name=context.Request.Query["name"].ToString(); + object model=part=="details"?new NameDetailsViewModel(7,name,new(){Recognised=true,Name=new(){DisplayName=name,NameType="Canonical",Notes="Retained catalogue metadata"}},[new(){CharacterID=501,CharacterName="George",CharacterTypeCode="animal",Species="Cat",CharacterImportance=10,MatchType="Character"},new(){CharacterID=502,CharacterName="Hamish",CharacterTypeCode="animal",Species="Dog",CharacterImportance=6,MatchType="Alias"}]):library; + var path=part switch{"details"=>"/Views/Shared/_NameDetails.cshtml","results"=>"/Views/Shared/_NamesResults.cshtml",_=>"/Views/Names/Index.cshtml"}; + var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,path,part=="page"); + using var writer=new StringWriter();await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); + context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); + } +} diff --git a/PlotLine.Tests/NamesWorkspaceTests.cs b/PlotLine.Tests/NamesWorkspaceTests.cs new file mode 100644 index 00000000..6952db0e --- /dev/null +++ b/PlotLine.Tests/NamesWorkspaceTests.cs @@ -0,0 +1,20 @@ +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +internal static class NamesWorkspaceTests +{ + public static async Task Run() + { + void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Names workspace: "+message);} + bool allowed=true;int metadataCalls=0,associationCalls=0; + var metadata=NativeWorkflowTests.Proxy((method,args)=>{Check(method=="RecogniseAsync","selected metadata uses the existing recognition service");metadataCalls++;return Task.FromResult(new NameRecognitionResult());}); + var repository=NativeWorkflowTests.Proxy((method,args)=>{Check(method=="ListUsedDecorationsAsync","one existing association query per selected name");Check((int)args![1]! ==7&&args[2] is null&&(string)args[3]! =="GEORGE"&&(string)args[4]! =="Project","associations use exact normalisation across the authorised series, independent of book");associationCalls++;return Task.FromResult>([new(){CharacterID=1,CharacterName="George",CharacterTypeCode="animal",Species="Cat",MatchType="Character"},new(){CharacterID=2,CharacterName="Hamish",CharacterTypeCode="animal",Species="Dog",MatchType="Alias"}]);}); + var projects=NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(allowed?new(){ProjectID=7}:null)); + var service=new NamesWorkspace(metadata,repository,projects,NativeWorkflowTests.Proxy((_,_)=>4)); + Check(metadataCalls==0&&associationCalls==0,"constructing a workspace does not eagerly load details"); + var selected=await service.Details(7," George ",null,null,default); + Check(selected!.Associations.Count==2&&selected.Associations.All(x=>x.CharacterTypeCode=="animal")&&selected.Associations[1].MatchType=="Alias","multiple non-human primary and alias associations retain their canonical records"); + allowed=false;Check(await service.Details(8,"George",null,null,default) is null&&associationCalls==1,"foreign series access is rejected before metadata and association retrieval"); + allowed=true;Check(await service.Details(7,new string('a',121),null,null,default) is null&&associationCalls==1,"invalid name scope is rejected before retrieval"); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index c50c28e7..9e0fcb18 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -199,6 +199,7 @@ if(args.Contains("--focus-diagnostics")){SharedFocusDiagnosticsTests.Run();retur var tests = new (string Name, Action Test)[] { + ("Names workspace authorised selected details",()=>NamesWorkspaceTests.Run().GetAwaiter().GetResult()), ("Deployment health is loopback-only, database-backed and fails closed",DeploymentOperationsTests.Run), ("Character quick attributes and protected Undo", () => CharacterQuickAttributesTests.Run().GetAwaiter().GetResult()), ("Main Character workspace lazy reads and safe management",()=>CharacterWorkspaceTests.Run().GetAwaiter().GetResult()), @@ -5875,7 +5876,7 @@ static void NameIntelligenceLibraryDefaultsToAllLocales() { var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine"); var model = File.ReadAllText(Path.Combine(root, "Models/NameIntelligenceModels.cs")); - var view = File.ReadAllText(Path.Combine(root, "Views/Names/Index.cshtml")); + var view = File.ReadAllText(Path.Combine(root, "Views/Shared/_NamesWorkspace.cshtml")); var migration = File.ReadAllText(Path.Combine(root, "Sql/152_NameLibraryAllLocalesDefault.sql")); Assert(model.Contains("public string? LocaleCode { get; set; }", StringComparison.Ordinal), "Name library filter should not default LocaleCode to a specific country."); diff --git a/PlotLine.Tests/Sql/NamesRecordedUsage.sql b/PlotLine.Tests/Sql/NamesRecordedUsage.sql new file mode 100644 index 00000000..0a65c6be --- /dev/null +++ b/PlotLine.Tests/Sql/NamesRecordedUsage.sql @@ -0,0 +1,23 @@ +IF DB_NAME() NOT LIKE N'PlotDirector_Qualification[_]%' THROW 51000,'Disposable database required',1; +SET NOCOUNT ON; +BEGIN TRANSACTION; +DECLARE @p int=(SELECT TOP(1) a.ProjectID FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.IsActive=1 AND a.AccessRole=N'Owner' AND p.IsArchived=0); +DECLARE @u int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@p AND IsActive=1 AND AccessRole=N'Owner'); +INSERT dbo.Characters(ProjectID,CharacterName,CharacterTypeCode,Species,DefaultDescription,CharacterImportance) VALUES(@p,N'George','animal',N'Cat',N'Synthetic complete biography',10); +DECLARE @a int=SCOPE_IDENTITY(); +INSERT dbo.Characters(ProjectID,CharacterName,CharacterTypeCode,Species,CharacterImportance) VALUES(@p,N'Hamish','animal',N'Dog',6); +DECLARE @b int=SCOPE_IDENTITY(); +INSERT dbo.CharacterAliases(CharacterID,Alias) VALUES(@a,N'George'),(@b,N'George'); +CREATE TABLE #associations(MatchedName nvarchar(200),MatchType nvarchar(20),CharacterID int,CharacterName nvarchar(200),CharacterTypeCode varchar(24),Species nvarchar(200),CharacterImportance int,ThumbnailPath nvarchar(1000),ImagePath nvarchar(1000),ProjectID int,ProjectName nvarchar(200),Scope nvarchar(20)); +INSERT #associations EXEC dbo.GivenName_UsedDecorations @UserID=@u,@ProjectID=@p,@BookID=-1,@NormalisedName=N'GEORGE',@UsedScope=N'Book'; +IF (SELECT COUNT(*) FROM #associations WHERE CharacterID IN(@a,@b))<>2 THROW 51000,'Primary name alias duplication or scene dependence',1; +IF NOT EXISTS(SELECT 1 FROM #associations WHERE CharacterID=@a AND MatchType=N'Character' AND Species=N'Cat' AND CharacterTypeCode='animal') THROW 51000,'Animal primary name lost',1; +IF NOT EXISTS(SELECT 1 FROM #associations WHERE CharacterID=@b AND MatchType=N'Alias' AND Species=N'Dog') THROW 51000,'Animal alias lost',1; +TRUNCATE TABLE #associations; +INSERT #associations EXEC dbo.GivenName_UsedDecorations @UserID=@u,@ProjectID=@p,@NormalisedName=N'GEORG'; +IF EXISTS(SELECT 1 FROM #associations WHERE CharacterID IN(@a,@b)) THROW 51000,'Substring treated as recorded usage',1; +TRUNCATE TABLE #associations; +INSERT #associations EXEC dbo.GivenName_UsedDecorations @UserID=-1,@ProjectID=@p,@NormalisedName=N'GEORGE'; +IF EXISTS(SELECT 1 FROM #associations) THROW 51000,'Unauthorised names disclosed',1; +ROLLBACK; +PRINT N'PASS Recorded names: animals, multiple associations, primary/alias distinction, no scene requirement, exact matching and authorisation'; diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 0f557036..3683e530 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -454,6 +454,7 @@ internal static class ToolbarBrowserHost app.MapGet("/context-lenses-fixture",(HttpContext context)=>Results.Json(ContextRelationshipBrowserFixture.Graph(context))); app.MapGet("/context-lenses-lookup-fixture",()=>Results.Json(new[]{new{id=7,name="An established relative with a deliberately long name 7",archived=false}})); app.MapGet("/context-names-fixture/{part}",ContextNamesBrowserFixture.Render); + app.MapGet("/names-workspace-fixture/{part}",NamesWorkspaceBrowserFixture.Render); app.MapGet("/context-tab-fixture/{tool}",async context=> { var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22; diff --git a/PlotLine/Controllers/NamesController.cs b/PlotLine/Controllers/NamesController.cs index 37440625..1083c4f9 100644 --- a/PlotLine/Controllers/NamesController.cs +++ b/PlotLine/Controllers/NamesController.cs @@ -6,7 +6,7 @@ using PlotLine.Services; namespace PlotLine.Controllers; [Authorize] -public sealed class NamesController(INameIntelligenceService names) : Controller +public sealed class NamesController(INameIntelligenceService names, NamesWorkspace workspace) : Controller { public async Task Index([FromQuery] NameSearchFilter filter, CancellationToken cancellationToken) { @@ -15,8 +15,23 @@ public sealed class NamesController(INameIntelligenceService names) : Controller return BadRequest("ProjectID is required."); } - if(!Request.Query.ContainsKey("UsedScope")&&filter.BookID.HasValue)filter.UsedScope="Book"; + filter.UsedScope="Project"; var model = await names.BuildLibraryAsync(filter, cancellationToken); return model is null ? NotFound() : View(model); } + + [HttpGet, ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] + public async Task Results([FromQuery] NameSearchFilter filter,CancellationToken cancellationToken) + { + if(!ModelState.IsValid || filter.Search?.Length>120) return BadRequest(); + var model=await names.BuildLibraryAsync(filter,cancellationToken); + return model is null ? NotFound() : PartialView("_NamesResults",model); + } + [HttpGet, ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] + public async Task Details(int projectId,string name,string? localeCode,int? birthYear,CancellationToken cancellationToken) + { + if(!ModelState.IsValid || string.IsNullOrWhiteSpace(name) || name.Length>120) return BadRequest(); + var model=await workspace.Details(projectId,name,localeCode,birthYear,cancellationToken); + return model is null ? NotFound() : PartialView("_NameDetails",model); + } } diff --git a/PlotLine/Models/NameIntelligenceModels.cs b/PlotLine/Models/NameIntelligenceModels.cs index f0296029..7ad1e24d 100644 --- a/PlotLine/Models/NameIntelligenceModels.cs +++ b/PlotLine/Models/NameIntelligenceModels.cs @@ -70,6 +70,11 @@ public sealed class NameRelationshipReference public sealed class NameUsageDecoration { + public string CharacterTypeCode { get; set; } = "unclassified"; + public string? Species { get; set; } + public int? CharacterImportance { get; set; } + public string? ThumbnailPath { get; set; } + public string? ImagePath { get; set; } public string MatchedName { get; set; } = string.Empty; public string MatchType { get; set; } = string.Empty; public int CharacterID { get; set; } @@ -111,6 +116,9 @@ public sealed class NameSearchFilter public sealed class NameSearchResult { + public int PrimaryCount { get; set; } + public int AliasCount { get; set; } + public bool HasAnimalAssociation { get; set; } public int GivenNameID { get; set; } public string GivenNameKey { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index d7df8c03..23fd287a 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -362,6 +362,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/NameIntelligenceService.cs b/PlotLine/Services/NameIntelligenceService.cs index 948a89a3..6e933512 100644 --- a/PlotLine/Services/NameIntelligenceService.cs +++ b/PlotLine/Services/NameIntelligenceService.cs @@ -109,7 +109,7 @@ public sealed class NameIntelligenceService( filter.Page = Math.Max(1, filter.Page); filter.PageSize = Math.Clamp(filter.PageSize, 1, 100); - filter.UsedScope = string.IsNullOrWhiteSpace(filter.UsedScope) ? "Project" : filter.UsedScope.Trim(); + filter.UsedScope = "Project"; if (!string.IsNullOrWhiteSpace(filter.GenderPreference) && !filter.GenderThreshold.HasValue) { filter.GenderThreshold = string.Equals(filter.GenderPreference, "Mixed", StringComparison.OrdinalIgnoreCase) diff --git a/PlotLine/Services/NamesWorkspace.cs b/PlotLine/Services/NamesWorkspace.cs new file mode 100644 index 00000000..16823e5d --- /dev/null +++ b/PlotLine/Services/NamesWorkspace.cs @@ -0,0 +1,16 @@ +using PlotLine.Data; +using PlotLine.ViewModels; +namespace PlotLine.Services; +// Shared selected-name retrieval for the directory and Context. Searches never load this data per row. +public sealed class NamesWorkspace(INameIntelligenceService names, INameIntelligenceRepository reference, IProjectRepository projects, ICurrentUserService user) +{ + public async Task Details(int projectId,string name,string? locale,int? birthYear,CancellationToken cancellationToken) + { + if(user.UserId is not int author || await projects.GetForUserAsync(projectId,author) is null) return null; + var normalised=NameIntelligenceService.NormaliseName(name); + if(normalised.Length is 0 or >120) return null; + var metadata=await names.RecogniseAsync(name,locale,birthYear,cancellationToken); + var associations=await reference.ListUsedDecorationsAsync(author,projectId,null,normalised,"Project",cancellationToken); + return new(projectId,name.Trim(),metadata,associations); + } +} diff --git a/PlotLine/Services/RibbonPresentation.cs b/PlotLine/Services/RibbonPresentation.cs index 8372de4b..daf11349 100644 --- a/PlotLine/Services/RibbonPresentation.cs +++ b/PlotLine/Services/RibbonPresentation.cs @@ -45,6 +45,8 @@ public static class RibbonPresentation return null; } public static IReadOnlyList AdditionalIcons { get; } = [ + new("name-available", "M22 12a10 10 0 1 1-5-8 M7 11l4 4 11-12", "characters"), + new("name-alias", "M3 3h18v18H3z M9 7a3 3 0 1 0 0 6 3 3 0 0 0 0-6 M5 19v-2a4 4 0 0 1 8 0v2 M16 8h3 M16 12h3 M16 16h3", "characters"), new("attribute-paw", "M8 15c-5 3-2 8 1 6l3-1 3 1c3 2 6-3 1-6l-4-3z M6 5a2 3 0 1 0 0 6 2 3 0 0 0 0-6 M11 2a2 3 0 1 0 0 6 2 3 0 0 0 0-6 M17 3a2 3 0 1 0 0 6 2 3 0 0 0 0-6 M21 8a2 3 0 1 0 0 6 2 3 0 0 0 0-6", "characters"), new("attribute-sparkles", "M12 2l3 7 7 3-7 3-3 7-3-7-7-3 7-3z M21 2v4 M19 4h4 M3 19v4 M1 21h4", "characters"), new("attribute-robot", "M4 7h16v14H4z M12 3v4 M10 3h4 M8 11h1 M15 11h1 M8 17h8 M1 11v6 M23 11v6", "characters"), diff --git a/PlotLine/Sql/325_NamesRecordedUsage.sql b/PlotLine/Sql/325_NamesRecordedUsage.sql new file mode 100644 index 00000000..ceb29a5c --- /dev/null +++ b/PlotLine/Sql/325_NamesRecordedUsage.sql @@ -0,0 +1,155 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- Recorded primary names and aliases across the current series; catalogue profiles and ordering are unchanged. +CREATE OR ALTER PROCEDURE dbo.GivenName_Search + @UserID int, + @ProjectID int, + @BookID int = NULL, + @Search nvarchar(120) = NULL, + @LocaleCode nvarchar(16) = NULL, + @BirthYear int = NULL, + @GenderPreference nvarchar(12) = NULL, + @GenderThreshold decimal(9,4) = NULL, + @NameType nvarchar(40) = NULL, + @MinimumUsage decimal(9,4) = NULL, + @UsedScope nvarchar(20) = N'Project', + @UsedOnly bit = NULL, + @Page int = 1, + @PageSize int = 25 +AS +BEGIN + SET NOCOUNT ON; + + IF NOT EXISTS (SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID = @ProjectID AND UserID = @UserID AND IsActive = 1) + BEGIN + SELECT TOP (0) CAST(NULL AS int) AS GivenNameID; + RETURN; + END; + + IF @Page < 1 SET @Page = 1; + IF @PageSize < 1 SET @PageSize = 25; + IF @PageSize > 100 SET @PageSize = 100; + + DECLARE @NameLocaleID int = NULL; + IF @LocaleCode IS NOT NULL + BEGIN + SELECT TOP (1) @NameLocaleID = NameLocaleID FROM dbo.NameLocales WHERE LocaleCode = @LocaleCode AND IsActive = 1; + END; + + ;WITH UsageChoice AS + ( + SELECT + u.*, + l.LocaleCode, + l.DisplayName AS LocaleDisplayName, + ROW_NUMBER() OVER (PARTITION BY u.GivenNameID ORDER BY + CASE WHEN @BirthYear IS NOT NULL AND @BirthYear BETWEEN u.BirthYearFrom AND u.BirthYearTo THEN 0 ELSE 1 END, + CASE WHEN @BirthYear IS NULL THEN ABS(1960 - ((u.BirthYearFrom + u.BirthYearTo) / 2)) ELSE ABS(@BirthYear - ((u.BirthYearFrom + u.BirthYearTo) / 2)) END, + u.UsageWeight DESC) AS rn + FROM dbo.NameUsages u + INNER JOIN dbo.NameLocales l ON l.NameLocaleID = u.NameLocaleID + WHERE u.IsActive = 1 + AND (@NameLocaleID IS NULL OR u.NameLocaleID = @NameLocaleID) + ), + Used AS + ( + SELECT g.GivenNameID, COUNT(DISTINCT c.CharacterID) AS UsedCount, + SUM(CASE WHEN c.MatchType=N'Character' THEN 1 ELSE 0 END) AS PrimaryCount, + SUM(CASE WHEN c.MatchType=N'Alias' THEN 1 ELSE 0 END) AS AliasCount, + MAX(CASE WHEN c.CharacterTypeCode='animal' THEN 1 ELSE 0 END) AS HasAnimalAssociation, + CAST(N'' AS nvarchar(max)) AS UsedSummary + FROM dbo.GivenNames g + INNER JOIN + ( + SELECT c.CharacterID, c.ProjectID, c.CharacterName AS MatchedName, c.CharacterTypeCode, N'Character' AS MatchType + FROM dbo.Characters c WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID + UNION + SELECT c.CharacterID, c.ProjectID, ca.Alias, c.CharacterTypeCode, N'Alias' + FROM dbo.CharacterAliases ca JOIN dbo.Characters c ON c.CharacterID=ca.CharacterID + WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID + AND UPPER(LTRIM(RTRIM(ca.Alias))) COLLATE Latin1_General_100_CI_AI_SC <> UPPER(LTRIM(RTRIM(c.CharacterName))) + ) c ON UPPER(LTRIM(RTRIM(c.MatchedName))) = g.NormalisedName COLLATE Latin1_General_100_CI_AI_SC + GROUP BY g.GivenNameID + ), + Related AS + ( + SELECT x.GivenNameID, + STRING_AGG(CONVERT(nvarchar(max), x.DisplayName), N', ') AS RelatedForms + FROM + ( + SELECT r.FromGivenNameID AS GivenNameID, t.DisplayName + FROM dbo.NameRelationships r + INNER JOIN dbo.GivenNames t ON t.GivenNameID = r.ToGivenNameID + WHERE r.IsActive = 1 + UNION + SELECT r.ToGivenNameID AS GivenNameID, f.DisplayName + FROM dbo.NameRelationships r + INNER JOIN dbo.GivenNames f ON f.GivenNameID = r.FromGivenNameID + WHERE r.IsActive = 1 AND r.IsBidirectional = 1 + ) x + GROUP BY x.GivenNameID + ), + Filtered AS + ( + SELECT + g.GivenNameID, g.GivenNameKey, g.DisplayName, g.NormalisedName, g.NameType, g.IsWordAmbiguous, + u.MaleWeight, u.FemaleWeight, u.UsageWeight, u.Confidence, u.BirthYearFrom, u.BirthYearTo, u.LocaleCode, u.LocaleDisplayName, u.SourceType, + rel.RelatedForms, + COALESCE(used.UsedSummary, N'') AS UsedSummary, + COALESCE(used.UsedCount, 0) AS UsedCount, + COALESCE(used.PrimaryCount,0) AS PrimaryCount, COALESCE(used.AliasCount,0) AS AliasCount, COALESCE(used.HasAnimalAssociation,0) AS HasAnimalAssociation, + COUNT(1) OVER() AS TotalRows + FROM dbo.GivenNames g + LEFT JOIN UsageChoice u ON u.GivenNameID = g.GivenNameID AND u.rn = 1 + LEFT JOIN Used used ON used.GivenNameID = g.GivenNameID + LEFT JOIN Related rel ON rel.GivenNameID = g.GivenNameID + WHERE g.IsActive = 1 + AND (@Search IS NULL OR g.NormalisedName LIKE UPPER(LTRIM(RTRIM(@Search))) + N'%' COLLATE Latin1_General_100_CI_AI_SC OR g.DisplayName LIKE @Search + N'%') + AND (@NameType IS NULL OR g.NameType = @NameType) + AND (@MinimumUsage IS NULL OR u.UsageWeight >= @MinimumUsage) + AND (@UsedOnly IS NULL OR (@UsedOnly = 1 AND COALESCE(used.UsedCount, 0) > 0) OR (@UsedOnly = 0 AND COALESCE(used.UsedCount, 0) = 0)) + AND ( + @GenderPreference IS NULL + OR @GenderThreshold IS NULL + OR (@GenderPreference = N'Female' AND u.FemaleWeight >= @GenderThreshold) + OR (@GenderPreference = N'Male' AND u.MaleWeight >= @GenderThreshold) + OR (@GenderPreference = N'Mixed' AND u.MaleWeight >= (1 - @GenderThreshold) AND u.FemaleWeight >= (1 - @GenderThreshold)) + ) + ) + SELECT * + FROM Filtered + ORDER BY + CASE WHEN @Search IS NOT NULL AND NormalisedName = UPPER(LTRIM(RTRIM(@Search))) COLLATE Latin1_General_100_CI_AI_SC THEN 0 ELSE 1 END, + UsageWeight DESC, + DisplayName + OFFSET (@Page - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY; +END; +GO + +-- Usage is recorded identity within the current series, independent of scene membership. +CREATE OR ALTER PROCEDURE dbo.GivenName_UsedDecorations + @UserID int, @ProjectID int, @BookID int=NULL, @NormalisedName nvarchar(120), + @UsedScope nvarchar(20)=N'Project', @Take int=100 +AS +BEGIN + SET NOCOUNT ON; + IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1) RETURN; + SELECT DISTINCT rows.MatchedName,rows.MatchType,c.CharacterID,c.CharacterName,c.CharacterTypeCode,c.Species, + c.CharacterImportance,c.ThumbnailPath,c.ImagePath,p.ProjectID,p.ProjectName,N'Project' AS Scope + FROM ( + SELECT c.CharacterID,c.CharacterName AS MatchedName,N'Character' AS MatchType + FROM dbo.Characters c WHERE c.ProjectID=@ProjectID AND c.IsArchived=0 + UNION + SELECT c.CharacterID,ca.Alias,N'Alias' + FROM dbo.Characters c JOIN dbo.CharacterAliases ca ON ca.CharacterID=c.CharacterID + WHERE c.ProjectID=@ProjectID AND c.IsArchived=0 + AND UPPER(LTRIM(RTRIM(ca.Alias))) COLLATE Latin1_General_100_CI_AI_SC <> UPPER(LTRIM(RTRIM(c.CharacterName))) + ) rows + JOIN dbo.Characters c ON c.CharacterID=rows.CharacterID + JOIN dbo.Projects p ON p.ProjectID=c.ProjectID + WHERE UPPER(LTRIM(RTRIM(rows.MatchedName)))=@NormalisedName COLLATE Latin1_General_100_CI_AI_SC + ORDER BY c.CharacterName,c.CharacterID,rows.MatchType; +END; +GO diff --git a/PlotLine/ViewModels/NameDetailsViewModel.cs b/PlotLine/ViewModels/NameDetailsViewModel.cs new file mode 100644 index 00000000..79180647 --- /dev/null +++ b/PlotLine/ViewModels/NameDetailsViewModel.cs @@ -0,0 +1,3 @@ +using PlotLine.Models; +namespace PlotLine.ViewModels; +public sealed record NameDetailsViewModel(int ProjectID, string Name, NameRecognitionResult Reference, IReadOnlyList Associations); diff --git a/PlotLine/Views/Names/Index.cshtml b/PlotLine/Views/Names/Index.cshtml index c0872b3f..22f4d74f 100644 --- a/PlotLine/Views/Names/Index.cshtml +++ b/PlotLine/Views/Names/Index.cshtml @@ -1,234 +1,7 @@ @model NamesLibraryViewModel -@{ - ViewData["Title"] = $"Names Library - {Model.Project.ProjectName}"; - ViewData["ProjectSection"] = "Names"; - var filter = Model.Filter; - var previousPage = Math.Max(1, filter.Page - 1); - var nextPage = Math.Min(Model.TotalPages, filter.Page + 1); - var genderPreset = (filter.GenderPreference, filter.GenderThreshold) switch - { - ("Female", >= 0.9m) => "female-very-strong", - ("Female", >= 0.7m) => "female-strong", - ("Female", _) => "female-mostly", - ("Male", >= 0.9m) => "male-very-strong", - ("Male", >= 0.7m) => "male-strong", - ("Male", _) => "male-mostly", - ("Mixed", _) => "mixed-balanced", - _ => string.Empty - }; - - string GenderLabel(NameSearchResult row) - { - if (!row.FemaleWeight.HasValue || !row.MaleWeight.HasValue) - { - return "No profile"; - } - - if (row.FemaleWeight >= 0.7m) - { - return "strong female prior"; - } - - if (row.MaleWeight >= 0.7m) - { - return "strong male prior"; - } - - return "mixed prior"; - } - - string EraLabel(NameSearchResult row) - => row.BirthYearFrom.HasValue && row.BirthYearTo.HasValue - ? $"established for {row.BirthYearFrom}-{row.BirthYearTo}" - : "no era profile"; -} - - - - - -
-
-

Characters

-

Names Library

-

Search established given-name forms with era, locale and current-project usage context.

-
-
- - - -
-
-

Results

- @Model.TotalRows.ToString("N0") names -
- - @if (!Model.Results.Any()) - { -

No matching names found.

- } - else - { -
- - - - - - - - - - - @foreach (var row in Model.Results) - { - - - - - - - } - -
NameProfileRelated formsCurrent use
- @row.DisplayName -
@row.NameType@if (row.IsWordAmbiguous){ · ambiguous word}
-
- @GenderLabel(row); @EraLabel(row) -
@row.LocaleDisplayName · usage @row.UsageWeight?.ToString("0.000") · confidence @row.Confidence?.ToString("0.000")
-
@(string.IsNullOrWhiteSpace(row.RelatedForms) ? "None listed" : row.RelatedForms) - @if (row.UsedCount > 0) - { - Already used -
@row.UsedSummary
- } - else - { - Unused here - } -
-
- -
- Previous - Page @filter.Page of @Model.TotalPages - Next -
- } -
- -@section Scripts { - -} +@{ViewData["Title"]="Names";ViewData["ProjectSection"]="Names";ViewData["ShellClass"]="pd-workspace-full-width";ViewData["DesktopLayout"]="management";} + + +

Names

Explore catalogue names and recorded names and aliases across this series.

+ +@section Scripts {} diff --git a/PlotLine/Views/Shared/_NameDetails.cshtml b/PlotLine/Views/Shared/_NameDetails.cshtml new file mode 100644 index 00000000..a494013c --- /dev/null +++ b/PlotLine/Views/Shared/_NameDetails.cshtml @@ -0,0 +1,20 @@ +@model NameDetailsViewModel +@{var reference=Model.Reference;} +
+ +

@Model.Name

+

@(Model.Associations.Count>0?"Already in use in this series.":"Available: no matching recorded character name or alias in this series.")

+@if(reference.Name is {} name){ + +}else{

This spelling has no catalogue profile. Recorded character associations are still shown.

} +@foreach(var association in Model.Associations){ +var type=CharacterTypes.Definition(association.CharacterTypeCode); +

@association.CharacterName

@(association.MatchType=="Character"?"Primary name":"Known name / alias")
+

@type.Label @if(!string.IsNullOrWhiteSpace(association.Species)){· @association.Species} · @(CharacterQuickAttributes.Definitions([]).Single(g=>g.Id=="importance").Values.FirstOrDefault(v=>v.Value==(association.CharacterImportance?.ToString()??""))?.Label??"Unrecorded importance")

+
+} +

Availability reflects recorded names and aliases. Textual matches are separate from confirmed character appearances.

+
diff --git a/PlotLine/Views/Shared/_NamesResults.cshtml b/PlotLine/Views/Shared/_NamesResults.cshtml new file mode 100644 index 00000000..be9a5927 --- /dev/null +++ b/PlotLine/Views/Shared/_NamesResults.cshtml @@ -0,0 +1,14 @@ +@model NamesLibraryViewModel +
+ +
@Model.TotalRows.ToString("N0") namesPage @Model.Filter.Page of @Model.TotalPages
+@if(!Model.Results.Any()){

No matching catalogue names. You can inspect the exact spelling using the search field.

} +@foreach(var row in Model.Results){ +var icon=row.HasAnimalAssociation?CharacterTypes.Definition("animal").Icon:row.PrimaryCount>0?"attribute-person":row.AliasCount>0?"name-alias":"name-available"; + +} +
+
diff --git a/PlotLine/Views/Shared/_NamesWorkspace.cshtml b/PlotLine/Views/Shared/_NamesWorkspace.cshtml new file mode 100644 index 00000000..c1888eb7 --- /dev/null +++ b/PlotLine/Views/Shared/_NamesWorkspace.cshtml @@ -0,0 +1,22 @@ +@model NamesLibraryViewModel +@{var f=Model.Filter;} + +
+ +

+
+
diff --git a/PlotLine/wwwroot/css/names-workspace.css b/PlotLine/wwwroot/css/names-workspace.css new file mode 100644 index 00000000..7a1b516b --- /dev/null +++ b/PlotLine/wwwroot/css/names-workspace.css @@ -0,0 +1,2 @@ +.names-workspace{container-type:inline-size;min-width:0}.names-search{padding:1rem;border:1px solid var(--pd-border-color,var(--bs-border-color));border-radius:.5rem;background:var(--pd-surface,var(--bs-body-bg))}.names-search-primary,.names-search-more{display:flex;gap:.75rem;align-items:end;flex-wrap:wrap}.names-search-primary>label:first-child{flex:1;min-width:12rem}.names-search label{display:grid;gap:.25rem;font-size:.9rem}.names-search details{margin-top:.65rem}.names-search-more{padding-top:.75rem}.names-search-more>label{flex:1 1 10rem}.names-workspace-columns{display:grid;grid-template-columns:minmax(0,1fr) minmax(20rem,.8fr);gap:1rem;align-items:start}.names-results-host,.names-details{min-width:0}.names-details{position:sticky;top:calc(var(--pd-sticky-height,0px) + 1rem);max-height:calc(100dvh - var(--pd-sticky-height,0px) - 2rem);overflow-y:auto;padding:1rem;border:1px solid var(--pd-border-color,var(--bs-border-color));border-radius:.5rem;background:var(--pd-surface,var(--bs-body-bg))}.names-result-heading{display:flex;gap:.75rem;justify-content:space-between;align-items:center;margin-bottom:.5rem}.names-result{display:grid;grid-template-columns:minmax(7rem,1fr) minmax(7rem,1fr) auto;gap:.5rem;align-items:center;width:100%;min-height:3rem;padding:.5rem .75rem;text-align:left;border:0;border-bottom:1px solid var(--pd-border-color,var(--bs-border-color));background:transparent;color:inherit}.names-result:hover,.names-result[aria-pressed=true]{background:var(--bs-tertiary-bg);outline:1px solid var(--bs-primary)}.names-result-profile,.names-result-usage{font-size:.85rem}.names-result-usage{display:flex;gap:.35rem;align-items:center}.names-result svg,.names-type-icon{width:1.1rem;height:1.1rem;fill:none;stroke:currentColor;stroke-width:1.6;vertical-align:middle}.names-metadata{display:grid;grid-template-columns:auto 1fr;gap:.35rem .75rem;font-size:.9rem}.names-metadata dd{margin:0;overflow-wrap:anywhere}.names-association{padding:.75rem 0;border-top:1px solid var(--pd-border-color,var(--bs-border-color))}.names-association h3{font-size:1rem;margin:0}.names-pages{margin-top:.75rem}.names-back{display:none}.names-workspace :focus-visible{outline:2px solid var(--bs-primary);outline-offset:2px} +@container(max-width:760px){.names-workspace-columns{grid-template-columns:minmax(0,1fr)}.names-details{display:none;position:static;max-height:none;overflow:visible}.names-workspace[data-details-open] .names-results-host{display:none}.names-workspace[data-details-open] .names-details{display:block}.names-back{display:inline-block}.names-result{grid-template-columns:minmax(5rem,1fr) auto}.names-result-profile{display:none}.names-search-primary>label{flex:1 1 10rem}} diff --git a/PlotLine/wwwroot/js/names-workspace.js b/PlotLine/wwwroot/js/names-workspace.js new file mode 100644 index 00000000..0ff50373 --- /dev/null +++ b/PlotLine/wwwroot/js/names-workspace.js @@ -0,0 +1,39 @@ +(() => { + 'use strict'; + window.PlotDirectorNames={mount(root,{state:prior,onState=()=>{}}={}){ + const lifetime=new AbortController(),form=root.querySelector('[data-names-search]'),results=root.querySelector('[data-names-results-host]'),details=root.querySelector('[data-names-details]'),status=root.querySelector('[data-names-status]'); + let selected='',page=Number(form.elements.Page.value)||1,searchRequest,detailRequest,searchEpoch=0,detailEpoch=0; + const listen=(node,event,fn)=>node.addEventListener(event,fn,{signal:lifetime.signal}); + function snapshot(){return {fields:[...new FormData(form)],selected,page,expanded:root.querySelector('[data-names-filters]').open,scroll:window.scrollY,detailsScroll:details.scrollTop,detailsOpen:root.hasAttribute('data-details-open')};} + function save(){onState(snapshot());} + function apply(fields){for(const [key,value] of fields){const input=form.elements.namedItem(key);if(input)input.value=value??'';}const gender=root.querySelector('[data-names-gender]');gender.value=form.elements.GenderPreference.value?form.elements.GenderPreference.value+':'+form.elements.GenderThreshold.value:'';} + async function fragment(url,signal,selector){const response=await fetch(url,{cache:'no-store',signal,headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error('The lookup is unavailable. Your search is retained; check access and retry.');const doc=new DOMParser().parseFromString(await response.text(),'text/html'),node=doc.querySelector(selector);if(!node)throw Error('The lookup returned an unavailable response.');return node;} + async function select(name,{restore=false}={}){ + const epoch=++detailEpoch;detailRequest?.abort();detailRequest=new AbortController();selected=name;root.setAttribute('data-details-open','');for(const row of results.querySelectorAll('[data-name-select]'))row.setAttribute('aria-pressed',String(row.dataset.nameSelect===name)); + details.setAttribute('aria-busy','true');status.textContent='Loading name details…';save(); + const parameters=new URLSearchParams({ProjectID:root.dataset.project,name,localeCode:form.elements.LocaleCode.value,birthYear:form.elements.BirthYear.value}); + try{const node=await fragment(root.dataset.detailsUrl+'?'+parameters,AbortSignal.any([lifetime.signal,detailRequest.signal]),'[data-name-details-fragment]');if(epoch!==detailEpoch)return;details.replaceChildren(node);status.textContent='';if(restore&&prior)details.scrollTop=prior.detailsScroll||0;else details.scrollTop=0;save();} + catch(error){if(error.name!=='AbortError'&&epoch===detailEpoch)status.textContent=error.message;}finally{if(epoch===detailEpoch)details.removeAttribute('aria-busy');} + } + async function search(next=1,{restore=false}={}){ + const epoch=++searchEpoch;searchRequest?.abort();searchRequest=new AbortController();form.elements.Page.value=next;status.textContent='Searching names…';results.setAttribute('aria-busy','true'); + try{const node=await fragment(root.dataset.searchUrl+'?'+new URLSearchParams(new FormData(form)),AbortSignal.any([lifetime.signal,searchRequest.signal]),'[data-names-results]');if(epoch!==searchEpoch)return;results.replaceChildren(node);page=Number(node.dataset.page);const applied=JSON.parse(node.querySelector('[data-names-applied]').textContent);apply(Object.entries(applied));status.textContent='';for(const row of results.querySelectorAll('[data-name-select]'))row.setAttribute('aria-pressed',String(row.dataset.nameSelect===selected));if(restore&&prior)window.scrollTo({top:prior.scroll||0,behavior:'instant'});save();} + catch(error){if(error.name!=='AbortError'&&epoch===searchEpoch)status.textContent=error.message;}finally{if(epoch===searchEpoch)results.removeAttribute('aria-busy');} + } + listen(form,'submit',event=>{event.preventDefault();void search();}); + listen(root.querySelector('[data-names-gender]'),'change',event=>{const [gender,threshold]=event.target.value.split(':');form.elements.GenderPreference.value=gender||'';form.elements.GenderThreshold.value=threshold||'';}); + listen(root,'click',async event=>{ + const button=event.target.closest('button');if(!button)return; + if(button.hasAttribute('data-name-select'))void select(button.dataset.nameSelect); + else if(button.hasAttribute('data-name-page'))void search(Number(button.dataset.namePage)); + else if(button.hasAttribute('data-names-inspect')){const name=form.elements.Search.value.trim();if(name)void select(name);else status.textContent='Enter an exact name spelling first.';} + else if(button.hasAttribute('data-names-back')){root.removeAttribute('data-details-open');save();results.querySelector('[aria-pressed=true]')?.focus();} + else if(button.hasAttribute('data-name-copy'))try{await navigator.clipboard.writeText(button.dataset.nameCopy);window.PlotDirector?.toast?.success('Name copied.');}catch{window.PlotDirector?.toast?.error('Copy is unavailable. Select and copy the name text.');} + }); + listen(form,'change',save);listen(details,'scroll',save);listen(window,'pagehide',save); + if(prior){apply(prior.fields||[]);root.querySelector('[data-names-filters]').open=Boolean(prior.expanded);void search(prior.page||1,{restore:true});if(prior.selected)void select(prior.selected,{restore:true});if(!prior.detailsOpen)root.removeAttribute('data-details-open');} + return {state:snapshot,refresh(){void search(page);if(selected)void select(selected);},dispose(){save();lifetime.abort();searchRequest?.abort();detailRequest?.abort();}}; + }}; + function main(){const root=document.querySelector('body:not(.context-window) [data-names-workspace]');if(!root||root.closest('[data-context-pane]'))return;const key='pd.names.workspace.v1:'+root.dataset.project;let state;try{state=JSON.parse(sessionStorage.getItem(key)||'null');}catch{}const workspace=window.PlotDirectorNames.mount(root,{state,onState:value=>{try{sessionStorage.setItem(key,JSON.stringify(value));}catch{}}});let connection,timer;function wire(c){if(connection||!c)return;connection=c;c.on('ContextInvalidated',hint=>{if((!hint.projectId||Number(hint.projectId)===Number(root.dataset.project))&&(!hint.kind||hint.kind==='characters')){clearTimeout(timer);timer=setTimeout(()=>workspace.refresh(),150);}});c.onreconnected(()=>workspace.refresh());}document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));wire(window.PlotDirectorPresenceConnection);} + if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',main,{once:true});else main(); +})();