diff --git a/Docs/Codex/NamesWorkspace.md b/Docs/Codex/NamesWorkspace.md index 0cf9aeb3..c536ffd5 100644 --- a/Docs/Codex/NamesWorkspace.md +++ b/Docs/Codex/NamesWorkspace.md @@ -23,3 +23,7 @@ Phase 1: Character Type migration 324 and SQL regression passed on a disposable 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. + +## Context reuse + +The pre-existing Names tab now mounts the same shared workspace. Its adapter only supplies authorised Context endpoints and retains component state keyed by pane and book. Separate windows have separate JavaScript state. Book-scoped Context refresh policy ignores paragraph/scene movement; character invalidation continues through the workspace's established connection and remount lifecycle. Character links open canonical records elsewhere. No new connections or manuscript-focus commands are introduced. diff --git a/PlotLine.Tests/Browser/context-names.cjs b/PlotLine.Tests/Browser/context-names.cjs index 5d877246..dc41d453 100644 --- a/PlotLine.Tests/Browser/context-names.cjs +++ b/PlotLine.Tests/Browser/context-names.cjs @@ -1,8 +1,18 @@ -const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; -(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:900},permissions:['clipboard-read','clipboard-write']});await c.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 c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}}));let queries=[];await c.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 c.route('**/Writing/Context/Names/*',async r=>{const u=new URL(r.request().url()),part=u.pathname.split('/').at(-1).toLowerCase();if(part==='search')queries.push(u.searchParams);await r.fulfill({response:await r.fetch({url:base+'/context-names-fixture/'+part+u.search})});});await c.route('**/Writing/Context/EditCharacter?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-edit-fixture?field=name'})}));const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-name-id]'); - step='discovery default and complete criteria';assert.equal(await p.locator('[data-context-name-id]').count(),25);assert.equal(await p.locator('[data-name-row]').count(),0);await p.locator('[name=Search]').fill('Uncommon');await p.selectOption('[name=LocaleCode]','fr-FR');await p.selectOption('[name=UsedOnly]','false');await p.click('[data-name-filters] summary');await p.locator('[name=BirthYear]').fill('1850');await p.selectOption('[data-name-gender]','Male:0.9');await p.selectOption('[name=NameType]','Variant');await p.selectOption('[name=MinimumUsage]','0.05');await p.selectOption('[name=UsedScope]','Book');await p.selectOption('[name=BookID]','13');await p.selectOption('[name=PageSize]','100');await p.locator('[data-context-name-search] [type=submit]').click();await p.waitForFunction(()=>document.querySelectorAll('[data-context-name-id]').length===100);for(const [key,value]of Object.entries({Search:'Uncommon',LocaleCode:'fr-FR',BirthYear:'1850',GenderPreference:'Male',GenderThreshold:'0.9',NameType:'Variant',MinimumUsage:'0.05',UsedScope:'Book',BookID:'13',UsedOnly:'false',Page:'1',PageSize:'100'}))assert.equal(queries.at(-1).get(key),value,key); - step='profile, copy, related forms and selected usage';const first=p.locator('[data-context-name-id]').first();await first.locator('[data-name-copy]').click();assert.equal(await p.evaluate(()=>navigator.clipboard.readText()),'Uncommon 1');await first.locator('summary').click();assert.match(await first.innerText(),/Known spelling variant/);await first.locator('[data-name-usage]').click();await first.locator('[data-name-usage-fragment]').waitFor();await first.locator('[data-name-identity]').click();await p.waitForSelector('[data-name-identity-fragment]');assert.match(await p.locator('[data-name-identity-fragment]').innerText(),/Known variant/);await p.locator('[data-context-edit="name"]').click();await p.waitForSelector('[data-context-edit-form]');await p.click('[data-context-edit-cancel]'); - step='pagination preserves all criteria';await p.click('[data-name-page="2"]');await p.waitForSelector('[data-name-results-fragment][data-page="2"]');assert.equal(queries.at(-1).get('GenderThreshold'),'0.9');assert.equal(await p.locator('[data-context-name-id]').first().getAttribute('data-context-name-id'),'101'); - step='independent same-tool panes and book scope';await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','names');await p.locator('[data-context-pane="1"] [name=Search]').fill('Other lookup');assert.equal(await p.locator('[data-context-pane="0"] [name=Search]').inputValue(),'Uncommon');const before=queries.length;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.waitForTimeout(150);assert.equal(queries.length,before); - step='actual pane widths and substantial result set';for(const width of [1366,760,390]){await p.setViewportSize({width,height:900});for(const layout of ['single','columns','rows']){await p.selectOption('[data-context-layout]',layout);await p.waitForTimeout(60);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}assert.deepEqual(errors,[]);console.log('PASS Names discovery browser: all library criteria, 100 bounded candidates, profiles/related forms/copy, on-demand usage/identity/correction, pagination, book scope, independent panes and desktop/half/stacked/mobile widths (query parity qualified separately against Development).'); -}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})(); +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),os=require('node:os');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const installed=process.argv.includes('--installed'),profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-context-names-pwa-')):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1080},permissions:['clipboard-read','clipboard-write']}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null,manifestId=base+'/Projects';try{ + const context=installed?persistent:await browser.newContext({viewport:{width:1920,height:1080},permissions:['clipboard-read','clipboard-write']}); + 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})});}); + const queries=[];await context.route('**/Writing/Context/Names/*',async r=>{const u=new URL(r.request().url()),part=u.pathname.split('/').at(-1).toLowerCase();queries.push({part,params:u.searchParams});await r.fulfill({response:await r.fetch({url:base+'/names-workspace-fixture/'+(part==='search'?'results':part)+u.search})});}); + let page;if(installed){await persistent.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await context.newPage();const errors=[];page.on('pageerror',error=>errors.push(error.message));await page.goto(base+'/Writing/Context');await page.locator('[data-context-tab]').first().selectOption('names'); + const pane=index=>page.locator(`[data-context-pane="${index}"]`),first=pane(0);await first.locator('[data-name-select]').first().waitFor();assert.equal(queries.length,0); + await first.locator('[name=Search]').fill('George');await first.locator('[data-names-filters] summary').click();await first.locator('[name=BirthYear]').fill('1850');await first.locator('[name=LocaleCode]').selectOption('fr-FR');await first.locator('[data-names-gender]').selectOption('Male:0.9');await first.locator('[name=NameType]').selectOption('Variant');await first.locator('[name=MinimumUsage]').selectOption('0.05');await first.locator('[name=PageSize]').selectOption('100');await first.locator('[data-names-search]').evaluate(f=>f.requestSubmit());await page.waitForFunction(()=>document.querySelectorAll('[data-context-pane="0"] [data-name-select]').length===100); + const query=queries.at(-1).params;for(const [key,value]of Object.entries({contextBookId:'12',ProjectID:'7',Search:'George',BirthYear:'1850',LocaleCode:'fr-FR',GenderPreference:'Male',GenderThreshold:'0.9',NameType:'Variant',MinimumUsage:'0.05',PageSize:'100'}))assert.equal(query.get(key),value,key); + await first.locator('[data-name-select]').first().click();await first.locator('[data-name-details-fragment]').waitFor();assert.equal(await first.locator('.names-association').count(),2);await first.locator('[data-name-copy]').click();assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),'George 1'); + await page.locator('[data-context-layout]').selectOption('columns');await pane(1).locator('[data-context-tab]').selectOption('names');await pane(1).locator('[name=Search]').fill('Hamish');assert.equal(await first.locator('[name=Search]').inputValue(),'George');const before=queries.length; + await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await page.waitForTimeout(200);assert.equal(queries.length,before);assert.equal(await first.locator('[name=Search]').inputValue(),'George');assert.equal(await first.locator('[data-name-details-fragment] h2').innerText(),'George 1'); + fs.mkdirSync('/tmp/pd-names-workspace',{recursive:true});for(const width of [2560,1366,768,390]){await page.setViewportSize({width,height:1080});for(const layout of ['single','columns','rows']){await page.locator('[data-context-layout]').selectOption(layout);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),`${width}/${layout}`);}if(width===2560||width===390)await page.screenshot({path:`/tmp/pd-names-workspace/context-${installed?'pwa':'browser'}-${width}.png`});} + await page.setViewportSize({width:1920,height:1080});await page.locator('[data-context-layout]').selectOption('single');await first.locator('[data-context-tab]').selectOption('overview');await first.locator('[data-context-tab]').selectOption('names');await first.locator('[data-name-select]').first().waitFor();assert.equal(await first.locator('[name=Search]').inputValue(),'George');assert.deepEqual(errors,[]); + console.log('PASS shared Context Names: complete catalogue criteria, deferred animal/alias details, copy, independent panes, focus stability, narrow/wide/split layouts and tab state'); + }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(error=>{console.error(error);process.exitCode=1;}); diff --git a/PlotLine.Tests/ContextNamesTests.cs b/PlotLine.Tests/ContextNamesTests.cs index e3e7d729..f13fc3fe 100644 --- a/PlotLine.Tests/ContextNamesTests.cs +++ b/PlotLine.Tests/ContextNamesTests.cs @@ -9,8 +9,8 @@ internal static class ContextNamesTests var filter=new NameSearchFilter{ProjectID=999,BookID=12,Search="Jo",LocaleCode="en-GB",BirthYear=1850,GenderPreference="Female",GenderThreshold=.7m,NameType="Variant",MinimumUsage=.05m,UsedScope="Book",UsedOnly=false,Page=2,PageSize=50};var value=await panel.Build(7,12,filter); Check(ReferenceEquals(observed,filter)&&observed.ProjectID==7&&observed.LocaleCode=="en-GB"&&observed.BirthYear==1850&&observed.GenderThreshold==.7m&&observed.MinimumUsage==.05m&&observed.UsedOnly==false&&observed.Page==2&&observed.PageSize==50,"all library criteria pass directly to the existing query service; project is authorised"); Check(ReferenceEquals(value.Library!.Results,results)&&value.Entries.Count==0,"candidate rows/counts/usage are unchanged and no identity catalogue is loaded"); - await panel.Build(7,12);Check(observed!.BookID==12&&observed.UsedScope=="Book"&&observed.PageSize==25,"discovery opens with bounded current-book criteria"); - await panel.Usage(7,12,"e\u0301va","Book");Check(normalised=="ÉVA"&&scope=="Book","exact identity/alias usage reuses existing normalisation and scope query"); + await panel.Build(7,12);Check(observed!.BookID==12&&observed.UsedScope=="Project"&&observed.PageSize==25,"discovery retains book profile defaults with bounded series-wide usage"); + await panel.Usage(7,12,"e\u0301va","Book");Check(normalised=="ÉVA"&&scope=="Project","exact identity/alias usage reuses existing normalisation across the series"); var identity=await panel.Identity(7,12,5);Check(identity.Entries.Single().Aliases.Single().Alias=="Variant"&&identity.CanEdit,"only explicitly selected canonical identity and aliases are loaded"); projectRole="Viewer";Check(!(await panel.Identity(7,12,5)).CanEdit,"read-only identity references expose no corrections");personProject=8;try{await panel.Identity(7,12,5);throw new Exception("Foreign identity accepted");}catch(UnauthorizedAccessException){Check(true,"foreign-project identity cannot be inspected for correction");} } diff --git a/PlotLine/Controllers/ContextNamesController.cs b/PlotLine/Controllers/ContextNamesController.cs index e71b026c..5271bf96 100644 --- a/PlotLine/Controllers/ContextNamesController.cs +++ b/PlotLine/Controllers/ContextNamesController.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using PlotLine.Data;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context; namespace PlotLine.Controllers; [Authorize,Route("Writing/Context/Names"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] -public sealed class ContextNamesController(ContextNames names,IWordCompanionRepository access,IBookRepository books,ICurrentUserService user):Controller +public sealed class ContextNamesController(ContextNames names,IWordCompanionRepository access,IBookRepository books,ICurrentUserService user,NamesWorkspace workspace):Controller { private async Task Book(int id){if(!user.UserId.HasValue||await access.GetBookStructureAsync(id,user.UserId.Value)==null)throw new UnauthorizedAccessException();return await books.GetAsync(id)??throw new UnauthorizedAccessException();} [HttpGet("Search")] @@ -9,9 +9,15 @@ public sealed class ContextNamesController(ContextNames names,IWordCompanionRepo { if(!ModelState.IsValid||filter.Search?.Length>120)return BadRequest(); try{var book=await Book(contextBookId);if(filter.BookID.HasValue&&(await books.GetAsync(filter.BookID.Value))?.ProjectID!=book.ProjectID)return Forbid(); - var panel=await names.Build(book.ProjectID,contextBookId,filter,cancellationToken);return PartialView("~/Views/Writing/_ContextNameResults.cshtml",panel); + var panel=await names.Build(book.ProjectID,contextBookId,filter,cancellationToken);return PartialView("~/Views/Shared/_NamesResults.cshtml",panel.Library); }catch(UnauthorizedAccessException){return Forbid();} } + [HttpGet("Details")] + public async Task Details(int contextBookId,string name,string? localeCode,int? birthYear,CancellationToken cancellationToken) + { + if(!ModelState.IsValid||string.IsNullOrWhiteSpace(name)||name.Length>120)return BadRequest(); + try{var book=await Book(contextBookId);var model=await workspace.Details(book.ProjectID,name,localeCode,birthYear,cancellationToken);return model is null?NotFound():PartialView("~/Views/Shared/_NameDetails.cshtml",model);}catch(UnauthorizedAccessException){return Forbid();} + } [HttpGet("Usage")] public async Task Usage(int contextBookId,string search,int? bookId,string usedScope="Project",CancellationToken cancellationToken=default) { diff --git a/PlotLine/Services/Context/ContextNames.cs b/PlotLine/Services/Context/ContextNames.cs index 77111d06..fe4da647 100644 --- a/PlotLine/Services/Context/ContextNames.cs +++ b/PlotLine/Services/Context/ContextNames.cs @@ -9,14 +9,14 @@ public sealed class ContextNames(ICharacterRepository characters,IProjectReposit { var author=user.UserId??throw new UnauthorizedAccessException(); var project=await projects.GetForUserAsync(projectId,author)??throw new UnauthorizedAccessException(); - filter??=new(){BookID=bookId,UsedScope="Book",PageSize=25};filter.ProjectID=projectId; + filter??=new(){BookID=bookId,UsedScope="Project",PageSize=25};filter.ProjectID=projectId;filter.UsedScope="Project"; var library=await names.BuildLibraryAsync(filter,cancellationToken); return new(projectId,bookId,ContextEditPolicy.CanEdit(project),[],library); } public async Task> Usage(int projectId,int? bookId,string search,string scope,CancellationToken cancellationToken=default) { var author=user.UserId??throw new UnauthorizedAccessException();if(await projects.GetForUserAsync(projectId,author)==null)throw new UnauthorizedAccessException(); - return await reference.ListUsedDecorationsAsync(author,projectId,bookId,NameIntelligenceService.NormaliseName(search),scope,cancellationToken); + return await reference.ListUsedDecorationsAsync(author,projectId,null,NameIntelligenceService.NormaliseName(search),"Project",cancellationToken); } public async Task Identity(int projectId,int bookId,int characterId) { diff --git a/PlotLine/Services/NameIntelligenceService.cs b/PlotLine/Services/NameIntelligenceService.cs index 6e933512..2ef378f6 100644 --- a/PlotLine/Services/NameIntelligenceService.cs +++ b/PlotLine/Services/NameIntelligenceService.cs @@ -139,6 +139,7 @@ public sealed class NameIntelligenceService( var rows = await SearchAsync(filter, cancellationToken); return new NamesLibraryViewModel { + UserID = userId, Project = project, Filter = filter, Locales = locales, diff --git a/PlotLine/ViewModels/NamesViewModels.cs b/PlotLine/ViewModels/NamesViewModels.cs index 6ce7e03d..81262894 100644 --- a/PlotLine/ViewModels/NamesViewModels.cs +++ b/PlotLine/ViewModels/NamesViewModels.cs @@ -4,6 +4,7 @@ namespace PlotLine.ViewModels; public sealed class NamesLibraryViewModel { + public int UserID { get; init; } public Project Project { get; init; } = new(); public NameSearchFilter Filter { get; init; } = new(); public IReadOnlyList Locales { get; init; } = []; diff --git a/PlotLine/Views/Shared/_NamesWorkspace.cshtml b/PlotLine/Views/Shared/_NamesWorkspace.cshtml index c1888eb7..17bac2aa 100644 --- a/PlotLine/Views/Shared/_NamesWorkspace.cshtml +++ b/PlotLine/Views/Shared/_NamesWorkspace.cshtml @@ -1,7 +1,7 @@ @model NamesLibraryViewModel @{var f=Model.Filter;} -
+
diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 1b84daaf..bea27969 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -56,6 +56,7 @@ @section Scripts { + diff --git a/PlotLine/Views/Writing/_ContextNames.cshtml b/PlotLine/Views/Writing/_ContextNames.cshtml index 7ae83215..a04724b3 100644 --- a/PlotLine/Views/Writing/_ContextNames.cshtml +++ b/PlotLine/Views/Writing/_ContextNames.cshtml @@ -1,25 +1,4 @@ @model WritingContextDisplayViewModel -@{var panel=Model.NamePanel;var library=panel?.Library;} -@if(library==null){

Names Library is unavailable. Refresh this tool.

}else{ -var f=library.Filter; -
-
-
- -
-
More filters and usage scope
- - - - - - - -
-
-

Candidates come from the existing Names Library. Usage is evaluated in the selected scope; unused in one book does not mean unused elsewhere.

-

-
Look up an established character or alias
-

-Open full Names workspace -
} +@if(Model.NamePanel?.Library is {} library){ +
+}else{

Names Library is unavailable. Refresh this tool.

} diff --git a/PlotLine/wwwroot/js/context-names.js b/PlotLine/wwwroot/js/context-names.js index 1ae8d2fe..46e82c57 100644 --- a/PlotLine/wwwroot/js/context-names.js +++ b/PlotLine/wwwroot/js/context-names.js @@ -1,27 +1,16 @@ (() => { - 'use strict';const saved=new Map(),mounted=new WeakMap(); + 'use strict'; + const saved=new Map(),mounted=new WeakMap(); window.PlotDirectorContextLifecycles.names={ - mount(node,{paneId}){ - const host=node.querySelector('[data-context-names]');if(!host)return;const abort=new AbortController(),form=host.querySelector('[data-context-name-search]'),status=host.querySelector('[data-name-query-status]'),results=host.querySelector('[data-context-name-results]');let active,epoch=0,page=1; - const state={host,abort,paneId,form,get page(){return page;}};mounted.set(node,state);const prior=saved.get(paneId); - if(prior){for(const [name,value]of prior.fields){const input=form.elements.namedItem(name);if(input)input.value=value;}form.querySelector('[data-name-gender]').value=prior.gender;host.querySelector('[data-name-filters]').open=prior.expanded;page=prior.page;} - const listen=(target,event,handler)=>target.addEventListener(event,handler,{signal:abort.signal}); - async function fragment(url,selector){const response=await fetch(url,{cache:'no-store',signal:abort.signal,headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error('This lookup is unavailable. Check book access and sign-in.');const parsed=new DOMParser().parseFromString(await response.text(),'text/html'),value=parsed.querySelector(selector);if(!value)throw Error('The lookup returned an unavailable response.');return value;} - async function query(nextPage=1){const request=++epoch;active?.abort();active=new AbortController();const params=new URLSearchParams(new FormData(form));params.set('contextBookId',host.dataset.book);params.set('Page',nextPage);if(params.get('UsedScope')==='Book'&&!params.get('BookID')){status.textContent='Choose a book for book-scoped usage.';return;}status.textContent='Searching the Names Library…';results.setAttribute('aria-busy','true'); - try{const response=await fetch('/Writing/Context/Names/Search?'+params,{cache:'no-store',signal:AbortSignal.any([abort.signal,active.signal,AbortSignal.timeout(20000)])});if(!response.ok||response.redirected)throw Error('Library search is unavailable. Your criteria are retained; check access and retry.');const parsed=new DOMParser().parseFromString(await response.text(),'text/html'),value=parsed.querySelector('[data-name-results-fragment]');if(!value)throw Error('Library response is unavailable.');if(request!==epoch||!node.isConnected)return;results.replaceChildren(value);page=Number(value.dataset.page);status.textContent='';const applied=value.querySelector('[data-name-applied-filter]');if(applied){const f=JSON.parse(applied.textContent);for(const [name,v]of Object.entries(f)){const input=form.elements.namedItem(name);if(input)input.value=v==null?'':String(v);}form.querySelector('[data-name-gender]').value=f.GenderPreference?f.GenderPreference+':'+f.GenderThreshold:'';}} - catch(error){if(error.name!=='AbortError'&&request===epoch)status.textContent=error.message;}finally{if(request===epoch)results.removeAttribute('aria-busy');} - } - listen(form,'submit',e=>{e.preventDefault();void query();});listen(form.querySelector('[data-name-gender]'),'change',e=>{const [preference,threshold]=(e.target.value||'').split(':');form.elements.namedItem('GenderPreference').value=preference||'';form.elements.namedItem('GenderThreshold').value=threshold||'';}); - listen(host,'click',async e=>{const target=e.target.closest('button');if(!target)return; - if(target.hasAttribute('data-name-page')){void query(Number(target.dataset.namePage));return;} - if(target.hasAttribute('data-name-copy')){try{await navigator.clipboard.writeText(target.dataset.nameCopy);window.PlotDirector?.toast?.success('Name copied.');}catch{window.PlotDirector?.toast?.error('Copy is unavailable. Select the name text and copy it.');}return;} - if(target.hasAttribute('data-name-focus')){target.dispatchEvent(new CustomEvent('context-command',{bubbles:true,detail:{action:'character.focus',characterID:Number(target.dataset.nameFocus)}}));return;} - if(target.hasAttribute('data-name-usage')){const box=target.parentElement.querySelector('[data-name-usage-result]');box.textContent='Loading recorded project usage…';const params=new URLSearchParams({contextBookId:host.dataset.book,search:target.dataset.nameUsage,usedScope:'Project'});try{box.replaceChildren(await fragment('/Writing/Context/Names/Usage?'+params,'[data-name-usage-fragment]'));}catch(error){if(error.name!=='AbortError')box.textContent=error.message;}return;} - if(target.hasAttribute('data-name-identity')){const box=host.querySelector('[data-context-name-identity]');box.textContent='Loading canonical identity…';try{box.replaceChildren(await fragment('/Writing/Context/Names/Identity?'+new URLSearchParams({contextBookId:host.dataset.book,characterId:target.dataset.nameIdentity}),'[data-name-identity-fragment]'));box.scrollIntoView({block:'nearest'});}catch(error){if(error.name!=='AbortError')box.textContent=error.message;}} - }); - listen(host.querySelector('[data-context-name-lookup]'),'submit',async e=>{e.preventDefault();const box=host.querySelector('[data-context-name-identities]');box.textContent='Looking up this recorded spelling…';try{box.replaceChildren(await fragment('/Writing/Context/Names/Usage?'+new URLSearchParams({contextBookId:host.dataset.book,search:new FormData(e.target).get('search'),usedScope:'Project'}),'[data-name-usage-fragment]'));}catch(error){if(error.name!=='AbortError')box.textContent=error.message;}}); - abort.signal.addEventListener('abort',()=>active?.abort(),{once:true});if(prior)void query(prior.page); - }, - dispose(node){const state=mounted.get(node);if(!state)return;saved.set(state.paneId,{fields:[...new FormData(state.form)],gender:state.form.querySelector('[data-name-gender]').value,expanded:state.host.querySelector('[data-name-filters]').open,page:state.page});state.abort.abort();mounted.delete(node);} + mount(node,{paneId}){ + const host=node.querySelector('[data-context-names]'),root=host?.querySelector('[data-names-workspace]');if(!root)return; + const book=host.dataset.book,key=book+':'+paneId; + root.dataset.searchUrl='/Writing/Context/Names/Search?contextBookId='+encodeURIComponent(book); + root.dataset.detailsUrl='/Writing/Context/Names/Details?contextBookId='+encodeURIComponent(book); + // A pane owns its reference-tool state. No manuscript-focus commands or SignalR connections. + const workspace=window.PlotDirectorNames.mount(root,{state:saved.get(key),onState:value=>saved.set(key,value)}); + mounted.set(node,workspace); + }, + dispose(node){mounted.get(node)?.dispose();mounted.delete(node);} }; })(); diff --git a/PlotLine/wwwroot/js/names-workspace.js b/PlotLine/wwwroot/js/names-workspace.js index 0ff50373..04377dd7 100644 --- a/PlotLine/wwwroot/js/names-workspace.js +++ b/PlotLine/wwwroot/js/names-workspace.js @@ -12,12 +12,12 @@ 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();} + try{const node=await fragment(root.dataset.detailsUrl+(root.dataset.detailsUrl.includes('?')?'&':'?')+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();} + try{const node=await fragment(root.dataset.searchUrl+(root.dataset.searchUrl.includes('?')?'&':'?')+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();}); @@ -34,6 +34,6 @@ 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);} + 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.user+':'+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(); })();