diff --git a/Docs/Writer/Context-UX-Refinement-20261122.md b/Docs/Writer/Context-UX-Refinement-20261122.md index 6bd62eb0..9a8c083b 100644 --- a/Docs/Writer/Context-UX-Refinement-20261122.md +++ b/Docs/Writer/Context-UX-Refinement-20261122.md @@ -15,3 +15,17 @@ Main recipients acknowledge navigation, attempt focus where permitted and protec Context workspace links use `data-context-workspace-target` plus optional `data-context-entity` as the reusable standard; href remains an accessible fallback. Existing main editors are not redesigned. Stage 1 qualification: clean solution build (zero warnings/errors), 19 registry/routing/lease assertions, real-SignalR isolated browser routing suite, existing Characters editing/responsive suite and expanded shared-refinement browser acceptance passed. Every existing character/name correction variant (classification, description, emotional state, physical condition, location, canonical name, alias add and alias correction/removal) and the relationship form was checked for full-width controls; desktop/mobile, one Save/Cancel and Escape passed. Existing-main reuse, repeated actions, unsaved-main cancellation and one named missing-main fallback passed. Browser fixture editor endpoints render the real application shell/views; canonical persistence is qualified separately. Relationship main-editor navigation retains the selected story point. No database migration was needed in this stage. + +Stage 1 deployed at `5de6e5f`, archive `context-refine-stage1-5de6e5f-20261122T162449Z`. Published/live assembly and all changed navigation/form assets matched SHA-256; clean active-job guard before restart; service active. Actual Development acceptance reused one existing main window for the real Scene, Character, Names and Relationships editors, kept the Context scene unchanged and sent no Word navigation. Focus remains discretionary in the browser. No canonical edits were made by this navigation check. + +## Stage 2: Names Library discovery + +Names now opens with bounded reference-library candidates rather than an identity catalogue. It calls the same `INameIntelligenceService.BuildLibraryAsync` with the complete existing `NameSearchFilter`: search, locale, birth year, gender preference/threshold, type, minimum commonness, project/book/accessible-project usage scope, used/unused, page and page size. No replacement database, generation or matching engine. Profiles retain existing prior weights, era, confidence, source, related forms and usage summary. Copy uses the clipboard and shared toast. Additional filters collapse; layouts use pane containers. Search cancellation propagates to the existing library query. Pagination retains criteria; pane state is independent. + +The tool is book-scoped, works without an active scene and does not reload just because the scene changes. Exact established-name/alias lookup and candidate project-use inspection reuse `GivenName_UsedDecorations`, now bounded to 100 distinct use records. Canonical identity/aliases load only after explicit selection, with existing focused name/alias modals and My Windows character focus. No automatic merge or rename. The obsolete alphabetical presentation and separate suggestion-only partial were removed. + +Underlying shared-query correction (migration299): the existing Name Search book-usage CTE joined every character to every book in its project, so unused-in-this-book could be reported as used. It now uses the same canonical SceneCharacters→Scenes→Chapters→Books membership joins as existing usage details. Project scope still includes project identities without appearances; Book scope requires a recorded appearance. Mentioned-only participation can establish name use, which does not establish physical presence or POV knowledge. No manuscript text matching or invented name-use evidence. The main controller now interprets its existing book scope selector correctly; hidden scope/pagination metadata preserve explicit criteria. The main UI is not redesigned. Nonvisual result IDs/counts permit exact parity acceptance. + +Both live procedure definitions were checked against the previous authoritative migration before applying the new forward-only definitions. Development backup `context-refine-stage2-20261122T163128Z.bak` succeeded and VERIFYONLY passed. Migration299 applied and its procedures were smoke-verified. No canonical data rows were changed by the migration. Disposable qualification added one empty book and one reference-name alias on the existing synthetic character; shared-query acceptance proved used in the character's appearance book and unused in the empty second book. + +Stage 2 predeployment qualification: clean solution build, seven direct library/filter/bounded-identity/read-only assertions, 17 existing character/name-edit assertions, stored-procedure architecture guard, actual compiled Razor browser with all filters, 100 candidates, profile/related forms/copy, on-demand identity/correction, pagination, independent panes and full/half/stacked/mobile passed. Touch-emulated 390px browser checks passed. Full Development query-parity acceptance follows installation. Existing open application/Context windows should reload once to acquire the updated tool scripts; no Word navigation is part of that reload. diff --git a/PlotLine.Tests/Browser/context-live-editing.cjs b/PlotLine.Tests/Browser/context-live-editing.cjs index 4599dcf9..b36f5690 100644 --- a/PlotLine.Tests/Browser/context-live-editing.cjs +++ b/PlotLine.Tests/Browser/context-live-editing.cjs @@ -8,8 +8,9 @@ const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('nod async function save(){await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);} step='live canonical description and quiet remote refresh';await open('description');await p.locator('[name=Value]').fill(stamp);await save();await remote.waitForFunction(stamp=>document.querySelector('[data-character-explorer]').textContent.includes(stamp),stamp);assert.equal(await p.evaluate(()=>successes),1);assert.equal(await remote.evaluate(()=>successes),0); step='cancel persists nothing';await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.locator('[name=Value]').fill('Discarded synthetic draft');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.click('[data-context-edit-cancel]'); - step='names alias add and persisted spelling';await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-names]');await p.locator('[data-name-filter]').fill('Synthetic Context person one');await p.locator('[data-name-row]:visible summary').click();await p.locator(`[data-context-edit="alias-add"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');const alias='Synthetic alias '+Date.now();await p.locator('[name=Value]').fill(alias);await save();await p.waitForFunction(alias=>document.querySelector('[data-context-names]').textContent.includes(alias),alias); - step='live inline validation retains failed draft';await p.locator('[data-name-filter]').fill('Synthetic Context person one');if(!await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).isVisible())await p.locator('[data-name-row]:visible summary').click();await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');await p.locator('[name=Value]').fill('');await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForSelector('.validation-summary-errors');assert(await p.locator('[data-context-edit-dialog]').isVisible());assert.equal(await p.locator('[name=Value]').inputValue(),'');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]'); + async function lookupIdentity(query){const details=p.locator('[data-established-names]');if(!await details.evaluate(n=>n.open))await details.locator('summary').first().click();await p.locator('[data-context-name-lookup] [name=search]').fill(query);await p.locator('[data-context-name-lookup] [type=submit]').click();await p.locator('[data-context-name-identities] [data-name-usage-fragment]').waitFor();await p.locator(`[data-context-name-identities] [data-name-identity="${id}"]`).click();await p.waitForSelector('[data-name-identity-fragment]');} + step='names alias add and persisted spelling';await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-names]');await lookupIdentity('Synthetic Context person one');await p.locator(`[data-context-edit="alias-add"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');const alias='Synthetic alias '+Date.now();await p.locator('[name=Value]').fill(alias);await save();await p.waitForSelector('[data-context-names]');await lookupIdentity(alias);assert.match(await p.locator('[data-name-identity-fragment]').innerText(),new RegExp(alias)); + step='live inline validation retains failed draft';await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');await p.locator('[name=Value]').fill('');await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForSelector('.validation-summary-errors');assert(await p.locator('[data-context-edit-dialog]').isVisible());assert.equal(await p.locator('[name=Value]').inputValue(),'');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]'); if(process.env.PD_CONTEXT_RELATIONSHIPS==='1'){ step='live one-relationship create and correction';await p.selectOption('[data-context-tab]','relationships');await remote.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await remote.waitForSelector('[data-context-relationships]'); const existing=p.locator('[data-context-relationship]');if(await existing.count()===0){await p.locator('[data-context-relationship-edit="scene"]').last().click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(s.characters[0]));await p.selectOption('[name=TargetID]',String(s.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&!n.textContent.includes('Family'))?.value);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic relationship evidence');await save();} diff --git a/PlotLine.Tests/Browser/context-names-parity.cjs b/PlotLine.Tests/Browser/context-names-parity.cjs new file mode 100644 index 00000000..56fb7e30 --- /dev/null +++ b/PlotLine.Tests/Browser/context-names-parity.cjs @@ -0,0 +1,12 @@ +// Actual shared Names Library query parity, read-only on an explicitly disposable Development project. +const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'); +(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));assert(s.libraryTestName&&s.unusedBook);const b=await chromium.launch();let step='login';try{const c=await b.newContext({viewport:{width:1280,height:900}}),main=await c.newPage();await main.goto('https://dev.plotdirector.com/Account/Login');await main.locator('[name=Email]').fill(who.Email);await main.locator('[name=Password]').fill(who.Password);await Promise.all([main.waitForURL(u=>u.pathname!='/Account/Login'),main.locator('button[type=submit]').click()]);const names=await c.newPage(); + await main.goto(`https://dev.plotdirector.com/Names?ProjectID=${s.project}&BookID=${s.book}&Search=${encodeURIComponent(s.libraryTestName)}&UsedScope=Book`);const locales=await main.locator('[name=LocaleCode] option').evaluateAll(ns=>ns.filter(n=>n.value).map(n=>({code:n.value,label:n.textContent.trim()})));assert(locales.length>=2);let testLocale=s.libraryLocale;if(!testLocale){const row=main.locator('tbody tr').first(),label=(await row.locator('td').nth(1).locator('.muted').innerText()).split(' · usage')[0].trim();testLocale=locales.find(l=>l.label===label)?.code||locales[0].code;} + const common={ProjectID:String(s.project),BookID:String(s.book),UsedScope:'Book',LocaleCode:testLocale,BirthYear:s.libraryBirthYear||'',Page:'1',PageSize:'25'}; + const cases=[{}, {Search:'zzxy-uncommon-qualification'}, {Search:s.libraryTestName,UsedOnly:'true'}, {Search:s.libraryTestName,BookID:String(s.unusedBook),UsedOnly:'false'}, {Search:s.libraryTestName,UsedScope:'Project',BookID:''}, {Search:'Jo',GenderPreference:'Female',GenderThreshold:'0.7',NameType:'Variant',MinimumUsage:'0.01'}, {LocaleCode:locales[0].code,Page:'2'}, {LocaleCode:locales[1].code,UsedOnly:'false'}, {Search:s.libraryTestName.slice(0,-1)}, {Search:s.libraryTestName,UsedScope:'Library',BookID:''}];let records=[]; + for(let i=0;irows.map(r=>({id:Number(r.dataset.nameLibraryId),used:Number(r.dataset.nameUsedCount)})));await names.goto('https://dev.plotdirector.com/Writing/Context/Names/Search?contextBookId='+s.book+'&'+q);const actual=await names.locator('[data-context-name-id]').evaluateAll(rows=>rows.map(r=>({id:Number(r.dataset.contextNameId),used:Number(r.dataset.usedCount)})));assert.deepEqual(actual,expected);assert(actual.length<=25);records.push(actual);} + assert(records[0].length>0&&records[6].length>0,'default and pagination searches must exercise actual candidates'); + assert(records[2].some(r=>r.used>0),'recorded alias must be used in its character appearance book');assert(records[3].every(r=>r.used===0)&&records[3].length>0,'same alias must be unused in empty second book');assert(records[4].some(r=>r.used>0),'project usage remains recorded'); + step='exact canonical/alias usage query';const response=await c.request.get('https://dev.plotdirector.com/Writing/Context/Names/Usage?'+new URLSearchParams({contextBookId:s.book,search:s.libraryTestName,usedScope:'Project'}));assert(response.ok());assert((await response.text()).includes('data-name-identity="'+s.characters[0]+'"')); + console.log('PASS Development Names parity: ten equivalent main/Context searches match exact candidate IDs and usage counts; empty/uncommon/near search, aliases, used/unused, book/project scope, gender/type/commonness, multiple locales and pagination; current-book alias used, empty other-book unused; bounded 25 rows.'); +}catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})(); diff --git a/PlotLine.Tests/Browser/context-names.cjs b/PlotLine.Tests/Browser/context-names.cjs index bd1c4977..5d877246 100644 --- a/PlotLine.Tests/Browser/context-names.cjs +++ b/PlotLine.Tests/Browser/context-names.cjs @@ -1,15 +1,8 @@ -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();}})(); +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();}})(); diff --git a/PlotLine.Tests/Browser/context-touch.cjs b/PlotLine.Tests/Browser/context-touch.cjs index 0bcb4ccd..942b89d0 100644 --- a/PlotLine.Tests/Browser/context-touch.cjs +++ b/PlotLine.Tests/Browser/context-touch.cjs @@ -1,2 +1,2 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; -(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});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'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));await c.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false}}));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})});});const p=await c.newPage();await p.goto(base+'/Writing/Context');for(const tool of ['characters','names','relationships']){await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');const first=p.locator('.context-character-row').first();await first.locator('summary').first().tap();await first.locator('summary').first().tap();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.screenshot({path:'/tmp/context-enhancement-'+tool+'-touch.png'});}console.log('PASS touch-emulated Chromium: all three tools, long names, summary tap and no horizontal overflow at 390px. Physical touch/PWA installation not exercised.');}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exitCode=1;}); +(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,deviceScaleFactor:2});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'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));await c.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false}}));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})});});const p=await c.newPage();await p.goto(base+'/Writing/Context');for(const tool of ['characters','names','relationships']){await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');const first=tool==='names'?p.locator('[data-context-name-id] details').first():p.locator('.context-character-row').first();await first.locator('summary').first().tap();await first.locator('summary').first().tap();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.screenshot({path:'/tmp/context-enhancement-'+tool+'-touch.png'});}console.log('PASS touch-emulated Chromium: all three tools, long names, summary tap and no horizontal overflow at 390px. Physical touch/PWA installation not exercised.');}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exitCode=1;}); diff --git a/PlotLine.Tests/ContextNamesBrowserFixture.cs b/PlotLine.Tests/ContextNamesBrowserFixture.cs new file mode 100644 index 00000000..6104e0bf --- /dev/null +++ b/PlotLine.Tests/ContextNamesBrowserFixture.cs @@ -0,0 +1,9 @@ +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;using PlotLine.Services.Context; +internal static class ContextNamesBrowserFixture +{ + public static ContextNamePanel Panel(NameSearchFilter? f=null){f??=new(){ProjectID=7,BookID=12,UsedScope="Book",PageSize=25};return new(7,12,true,[],new(){Project=new(){ProjectID=7,ProjectName="Fixture project"},Filter=f,Books=[new(){BookID=12,BookTitle="Current book"},new(){BookID=13,BookTitle="Other book"}],Locales=[new(){LocaleCode="en-GB",DisplayName="English (UK)"},new(){LocaleCode="fr-FR",DisplayName="French"}],Results=Enumerable.Range((Math.Max(1,f.Page)-1)*f.PageSize+1,f.PageSize).Select(i=>new NameSearchResult{GivenNameID=i,DisplayName=(f.Search??"Reference suggestion")+" "+i,NameType=f.NameType??"Canonical",LocaleDisplayName=f.LocaleCode??"English",RelatedForms="Known spelling variant",FemaleWeight=.7m,MaleWeight=.3m,UsageWeight=.5m,BirthYearFrom=1800,BirthYearTo=1900,UsedCount=f.UsedOnly==false?0:i%2,UsedSummary="Fixture participant · Current book",TotalRows=300}).ToList()});} + public static async Task Render(HttpContext context){var f=new NameSearchFilter{ProjectID=7,BookID=12,UsedScope="Book",PageSize=25};foreach(var p in typeof(NameSearchFilter).GetProperties()){var value=context.Request.Query[p.Name].ToString();if(!context.Request.Query.ContainsKey(p.Name))continue;var type=Nullable.GetUnderlyingType(p.PropertyType)??p.PropertyType;p.SetValue(f,string.IsNullOrWhiteSpace(value)&&type!=typeof(string)?null:Convert.ChangeType(value,type,System.Globalization.CultureInfo.InvariantCulture));} + var part=context.Request.RouteValues["part"]?.ToString();object model=part switch{"usage"=>new List{new(){CharacterID=5,CharacterName="Fixture participant",ProjectID=7,ProjectName="Fixture project",BookID=12,BookTitle="Current book",MatchedName="Known variant",MatchType="Alias"}},"identity"=>new ContextNamePanel(7,12,true,[new(new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant"},[new(){CharacterAliasID=11,CharacterID=5,Alias="Known variant"}],[])],null),_=>Panel(f)}; + var partial=part switch{"usage"=>"_ContextNameUsage","identity"=>"_ContextNameIdentity",_=>"_ContextNameResults"};var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/"+partial+".cshtml",false);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/ContextNamesTests.cs b/PlotLine.Tests/ContextNamesTests.cs new file mode 100644 index 00000000..e3e7d729 --- /dev/null +++ b/PlotLine.Tests/ContextNamesTests.cs @@ -0,0 +1,17 @@ +using PlotLine.Data;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels; +internal static class ContextNamesTests +{ + public static async Task Run(){void Check(bool p,string m){if(!p)throw new Exception(m);Console.WriteLine("PASS Context Names Library: "+m);} + NameSearchFilter? observed=null;var results=new List{new(){GivenNameID=8,DisplayName="Candidate",UsedCount=2,TotalRows=90}}; + var service=NativeWorkflowTests.Proxy((n,a)=>{if(n!="BuildLibraryAsync")throw new Exception(n);observed=(NameSearchFilter)a![0]!;return Task.FromResult(new(){Filter=observed,Results=results});}); + var projectRole="Owner";var personProject=7;var normalised="";var scope=""; + var panel=new ContextNames(NativeWorkflowTests.Proxy((n,a)=>n switch{"GetCharacterAsync"=>Task.FromResult(new(){CharacterID=5,ProjectID=personProject,CharacterName="Canonical"}),"ListAliasesAsync"=>Task.FromResult>([new(){CharacterID=5,CharacterAliasID=1,Alias="Variant"}]),_=>throw new Exception("Unbounded catalogue read: "+n)}),NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){ProjectID=7,AccessRole=projectRole})),NativeWorkflowTests.Proxy((_,_)=>4),service,NativeWorkflowTests.Proxy((n,a)=>{normalised=(string)a![3]!;scope=(string)a[4]!;return Task.FromResult>([]);})); + 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"); + 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.Tests/Program.cs b/PlotLine.Tests/Program.cs index 69278ea6..cffe1b3d 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -182,12 +182,14 @@ if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text. if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;} +if(args.Contains("--context-names")){await ContextNamesTests.Run();return;} if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;} if(args.Contains("--context-characters")){await ContextCharacterTests.Run();return;} if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;} var tests = new (string Name, Action Test)[] { + ("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()), ("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()), ("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()), ("Context My Windows routing and lifecycle",ContextWindowsTests.Run), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 85fe1c01..55c9f91c 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -408,6 +408,7 @@ internal static class ToolbarBrowserHost var model=new PlotLine.Services.Context.ContextRelationshipForm{BookID=12,SceneID=22,RelationshipID=9,Mode="scene",SourceID=5,TargetID=6,TypeID=1,StateID=1,Label="Relationship development at selected scene",Notes="Saved scene note",Fingerprint="fixture",Characters=[new("Fixture participant","5"),new("Other character","6")],Types=[new("Family · Parent","1")],States=[new("Established","1")]}; 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()); }); + app.MapGet("/context-names-fixture/{part}",ContextNamesBrowserFixture.Render); app.MapGet("/context-tab-fixture/{tool}",async context=> { var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22; @@ -425,7 +426,7 @@ internal static class ToolbarBrowserHost 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.RelationshipMap=new(){Relationships=[new(){CharacterRelationshipID=9,CharacterAID=5,CharacterBID=6,CharacterAName="Fixture participant",CharacterBName="A long established character name 6",RelationshipCategoryName="Family",RelationshipTypeName="Parent",CurrentStateName="Established",InitialStateEditable=true,Notes="Explicit recorded family note",History=[new(){SceneID=22,Label="Current scene",StateName="Established",Notes="An explicit development"}]},new(){CharacterRelationshipID=10,CharacterAID=5,CharacterBID=7,CharacterAName="Fixture participant",CharacterBName="Another character",RelationshipCategoryName="Social",RelationshipTypeName="Friend",CurrentStateName="Trusting",IsReciprocal=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"}]}); + model.NamePanel=ContextNamesBrowserFixture.Panel(); var action=new ActionContext(context,new RouteData(),new ActionDescriptor()); var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextTab.cshtml",false); using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; diff --git a/PlotLine/Controllers/ContextNamesController.cs b/PlotLine/Controllers/ContextNamesController.cs new file mode 100644 index 00000000..e71b026c --- /dev/null +++ b/PlotLine/Controllers/ContextNamesController.cs @@ -0,0 +1,26 @@ +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 +{ + 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")] + public async Task Search(int contextBookId,[FromQuery] NameSearchFilter filter,CancellationToken cancellationToken) + { + 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); + }catch(UnauthorizedAccessException){return Forbid();} + } + [HttpGet("Usage")] + public async Task Usage(int contextBookId,string search,int? bookId,string usedScope="Project",CancellationToken cancellationToken=default) + { + if(string.IsNullOrWhiteSpace(search)||search.Length>120||usedScope is not ("Project" or "Book" or "Library"))return BadRequest(); + try{var book=await Book(contextBookId);if(bookId.HasValue&&(await books.GetAsync(bookId.Value))?.ProjectID!=book.ProjectID)return Forbid(); + ViewData["ContextBookID"]=contextBookId;return PartialView("~/Views/Writing/_ContextNameUsage.cshtml",await names.Usage(book.ProjectID,bookId,search,usedScope,cancellationToken)); + }catch(UnauthorizedAccessException){return Forbid();} + } + [HttpGet("Identity")] + public async Task Identity(int contextBookId,int characterId) + {try{var book=await Book(contextBookId);return PartialView("~/Views/Writing/_ContextNameIdentity.cshtml",await names.Identity(book.ProjectID,contextBookId,characterId));}catch(UnauthorizedAccessException){return Forbid();}} +} diff --git a/PlotLine/Controllers/NamesController.cs b/PlotLine/Controllers/NamesController.cs index 5464fe41..37440625 100644 --- a/PlotLine/Controllers/NamesController.cs +++ b/PlotLine/Controllers/NamesController.cs @@ -15,6 +15,7 @@ public sealed class NamesController(INameIntelligenceService names) : Controller return BadRequest("ProjectID is required."); } + if(!Request.Query.ContainsKey("UsedScope")&&filter.BookID.HasValue)filter.UsedScope="Book"; var model = await names.BuildLibraryAsync(filter, cancellationToken); return model is null ? NotFound() : View(model); } diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index d80122d1..ee9f42bc 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -108,16 +108,15 @@ public sealed class WritingController( =>RenderContextTab("_ContextRelationships",projectId,bookId,chapterId,sceneId,instanceId,sessionId); [HttpGet("Context/Tabs/names")] - public Task ContextNamesTab(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId=null,Guid? sessionId=null) - =>RenderContextTab("_ContextNames",projectId,bookId,chapterId,sceneId,instanceId,sessionId); - [HttpGet("Context/NameSuggestions")] - public async Task ContextNameSuggestions(int bookId,string? search,[FromServices] IBookRepository books) + public async Task ContextNamesTab(int? projectId,int? bookId,int? chapterId,int? sceneId,[FromServices] IBookRepository books,Guid? instanceId=null,Guid? sessionId=null) { - 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); + if(!ModelState.IsValid||bookId is not >0||InvalidNativeSelection(instanceId,sessionId)||contextNames==null||companion==null)return BadRequest(); + var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser);var book=await books.GetAsync(bookId.Value); + if(structure==null||book==null||projectId.HasValue&&projectId!=book.ProjectID)return Forbid(); + var chapter=sceneId.HasValue?structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId)):null; + if(sceneId.HasValue&&chapter==null)return BadRequest(); + var model=new WritingContextDisplayViewModel{Context=new(){Position=new(book.ProjectID,book.BookID,chapter?.ChapterId,sceneId)},NamePanel=await contextNames.Build(book.ProjectID,book.BookID)}; + ViewData["ContextTabPartial"]="_ContextNames";return PartialView("_ContextTab",model); } private async Task RenderContextTab(string partial, int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId, Guid? sessionId) @@ -133,7 +132,6 @@ 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"||partial=="_ContextRelationships")&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model); - if(partial=="_ContextNames"&&contextNames!=null)model.NamePanel=await contextNames.Build(model.Context!.Position.ProjectId,model.Context.Position.BookId!.Value); ViewData["ContextTabPartial"] = partial; return PartialView("_ContextTab", model); } diff --git a/PlotLine/Services/Context/ContextNames.cs b/PlotLine/Services/Context/ContextNames.cs index b3ef54a4..77111d06 100644 --- a/PlotLine/Services/Context/ContextNames.cs +++ b/PlotLine/Services/Context/ContextNames.cs @@ -3,16 +3,29 @@ using PlotLine.Models; namespace PlotLine.Services.Context; public sealed record ContextNameEntry(Character Character,IReadOnlyList Aliases,IReadOnlyList SharedSpellings); public sealed record ContextNamePanel(int ProjectID,int BookID,bool CanEdit,IReadOnlyList Entries,PlotLine.ViewModels.NamesLibraryViewModel? Library); -public sealed class ContextNames(ICharacterRepository characters,IProjectRepository projects,ICurrentUserService user,INameIntelligenceService names) +public sealed class ContextNames(ICharacterRepository characters,IProjectRepository projects,ICurrentUserService user,INameIntelligenceService names,INameIntelligenceRepository reference) { - public async Task Build(int projectId,int bookId,string? search=null) + public async Task Build(int projectId,int bookId,NameSearchFilter? filter=null,CancellationToken cancellationToken=default) { 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); + filter??=new(){BookID=bookId,UsedScope="Book",PageSize=25};filter.ProjectID=projectId; + 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); + } + public async Task Identity(int projectId,int bookId,int characterId) + { + var author=user.UserId??throw new UnauthorizedAccessException();var project=await projects.GetForUserAsync(projectId,author)??throw new UnauthorizedAccessException(); + var person=await characters.GetCharacterAsync(characterId)??throw new UnauthorizedAccessException();if(person.ProjectID!=projectId)throw new UnauthorizedAccessException(); + var aliases=await characters.ListAliasesAsync(characterId); + return new(projectId,bookId,ContextEditPolicy.CanEdit(project),Compose([person],aliases.Take(50).ToList()),null); + } + public static IReadOnlyList Compose(IReadOnlyList people,IReadOnlyList aliases) { var active=people.Where(c=>!c.IsArchived).ToList();var ids=active.Select(c=>c.CharacterID).ToHashSet(); diff --git a/PlotLine/Sql/299_ContextNamesUsageScope.sql b/PlotLine/Sql/299_ContextNamesUsageScope.sql new file mode 100644 index 00000000..c8f319d1 --- /dev/null +++ b/PlotLine/Sql/299_ContextNamesUsageScope.sql @@ -0,0 +1,185 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- Shared library usage uses established scene membership for book scope; no data rows change. +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, + STRING_AGG(CONVERT(nvarchar(max), c.CharacterName + N' (' + p.ProjectName + COALESCE(N' / ' + b.BookTitle, N'') + N')'), N'; ') AS UsedSummary + FROM dbo.GivenNames g + INNER JOIN + ( + SELECT c.CharacterID, c.ProjectID, c.CharacterName, c.CharacterName AS MatchedName + FROM dbo.Characters c + WHERE c.IsArchived = 0 + UNION ALL + SELECT c.CharacterID, c.ProjectID, c.CharacterName, ca.Alias AS MatchedName + FROM dbo.CharacterAliases ca + INNER JOIN dbo.Characters c ON c.CharacterID = ca.CharacterID + WHERE c.IsArchived = 0 + ) c ON UPPER(LTRIM(RTRIM(c.MatchedName))) = g.NormalisedName COLLATE Latin1_General_100_CI_AI_SC + INNER JOIN dbo.Projects p ON p.ProjectID = c.ProjectID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = c.ProjectID AND pua.UserID = @UserID AND pua.IsActive = 1 + LEFT JOIN dbo.SceneCharacters sc ON sc.CharacterID = c.CharacterID + LEFT JOIN dbo.Scenes s ON s.SceneID = sc.SceneID AND s.IsArchived = 0 + LEFT JOIN dbo.Chapters ch ON ch.ChapterID = s.ChapterID AND ch.IsArchived = 0 + LEFT JOIN dbo.Books b ON b.BookID = ch.BookID AND b.IsArchived = 0 + WHERE (@UsedScope = N'Library' OR c.ProjectID = @ProjectID) + AND (@BookID IS NULL OR @UsedScope <> N'Book' OR b.BookID = @BookID) + 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, + 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 + +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; + + SET @Take=CASE WHEN @Take BETWEEN 1 AND 100 THEN @Take ELSE 100 END; + SELECT DISTINCT TOP (@Take) + rows.MatchedName, + rows.MatchType, + c.CharacterID, + c.CharacterName, + p.ProjectID, + p.ProjectName, + b.BookID, + b.BookTitle, + b.Subtitle AS BookSubtitle, + CASE WHEN b.BookID IS NOT NULL THEN N'Book' ELSE N'Project' END AS Scope + FROM + ( + SELECT c.CharacterID, c.ProjectID, c.CharacterName AS MatchedName, N'Character' AS MatchType + FROM dbo.Characters c + WHERE c.IsArchived = 0 + UNION ALL + SELECT ca.CharacterID, c.ProjectID, ca.Alias AS MatchedName, N'Alias' AS MatchType + FROM dbo.CharacterAliases ca + INNER JOIN dbo.Characters c ON c.CharacterID = ca.CharacterID + WHERE c.IsArchived = 0 + ) rows + INNER JOIN dbo.Characters c ON c.CharacterID = rows.CharacterID + INNER JOIN dbo.Projects p ON p.ProjectID = c.ProjectID + INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = c.ProjectID AND pua.UserID = @UserID AND pua.IsActive = 1 + LEFT JOIN dbo.SceneCharacters sc ON sc.CharacterID = c.CharacterID + LEFT JOIN dbo.Scenes s ON s.SceneID = sc.SceneID AND s.IsArchived = 0 + LEFT JOIN dbo.Chapters ch ON ch.ChapterID = s.ChapterID AND ch.IsArchived = 0 + LEFT JOIN dbo.Books b ON b.BookID = ch.BookID AND b.IsArchived = 0 + WHERE UPPER(LTRIM(RTRIM(rows.MatchedName))) = @NormalisedName COLLATE Latin1_General_100_CI_AI_SC + AND (@UsedScope = N'Library' OR c.ProjectID = @ProjectID) + AND (@BookID IS NULL OR @UsedScope <> N'Book' OR b.BookID = @BookID) + ORDER BY p.ProjectName, b.BookTitle, c.CharacterName; +END; +GO diff --git a/PlotLine/Views/Names/Index.cshtml b/PlotLine/Views/Names/Index.cshtml index 6b7de530..c0872b3f 100644 --- a/PlotLine/Views/Names/Index.cshtml +++ b/PlotLine/Views/Names/Index.cshtml @@ -63,6 +63,7 @@
+
@@ -176,7 +177,7 @@ @foreach (var row in Model.Results) { - + @row.DisplayName
@row.NameType@if (row.IsWordAmbiguous){ · ambiguous word}
@@ -204,9 +205,9 @@
- Previous + Previous Page @filter.Page of @Model.TotalPages - Next + Next
} @@ -226,6 +227,8 @@ }; preset?.addEventListener("change", sync); sync(); + const book=root.querySelector("[name=BookID]"),scope=root.querySelector("[data-name-used-scope]"); + book?.addEventListener("change",()=>scope.value=book.value?"Book":"Project"); })(); } diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index ddb16cd5..154c14c5 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -7,7 +7,7 @@ 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 = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, + new { id = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Book", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, new { id = "relationships", displayName = "Relationships", endpoint = Url.Action("ContextRelationships", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "relationships", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "relationship.focus" } } }; } @@ -55,6 +55,7 @@ @section Scripts { + diff --git a/PlotLine/Views/Writing/_ContextNameIdentity.cshtml b/PlotLine/Views/Writing/_ContextNameIdentity.cshtml new file mode 100644 index 00000000..eff949fb --- /dev/null +++ b/PlotLine/Views/Writing/_ContextNameIdentity.cshtml @@ -0,0 +1,8 @@ +@model PlotLine.Services.Context.ContextNamePanel +@{var entry=Model.Entries.Single();} +

Recorded identity: @entry.Character.CharacterName

+@if(Model.CanEdit){} +
    @foreach(var alias in entry.Aliases){
  • @alias.Alias · recorded alias@if(Model.CanEdit&&!string.Equals(alias.Alias,entry.Character.CharacterName,StringComparison.OrdinalIgnoreCase)){}
  • }
+@if(Model.CanEdit){} +Open full character workspace +
diff --git a/PlotLine/Views/Writing/_ContextNameResults.cshtml b/PlotLine/Views/Writing/_ContextNameResults.cshtml new file mode 100644 index 00000000..3e524607 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextNameResults.cshtml @@ -0,0 +1,14 @@ +@model PlotLine.Services.Context.ContextNamePanel +@{var lib=Model.Library!;var f=lib.Filter;var scope=f.UsedScope=="Book"?lib.Books.FirstOrDefault(b=>b.BookID==f.BookID)?.BookDisplayTitle??"selected book":f.UsedScope=="Library"?"accessible projects":"this project";} +
+ +

@lib.TotalRows.ToString("N0") candidates · Usage in @scope · Page @f.Page of @lib.TotalPages

+@if(!lib.Results.Any()){

No matching library names. Try broader criteria or the established-name lookup.

} +
@foreach(var row in lib.Results){
+
@row.DisplayName@(row.UsedCount>0?$"Already used ({row.UsedCount})":"Unused in scope")
+

@row.NameType @if(row.IsWordAmbiguous){· Ambiguous word} · @row.LocaleDisplayName

+
Profile, related forms and usage
Gender prior
Female @row.FemaleWeight?.ToString("0.###") · Male @row.MaleWeight?.ToString("0.###")
Era profile
@(row.BirthYearFrom.HasValue?$"{row.BirthYearFrom}–{row.BirthYearTo}":"No era profile")
Commonness / confidence
@row.UsageWeight?.ToString("0.###") / @row.Confidence?.ToString("0.###")
Reference source
@(row.SourceType??"Not recorded")
Related forms
@(string.IsNullOrWhiteSpace(row.RelatedForms)?"None recorded":row.RelatedForms)
Recorded use
@(string.IsNullOrWhiteSpace(row.UsedSummary)?"No use recorded in this scope":row.UsedSummary)
+
+
}
+
+
diff --git a/PlotLine/Views/Writing/_ContextNameSuggestions.cshtml b/PlotLine/Views/Writing/_ContextNameSuggestions.cshtml deleted file mode 100644 index 0249f461..00000000 --- a/PlotLine/Views/Writing/_ContextNameSuggestions.cshtml +++ /dev/null @@ -1,6 +0,0 @@ -@model PlotLine.Services.Context.ContextNamePanel -
-

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

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

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

} -
diff --git a/PlotLine/Views/Writing/_ContextNameUsage.cshtml b/PlotLine/Views/Writing/_ContextNameUsage.cshtml new file mode 100644 index 00000000..e77416c9 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextNameUsage.cshtml @@ -0,0 +1,8 @@ +@model IReadOnlyList +
+@if(Model.Count==0){

No matching canonical name or alias use is recorded in this scope.

}else{ +@if(Model.Select(r=>r.CharacterID).Distinct().Count()>1){

This spelling belongs to more than one recorded identity. Shared names can be legitimate; no identities are merged.

} +

Up to 100 distinct use records. Book use is based on recorded scene participation; it does not prove that every character knows this name.

+
    @foreach(var person in Model.GroupBy(r=>r.CharacterID)){var row=person.First();
  • @row.CharacterName · @row.MatchType: @row.MatchedName @row.ProjectName · @string.Join(", ",person.Where(p=>p.BookID.HasValue).Select(p=>p.BookDisplayTitle).Where(s=>!string.IsNullOrWhiteSpace(s)).Distinct()) +
  • }
} +
diff --git a/PlotLine/Views/Writing/_ContextNames.cshtml b/PlotLine/Views/Writing/_ContextNames.cshtml index 67408ad7..7ae83215 100644 --- a/PlotLine/Views/Writing/_ContextNames.cshtml +++ b/PlotLine/Views/Writing/_ContextNames.cshtml @@ -1,18 +1,25 @@ @model WritingContextDisplayViewModel -@{var panel=Model.NamePanel;} -@if(panel==null){

Names reference unavailable. Reopen this tool.

}else{ -
- -

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

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

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

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

Open full Names workspace +@{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
} diff --git a/PlotLine/wwwroot/css/context-workspace.css b/PlotLine/wwwroot/css/context-workspace.css index 53559592..4d71a982 100644 --- a/PlotLine/wwwroot/css/context-workspace.css +++ b/PlotLine/wwwroot/css/context-workspace.css @@ -57,3 +57,9 @@ body:has([data-context-workspace])>.writing-window-bar { flex:none; } [data-context-edit-form] label:has(input[type=checkbox]){flex-direction:row;align-items:center;} [data-context-edit-form] textarea{min-height:9rem;resize:vertical;} [data-context-edit-form] input[type=checkbox]{flex:0 0 auto;} +.context-name-primary,.context-name-filters{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.75rem;align-items:end;margin-block:.6rem;} +[data-context-names] label{display:flex;flex-direction:column;gap:.3rem;min-width:0;}[data-context-names] input,[data-context-names] select{width:100%;min-width:0;max-width:100%;} +.context-name-result{padding:.8rem;border:1px solid var(--plotline-line);border-radius:.5rem;margin-block:.7rem;overflow-wrap:anywhere;} +.context-name-result header{display:flex;gap:.6rem;align-items:center;flex-wrap:wrap;}.context-name-result header strong{flex:1;min-width:8rem;}.context-name-result .writing-context-facts{margin-top:.6rem;} +@container(max-width:650px){.context-name-primary,.context-name-filters{grid-template-columns:repeat(2,minmax(0,1fr));}.context-name-primary>label:first-child{grid-column:1/-1;}} +@container(max-width:400px){.context-name-primary,.context-name-filters{grid-template-columns:minmax(0,1fr);}} diff --git a/PlotLine/wwwroot/js/context-editing.js b/PlotLine/wwwroot/js/context-editing.js index f871c1a4..766950ad 100644 --- a/PlotLine/wwwroot/js/context-editing.js +++ b/PlotLine/wwwroot/js/context-editing.js @@ -5,7 +5,7 @@ function install(html){const doc=new DOMParser().parseFromString(html,'text/html');const form=doc.querySelector('[data-context-edit-form]');if(!form||doc.querySelector('html>head>title')||/{const button=event.target.closest('[data-context-edit],[data-context-relationship-edit]');if(!button||dialog.open)return; - pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const relationship=button.hasAttribute('data-context-relationship-edit');const url=new URL(relationship?'/Writing/Context/EditRelationship':'/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',fragment.dataset.sceneId);if(relationship){url.searchParams.set('relationshipId',button.dataset.relationshipId||'0');url.searchParams.set('mode',button.dataset.contextRelationshipEdit);}else{url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit);} + pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const relationship=button.hasAttribute('data-context-relationship-edit');const url=new URL(relationship?'/Writing/Context/EditRelationship':'/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',fragment.dataset.sceneId||'0');if(relationship){url.searchParams.set('relationshipId',button.dataset.relationshipId||'0');url.searchParams.set('mode',button.dataset.contextRelationshipEdit);}else{url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit);} dialog.querySelector('[data-context-edit-close]').hidden=true;dialog.showModal();dirty=false;busy=true;state();status.textContent='Loading current saved values…';host.replaceChildren();load=new AbortController(); try{const response=await fetch(url,{signal:load.signal,cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error('This correction is unavailable. Check sign-in and editing permission.');install(await response.text());status.textContent='';} catch(error){if(error.name!=='AbortError'){status.textContent=error.message;dialog.querySelector('[data-context-edit-close]').hidden=false;window.PlotDirector?.toast?.error(error.message);}} diff --git a/PlotLine/wwwroot/js/context-names.js b/PlotLine/wwwroot/js/context-names.js new file mode 100644 index 00000000..1ae8d2fe --- /dev/null +++ b/PlotLine/wwwroot/js/context-names.js @@ -0,0 +1,27 @@ +(() => { + '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);} + }; +})(); diff --git a/PlotLine/wwwroot/js/context-tools.js b/PlotLine/wwwroot/js/context-tools.js index b2ea5313..83787000 100644 --- a/PlotLine/wwwroot/js/context-tools.js +++ b/PlotLine/wwwroot/js/context-tools.js @@ -33,23 +33,6 @@ } }; })(); -(() => { - 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);}} - }; -})(); (() => { const saved=new Map(),mounted=new WeakMap(); function apply(node){const q=node.querySelector('[data-relationship-filter]').value.toLocaleLowerCase(),all=node.querySelector('[data-relationship-scope]').value==='all';let count=0;node.querySelectorAll('[data-context-relationship]').forEach(row=>{row.hidden=(!all&&row.dataset.relevant!=='true')||!row.dataset.filterName.toLocaleLowerCase().includes(q);if(!row.hidden)count++;});node.querySelector('[data-relationship-empty]').hidden=count>0;}