From 4cba388de8e1f5225ec325d70627bcfd3758287e Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 26 Nov 2026 20:33:57 +0000 Subject: [PATCH] Refine Names navigation, filters and server sorting with shared character symbols --- Docs/Codex/CharacterAttributes.md | 17 +- Docs/Codex/NamesWorkspace.md | 15 +- .../Browser/character-attribute-icons.cjs | 9 ++ .../Browser/character-attributes.cjs | 17 +- PlotLine.Tests/Browser/context-names.cjs | 4 +- PlotLine.Tests/Browser/names-workspace.cjs | 10 +- .../CharacterQuickAttributesTests.cs | 6 + .../NameVerificationDatabaseTests.cs | 2 +- .../NamesRefinementDatabaseTests.cs | 39 +++++ .../NamesWorkspaceBrowserFixture.cs | 2 +- PlotLine.Tests/Program.cs | 1 + PlotLine.Tests/ToolbarBrowserHost.cs | 2 +- .../CharacterAttributesController.cs | 2 +- .../Controllers/ContextNamesController.cs | 2 +- PlotLine/Controllers/NamesController.cs | 2 +- PlotLine/Data/NameIntelligenceRepository.cs | 1 + PlotLine/Models/NameIntelligenceModels.cs | 2 + PlotLine/Services/CharacterQuickAttributes.cs | 18 ++- PlotLine/Services/RibbonPresentation.cs | 7 +- PlotLine/Sql/334_NamesWorkspaceSorting.sql | 148 ++++++++++++++++++ PlotLine/ViewModels/NameDetailsViewModel.cs | 2 +- .../Views/Shared/_ApplicationShell.cshtml | 2 +- PlotLine/Views/Shared/_NameDetails.cshtml | 2 +- PlotLine/Views/Shared/_NamesWorkspace.cshtml | 5 +- PlotLine/wwwroot/css/character-attributes.css | 8 +- .../wwwroot/js/application-context-menu.js | 2 +- PlotLine/wwwroot/js/character-attributes.js | 4 +- PlotLine/wwwroot/js/names-workspace.js | 13 +- 28 files changed, 305 insertions(+), 39 deletions(-) create mode 100644 PlotLine.Tests/Browser/character-attribute-icons.cjs create mode 100644 PlotLine.Tests/NamesRefinementDatabaseTests.cs create mode 100644 PlotLine/Sql/334_NamesWorkspaceSorting.sql diff --git a/Docs/Codex/CharacterAttributes.md b/Docs/Codex/CharacterAttributes.md index 24c0c1b9..2711c3df 100644 --- a/Docs/Codex/CharacterAttributes.md +++ b/Docs/Codex/CharacterAttributes.md @@ -17,13 +17,15 @@ The directory retains its existing `CharacterCardLayout.ColumnSpan`, full `Defau | Attribute | Icon key | Theme tone | | --- | --- | --- | -| Major | attribute-star | warning (gold intention) | -| Supporting | characters | info (blue intention) | -| Minor | attribute-person | secondary | +| Major (filled) | attribute-star-filled | warning (gold intention) | +| Supporting (half-filled) | attribute-star-half | info (blue intention) | +| Minor (outline) | attribute-star | secondary | | Unclassified / unrecorded / not set | help | secondary | | Living | attribute-heart | success | | Deceased | attribute-flower | data-5 (existing purple theme palette) | -| Recorded sex | attribute-person | secondary | +| Male (canonical system value) | sex-male (Mars) | info | +| Female (canonical system value) | sex-female (Venus) | data-7 (theme rose) | +| Other / custom / recorded legacy sex | sex-other (combined Venus/Mars) | data-5 | | Quick Add included | attribute-pin | primary | | Quick Add excluded | attribute-unpin | secondary | @@ -65,3 +67,10 @@ The editor explicitly supplies classification with an original timestamp. Existi `PlotLine.Tests/Sql/CharacterTypes.sql` runs on a disposable qualification copy and covers no-inference migration, bulk/individual updates, species retention, independent attributes, Undo, editor persistence, old caller preservation and invalid codes. The normal harness checks the vocabulary, snapshot and server-side validation. Character browser fixtures now include Type assignment/Undo through the common UI. The Character Editor concurrency version is sent explicitly as Dapper `DbType.DateTime2`, preserving the `Characters.UpdatedDate datetime2(7)` precision. SQL `datetime` rounding can otherwise produce a false stale-version failure after quick assignment. The isolated real-repository `--character-editor-precision-database` check covers a seven-digit fractional timestamp, a successful ordinary editor save, stale-version rejection and preservation of a newer concurrent biography. Legacy save callers retain the existing opt-in classification behaviour. + + +## UI refinement standard + +Shared group order is Story importance, Life status, Sex, Character Type, Quick Add Bar, on the sidebar, cards and attribute menus. Filled and half-filled stars use the shared ribbon icon `Filled` metadata with compound even-odd SVG geometry; the remaining star is outlined. The same presentation metadata reaches directory icons and the existing context-menu icon catalogue. Custom Sex values retain their IDs and labels; they use the combined symbol without inferring Male/Female from arbitrary labels. Legacy recorded sex uses the shared fallback rather than another group's icon by position. + +Attribute gold/blue/neutral use existing `--pd-warning`, `--pd-info`, `--pd-muted`. Rose/purple data tones mix with theme text for contrast in light/dark palettes; no new hardcoded colour catalogue or wider icon migration is introduced. diff --git a/Docs/Codex/NamesWorkspace.md b/Docs/Codex/NamesWorkspace.md index 5fd6bc22..7324081d 100644 --- a/Docs/Codex/NamesWorkspace.md +++ b/Docs/Codex/NamesWorkspace.md @@ -12,7 +12,7 @@ Migration 325 replaces scene-dependent usage with exact canonical comparison of `_NamesWorkspace`, `_NamesResults`, `_NameDetails`, `NamesWorkspace` and `names-workspace.js` implement the compact results and selected-name panel. Details use existing recognition metadata and the existing association repository only after selection. Catalogue searches retain pagination and never retrieve biographies or per-result occurrence lists. -The main page opts into the existing full-width shell. The selected panel is sticky, with bounded scrolling; narrow containers show details with Back to Results. Main-page interaction state uses session storage scoped to series. Character actions open canonical records in another window, preserving the search. +The main page opts into the existing full-width shell. The selected panel is sticky, with bounded scrolling; narrow containers show details with Back to Results. Main-page interaction state uses session storage scoped to series. Main-page character actions navigate to canonical Details/Editor in the same window; returning restores workspace state. Context actions retain separate-window navigation. Usage icons come from the existing SVG library: primary name uses the shared Character Type icon (including Animal paw), aliases use `name-alias`, available uses `name-available`. Selected details distinguish confirmed associations from textual matches. Explicit paragraph occurrence lookup and AI verification are subsequent phases of this implementation. @@ -26,10 +26,21 @@ No migrations have been applied to Development and no deployment has occurred du ## 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. +The pre-existing Names tab now mounts the same shared workspace. Its adapter only supplies authorised Context endpoints and retains component state keyed by series and pane. 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. ## Query plan stability Authenticated Development acceptance exposed a timeout when a cached catalogue plan was reused across different prefix/default/locale/usage filters on a small cast. Forward-only migration 333 recompiles the final catalogue statement for the current parameters, without changing matching, metadata, ordering or pagination. Migration 325 remains immutable. Qualification now alternates narrow and broad searches, locale/era criteria and assigned/available filters with a two-character cast, in addition to the 500-character fixture. The benchmark restores the latest procedure after measuring historical SQL, so tests do not leave the database on an earlier definition. Context Names state is keyed by series and pane, so switching books within the same series retains the author's search and selection. Requests still use the current authorised Context book; moving to another series uses independent state. + + +## Targeted UI refinements (26 November 2026) + +The shared primary control row includes Clear Filters and Sort order. The search placeholder explains complete names or starting letters; prefix semantics are unchanged. Clear resets search, usage, locale/year, gender prior, classification and minimum usage, then requests page one. It preserves the current project/book, page size and sort. Existing book defaults are reapplied by the normal read service; no saved book profile is written. The action remains outside the collapsible advanced filters. + +Sort codes are `suggested`, `name-asc`, `name-desc`, `common-desc`, `common-asc`. Suggested retains exact matches first, then the selected catalogue profile's usage weight and display name. Commonness uses that existing `UsageWeight`, with unrecorded weights last. All modes have deterministic display-name/ID tie breaks and are applied before SQL pagination. Changing sort returns to page one; searches, Clear and history restoration retain it. + +Migration 334 is required by the existing stored-procedure pagination architecture: sorting only a fetched page would be incorrect, and loading the whole catalogue to sort in application code would regress performance. It adds one optional, validated sort parameter to `GivenName_Search`; earlier numbered migrations remain immutable. No name-matching, occurrence retrieval, AI, allowance, character-data or catalogue-data migration is involved. + +Main details links contain no separate-window or Context bridge attributes. The Context controller explicitly opts its shared details model into those attributes. State includes the actual application/pane scroll host, not merely window scroll, and cached-history returns refresh through the existing workspace without replacing Context or changing manuscript focus. diff --git a/PlotLine.Tests/Browser/character-attribute-icons.cjs b/PlotLine.Tests/Browser/character-attribute-icons.cjs new file mode 100644 index 00000000..071de2ca --- /dev/null +++ b/PlotLine.Tests/Browser/character-attribute-icons.cjs @@ -0,0 +1,9 @@ +const {chromium}=require('playwright'),assert=require('assert/strict'),fs=require('fs'),os=require('os'),path=require('path'); +(async()=>{const installed=process.argv.includes('--installed'),base='http://127.0.0.1:5238',profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-icons-pwa-')):null,b=installed?null:await chromium.launch(),c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1200}}):await b.newContext({viewport:{width:1920,height:1200}});let p=installed?c.pages()[0]:await c.newPage(),cdp;try{ + if(installed){await p.goto(base+'/fixture?page=calendar-test');cdp=await c.browser().newBrowserCDPSession();await cdp.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:p.url()});await cdp.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});const opened=c.waitForEvent('page');await cdp.send('PWA.launch',{manifestId:base+'/Projects',url:p.url()});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));} + const groups=await (await p.request.get(base+'/character-attribute-definitions-fixture')).json(),records=Array.from({length:48},(_,i)=>({id:i+1,name:`Fixture character ${i+1}`,version:'v1',values:{importance:['10','6','2',''][i%4],life:'',sex:['1','2','3','','legacy:Recorded legacy sex'][i%5],type:'unclassified',quickAdd:'0'}}));await p.route('**/CharacterAttributes/Directory?*',r=>r.fulfill({json:{canEdit:true,groups,characters:records}}));await p.goto(base+'/character-attributes-fixture?count=48');await p.locator('[data-attribute-indicators] svg').first().waitFor();assert.deepEqual(await p.locator('[data-attribute-groups] summary').allTextContents(),['Story importance','Life status','Sex','Character Type','Quick Add Bar']); + assert.equal(await p.locator('[data-attribute="importance"][data-value="10"] path').getAttribute('fill'),'currentColor');assert.equal(await p.locator('[data-attribute="importance"][data-value="6"] path').getAttribute('fill-rule'),'evenodd');assert.equal(await p.locator('[data-attribute="importance"][data-value="2"] path').getAttribute('fill'),'none'); + const out='/tmp/pd-ui-refinements';fs.mkdirSync(out,{recursive:true});const contrast=[]; + for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await p.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);const ratios=await p.evaluate(()=>{const canvas=document.createElement('canvas');canvas.width=canvas.height=1;const context=canvas.getContext('2d');function luminance(color){context.clearRect(0,0,1,1);context.fillStyle=color;context.fillRect(0,0,1,1);const rgb=[...context.getImageData(0,0,1,1).data].slice(0,3).map(x=>x/255).map(x=>x<=.04045?x/12.92:((x+.055)/1.055)**2.4);return .2126*rgb[0]+.7152*rgb[1]+.0722*rgb[2];}const bg=luminance(getComputedStyle(document.querySelector('[data-attribute-sidebar]')).backgroundColor);return [...document.querySelectorAll('[data-attribute="importance"] svg,[data-attribute="sex"] svg')].map(svg=>{const fg=luminance(getComputedStyle(svg).color);return (Math.max(fg,bg)+.05)/(Math.min(fg,bg)+.05)});});assert(ratios.every(x=>x>=3),theme+' icon contrast '+ratios);contrast.push({theme,minimumIconContrast:Math.min(...ratios)});for(const button of await p.getByRole('button',{name:/Dismiss .* notification/}).all())await button.click().catch(()=>{});await p.screenshot({path:`${out}/icons-${installed?'pwa':'browser'}-${theme}.png`});} + const card=p.locator('.character-card').first(),box=await card.boundingBox();await card.click({button:'right',position:{x:box.width-8,y:box.height-8}});const menus=await p.getByRole('menuitem').allTextContents();assert(menus.indexOf('Story importance'){});await c.close();if(b)await b.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e.name+': '+e.message.split('Call log:')[0]);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/character-attributes.cjs b/PlotLine.Tests/Browser/character-attributes.cjs index 6bb4fd94..96a4bab0 100644 --- a/PlotLine.Tests/Browser/character-attributes.cjs +++ b/PlotLine.Tests/Browser/character-attributes.cjs @@ -12,12 +12,19 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require( const page=await newPage(),errors=[];console.log('ACCEPTANCE',installed?'installed':'browser',count);page.on('pageerror',e=>errors.push(e.message)); const groups=await (await page.request.get('http://127.0.0.1:5238/character-attribute-definitions-fixture')).json(); - let clock=0,requests=[],undo=new Map(),records=Array.from({length:count},(_,i)=>({id:i+1,name:`Fixture character ${String(i+1).padStart(3,'0')}`,version:`v${clock++}`,values:{type:'unclassified',importance:(i+1)%3===0?'10':(i+1)%3===1?'6':'2',life:'',sex:'',quickAdd:'0'}})); + let clock=0,requests=[],undo=new Map(),records=Array.from({length:count},(_,i)=>({id:i+1,name:`Fixture character ${String(i+1).padStart(3,'0')}`,version:`v${clock++}`,values:{type:'unclassified',importance:(i+1)%3===0?'10':(i+1)%3===1?'6':'2',life:'',sex:i===0?'legacy:Recorded custom sex':i%4===1?'1':i%4===2?'2':i%4===3?'3':'',quickAdd:'0'}})); await page.route('**/CharacterAttributes/Directory?*',route=>route.fulfill({json:{canEdit:true,groups,characters:records}})); await page.route('**/CharacterAttributes/Assign',async route=>{const input=route.request().postDataJSON();requests.push(input);assert(route.request().headers().requestverificationtoken);const previous=[],changed=[];for(const c of input.changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Characters changed in another window.'}});if(r.values[input.attribute]!==c.value){previous.push(structuredClone(r));r.values[input.attribute]=c.value;r.version=`v${clock++}`;changed.push(r);}}const token=`undo-${clock}`;undo.set(token,{previous,versions:changed.map(r=>[r.id,r.version])});await route.fulfill({json:{saved:true,characters:changed,undoToken:token}});}); await page.route('**/CharacterAttributes/Undo',async route=>{const token=route.request().postDataJSON().token,state=undo.get(token);assert(state);if(state.versions.some(([id,version])=>records.find(r=>r.id===id).version!==version))return route.fulfill({status:409,json:{message:'Characters changed in another window.'}});const changed=state.previous.map(old=>{const r=records.find(r=>r.id===old.id);r.values=old.values;r.version=`v${clock++}`;return r;});await route.fulfill({json:{saved:true,characters:changed}});}); + assert.deepEqual(groups.map(g=>g.id),['importance','life','sex','type','quickAdd']); const start=Date.now();await page.goto(`http://127.0.0.1:5238/character-attributes-fixture?count=${count}`);await page.locator('[data-attribute="importance"]').first().waitFor();const load=Date.now()-start; + const expose=async node=>{await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^="Dismiss"]').forEach(b=>b.click()));await node.scrollIntoViewIfNeeded();}; const card=id=>page.locator(`.character-card[data-drag-id="${id}"]`),value=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`); + assert.deepEqual(await card(1).locator('[data-attribute-indicators]>span').evaluateAll(nodes=>nodes.map(n=>n.title.split(':')[0])),['Story importance','Life status','Sex','Character Type','Quick Add Bar']); + assert.equal(await card(1).locator('[title="Sex: Recorded custom sex"] path').getAttribute('d'),groups.find(g=>g.id==='sex').fallback.path); + // Native mouse drag with both endpoints visible: scrolling a sticky target through + // dragTo can scroll the page after locating the source and move its handle away. + async function reverse(id,a,v){await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^="Dismiss"]').forEach(b=>b.click()));const source=card(id).locator('[data-character-drag]'),target=value(a,v);await source.evaluate(n=>n.scrollIntoView({block:'start',inline:'nearest'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));await target.evaluate(n=>{const host=n.closest('[data-attribute-sidebar]'),r=n.getBoundingClientRect(),h=host.getBoundingClientRect();const bottom=Math.min(h.bottom,innerHeight),top=Math.max(h.top,0);if(r.bottom>bottom-8)host.scrollTop+=r.bottom-bottom+8;if(r.topg.id==='type')){ await value('type','person').locator('button').first().dragTo(card(1));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Person"]')); - await card(2).locator('[data-character-drag]').dragTo(value('type','artificial'));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Artificial being"]')); + await reverse(2,'type','artificial');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Artificial being"]')); await card(1).locator('[data-character-select]').check();await card(2).locator('[data-character-select]').check(); await value('type','animal').getByRole('button',{name:/Assign/}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Animal"]')); await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Artificial being"]'));assert.equal(records[0].values.type,'person'); @@ -44,7 +51,7 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require( await value('type','animal').locator('button').first().dragTo(card(1));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Animal"]'));assert.equal(await value('type','animal').locator('button').first().getAttribute('aria-pressed'),'false'); if(count===100){fs.mkdirSync('/tmp/pd-character-types',{recursive:true});await page.screenshot({path:`/tmp/pd-character-types/${installed?'pwa':'browser'}-assigned.png`});} await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Unclassified"]')); - await card(2).locator('[data-character-drag]').dragTo(value('type','animal'));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Animal"]'));await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Unclassified"]')); + await reverse(2,'type','animal');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Animal"]'));await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Unclassified"]')); await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'Character Type',exact:true}).hover();assert.equal(await page.getByRole('menuitemradio',{name:'Unclassified',exact:true}).getAttribute('aria-checked'),'true'); if(count===100)await page.screenshot({path:`/tmp/pd-character-types/${installed?'pwa':'browser'}-context-menu.png`}); await page.getByRole('menuitemradio',{name:'Animal',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Animal"]'));await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Unclassified"]')); @@ -52,10 +59,10 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require( } assert.equal(await page.locator('.character-card').count(),count);const biography=await card(1).locator('.visual-card-heading p.muted').textContent();assert(biography.includes('Complete biography for character 1'));const heights=await page.locator('.character-card').evaluateAll(ns=>ns.slice(0,9).map(n=>n.getBoundingClientRect().height));assert(new Set(heights.map(Math.round)).size>1); await value('importance','10').locator('button').first().dragTo(card(1));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [data-attribute-indicators]').textContent===''&&document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Major"]'));assert.equal(records[0].values.importance,'10'); - await card(2).locator('[data-character-drag]').dragTo(value('importance','6'));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]'));assert.equal(records[1].values.importance,'6'); + await reverse(2,'importance','6');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]'));assert.equal(records[1].values.importance,'6'); await card(1).locator('[data-character-select]').check();await card(2).locator('[data-character-select]').check();await value('importance','2').getByRole('button',{name:/Assign/}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2); await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Major"]'));assert.equal(records[1].values.importance,'6'); - await card(1).locator('[data-character-drag]').dragTo(value('importance','2'));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2);await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]')); + await reverse(1,'importance','2');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2);await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]')); await card(1).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'2 characters selected',exact:true}).waitFor();await page.getByRole('menuitem',{name:'Life status',exact:true}).hover();await page.getByRole('menuitemradio',{name:'Living',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Life status: Living"]'));assert.equal(requests.at(-1).changes.length,2); await page.locator('[data-clear-selection]').click(); // Modifier selection follows displayed order and does not navigate character links. diff --git a/PlotLine.Tests/Browser/context-names.cjs b/PlotLine.Tests/Browser/context-names.cjs index 96a710e4..f6f71489 100644 --- a/PlotLine.Tests/Browser/context-names.cjs +++ b/PlotLine.Tests/Browser/context-names.cjs @@ -9,8 +9,8 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=r 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);assert.equal(await first.locator('[data-context-workspace-target]').first().getAttribute('data-context-narrative'),'author');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 first.locator('[data-name-select]').first().click();await first.locator('[data-name-details-fragment]').waitFor();assert.equal(await first.locator('.names-association').count(),2);assert.equal(await first.locator('[data-context-workspace-target]').first().getAttribute('data-context-narrative'),'author');assert.equal(await first.getByRole('link',{name:'View Character',exact:true}).first().getAttribute('target'),'_blank');assert.equal(await first.getByRole('link',{name:'Edit Character',exact:true}).first().getAttribute('target'),'_blank');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');await first.locator('[name=SortOrder]').selectOption('name-desc');await pane(1).locator('[name=SortOrder]').selectOption('name-asc');await page.waitForTimeout(200);await pane(1).locator('[data-names-clear]').click();await page.waitForTimeout(200);assert.equal(await first.locator('[name=SortOrder]').inputValue(),'name-desc');assert.equal(await first.locator('[name=Search]').inputValue(),'George');assert.equal(await pane(1).locator('[name=Search]').inputValue(),'');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,[]); diff --git a/PlotLine.Tests/Browser/names-workspace.cjs b/PlotLine.Tests/Browser/names-workspace.cjs index c454b05b..0421417b 100644 --- a/PlotLine.Tests/Browser/names-workspace.cjs +++ b/PlotLine.Tests/Browser/names-workspace.cjs @@ -16,6 +16,14 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=r fs.mkdirSync('/tmp/pd-names-workspace',{recursive:true});const measurements=[]; for(const width of [1280,1920,2560,3840,768,390]){await page.setViewportSize({width,height:1080});const m=await page.evaluate(()=>({width:innerWidth,overflow:document.documentElement.scrollWidth>innerWidth,workspace:document.querySelector('[data-names-workspace]').getBoundingClientRect().width,rowHeight:document.querySelector('.names-result').getBoundingClientRect().height,details:!!document.querySelector('[data-names-details]').getBoundingClientRect().width}));assert(!m.overflow);assert(m.rowHeight<=65);measurements.push(m);if(width===2560||width===390)await page.screenshot({path:`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-${width}.png`});if(width===390){await page.locator('[data-names-back]').click();assert(await page.locator('[data-names-details]').isHidden());await page.locator('[data-name-select]').first().click();await page.locator('[data-name-details-fragment]').waitFor();assert(await page.locator('[data-names-results-host]').isHidden());}} await page.setViewportSize({width:1920,height:1080});for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);await page.screenshot({path:`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-${theme}.png`});} - await page.reload();await page.locator('[data-name-details-fragment]').waitFor();assert.equal(await page.locator('[name=Search]').inputValue(),'George');assert.equal(await page.locator('[data-name-select][aria-pressed=true]').count(),1);assert.deepEqual(errors,[]);fs.writeFileSync(`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-measurements.json`,JSON.stringify({measurements,calls},null,2));console.log('PASS Names compact results, deferred canonical details, animal/alias associations, navigation, state, themes, wide/narrow layouts',calls); + await page.reload();await page.locator('[data-name-details-fragment]').waitFor();assert.equal(await page.locator('[name=Search]').inputValue(),'George');assert.equal(await page.locator('[data-name-select][aria-pressed=true]').count(),1);assert.deepEqual(errors,[]); + assert.equal(await page.locator('.names-association a').first().getAttribute('target'),null);assert.equal(await page.locator('.names-association a').nth(1).getAttribute('target'),null); + await page.locator('[data-names-filters]').evaluate(n=>n.open=true);await page.locator('[name=PageSize]').selectOption('50');await page.locator('[name=BookID]').selectOption('13');await page.locator('[name=LocaleCode]').selectOption('fr-FR');await page.locator('[name=UsedOnly]').selectOption('false');await page.locator('[name=SortOrder]').selectOption('name-desc'); + await page.waitForFunction(()=>JSON.parse(document.querySelector('[data-names-applied]').textContent).SortOrder==='name-desc');await page.locator('[data-name-page="2"]').click();await page.waitForFunction(()=>document.querySelector('[data-names-results]').dataset.page==='2');await page.locator('[data-name-select]').first().click();await page.waitForFunction(()=>document.querySelector('[data-name-details-fragment] h2')?.textContent==='George 51'); + const scroll=await page.evaluate(()=>{let node=document.querySelector('[data-names-workspace]').parentElement;for(;node;node=node.parentElement)if(/auto|scroll/.test(getComputedStyle(node).overflowY)&&node.scrollHeight>node.clientHeight){node.scrollTop=450;return node.scrollTop}document.scrollingElement.scrollTop=450;return document.scrollingElement.scrollTop});assert(scroll>100); + const pages=page.context().pages().length;await page.route('**/Characters/Details/501',r=>r.fulfill({contentType:'text/html',body:'

Canonical Character Details

'}));await page.route('**/Characters/Edit/501',r=>r.fulfill({contentType:'text/html',body:'

Canonical Character Editor

'})); + for(const action of ['View Character','Edit Character']){await Promise.all([page.waitForURL(action==='View Character'?'**/Characters/Details/501':'**/Characters/Edit/501'),page.getByRole('link',{name:action,exact:true}).first().click()]);assert.equal(page.context().pages().length,pages);await page.goBack();await page.waitForFunction(()=>document.querySelector('[data-name-details-fragment] h2')?.textContent==='George 51');assert.equal(await page.locator('[name=SortOrder]').inputValue(),'name-desc');assert.equal(await page.locator('[name=Page]').inputValue(),'2');assert.equal(await page.locator('[name=PageSize]').inputValue(),'50');assert.equal(await page.locator('[name=BookID]').inputValue(),'13');assert.equal(await page.locator('[name=LocaleCode]').inputValue(),'fr-FR');await page.waitForFunction(expected=>{let n=document.querySelector('[data-names-workspace]').parentElement;for(;n;n=n.parentElement)if(/auto|scroll/.test(getComputedStyle(n).overflowY)&&n.scrollHeight>n.clientHeight)return Math.abs(n.scrollTop-expected)<3;return Math.abs(document.scrollingElement.scrollTop-expected)<3},scroll);} + for(const expanded of [false,true]){await page.locator('[data-names-filters]').evaluate((n,open)=>n.open=open,expanded);await page.locator('[name=Search]').fill('R');await page.locator('[data-names-clear]').click();await page.waitForFunction(()=>{const f=JSON.parse(document.querySelector('[data-names-applied]').textContent);return !f.Search&&f.Page===1});assert.equal(await page.locator('[name=Search]').inputValue(),'');assert.equal(await page.locator('[name=UsedOnly]').inputValue(),'');assert.equal(await page.locator('[name=LocaleCode]').inputValue(),'');assert.equal(await page.locator('[name=PageSize]').inputValue(),'50');assert.equal(await page.locator('[name=BookID]').inputValue(),'13');assert.equal(await page.locator('[name=SortOrder]').inputValue(),'name-desc');} + fs.writeFileSync(`/tmp/pd-names-workspace/${installed?'pwa':'browser'}-measurements.json`,JSON.stringify({measurements,calls},null,2));console.log('PASS Names compact results, deferred canonical details, animal/alias associations, navigation, state, themes, wide/narrow layouts',calls); }finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();} })().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/CharacterQuickAttributesTests.cs b/PlotLine.Tests/CharacterQuickAttributesTests.cs index a421a158..a79db844 100644 --- a/PlotLine.Tests/CharacterQuickAttributesTests.cs +++ b/PlotLine.Tests/CharacterQuickAttributesTests.cs @@ -11,6 +11,12 @@ internal static class CharacterQuickAttributesTests void Check(bool value,string label){if(!value)throw new Exception(label);Console.WriteLine("PASS character quick attributes: "+label);} var definitions=CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=17,SexName="Recorded custom value"}]); Check(definitions.Single(g=>g.Id=="sex").Values.Any(v=>v.Value=="17"&&v.Label=="Recorded custom value"),"custom catalogue values remain available without binary assumptions"); + Check(definitions.Select(g=>g.Id).SequenceEqual(new[]{"importance","life","sex","type","quickAdd"}),"shared group order is importance, life, sex, type, Quick Add"); + var importance=definitions.Single(g=>g.Id=="importance"); + Check(importance.Values.Select(v=>v.Icon).SequenceEqual(new[]{"attribute-star-filled","attribute-star-half","attribute-star","help"}),"importance uses a related filled/half/outline/unknown family"); + Check(ApplicationRibbon.Icon("attribute-star-filled").Filled&&ApplicationRibbon.Icon("attribute-star-half").Filled&&!ApplicationRibbon.Icon("attribute-star").Filled,"shared icon library supplies filled geometry without colour-only meaning"); + var sex=CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male",IsSystem=true},new(){CharacterSexValueID=2,SexName="Female",IsSystem=true},new(){CharacterSexValueID=3,SexName="Other",IsSystem=true},new(){CharacterSexValueID=4,SexName="Recorded custom sex"}]).Single(g=>g.Id=="sex"); + Check(sex.Values.Select(v=>v.Icon).SequenceEqual(new[]{"help","sex-male","sex-female","sex-other","sex-other"})&&sex.RecordedFallback?.Icon=="sex-other","canonical and custom/legacy sex symbols preserve catalogue values and distinct shapes"); Check(CharacterTypes.Values.Select(v=>v.Value).Distinct().Count()==6 && !CharacterTypes.IsValid("human"),"six stable type codes reject invented classifications"); Check(new Character().CharacterTypeCode=="unclassified", "new/legacy projections remain Unclassified without inference"); Check(CharacterTypes.Definition("animal").Icon=="attribute-paw", "animal associations reuse the shared paw icon"); diff --git a/PlotLine.Tests/NameVerificationDatabaseTests.cs b/PlotLine.Tests/NameVerificationDatabaseTests.cs index 16d0945d..52614cbf 100644 --- a/PlotLine.Tests/NameVerificationDatabaseTests.cs +++ b/PlotLine.Tests/NameVerificationDatabaseTests.cs @@ -77,7 +77,7 @@ internal static class NameVerificationDatabaseTests await Measure("initialResults",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});await Measure("catalogueSearch",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("selectedMetadata",async()=>{await catalogue.RecogniseAsync("GEORGE",null,null);});await Measure("characterAssociations",async()=>{await catalogue.ListUsedDecorationsAsync(user,project,null,"GEORGE","Project");});await Measure("localCandidateSearch",async()=>{await manuscripts.Search(user,project,"Rose");});await Measure("verificationCacheRead",async()=>{await service.Read(user,project,"Rose");}); var sqlRoot=Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,"../../../../PlotLine/Sql")); async Task Apply(string file){foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(Path.Combine(sqlRoot,file)),@"^GO\s*$",System.Text.RegularExpressions.RegexOptions.Multiline|System.Text.RegularExpressions.RegexOptions.IgnoreCase)){if(!string.IsNullOrWhiteSpace(batch))await db.ExecuteAsync(batch);}} - try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("initialResultsBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});}finally{await Apply("333_NameSearchPlanStability.sql");} + try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await db.QueryAsync("dbo.GivenName_Search",new{UserID=user,ProjectID=project,Search="Ge",PageSize=25},commandType:CommandType.StoredProcedure);});await Measure("initialResultsBefore299",async()=>{await db.QueryAsync("dbo.GivenName_Search",new{UserID=user,ProjectID=project,PageSize=25},commandType:CommandType.StoredProcedure);});}finally{await Apply("334_NamesWorkspaceSorting.sql");} Console.WriteLine("PERFORMANCE synthetic qualification, 500 characters / 5009 paragraphs, median milliseconds "+JsonSerializer.Serialize(measurements)); await db.ExecuteAsync("UPDATE dbo.Characters SET IsArchived=1 WHERE ProjectID=@ProjectID AND CharacterName NOT IN(N'George',N'Hamish')",new{ProjectID=project}); foreach(var filter in new NameSearchFilter[]{new(){ProjectID=project,Search="George"},new(){ProjectID=project},new(){ProjectID=project,LocaleCode="US",BirthYear=1950,NameType="Canonical"},new(){ProjectID=project,UsedOnly=true},new(){ProjectID=project,UsedOnly=false},new(){ProjectID=project,Search="Ge"},new(){ProjectID=project}}){var clock=Stopwatch.StartNew();await catalogue.SearchAsync(user,filter);Check(clock.Elapsed(await File.ReadAllTextAsync(path),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!; + if(!settings.Database.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal))throw new Exception("Disposable database required"); + var cs=new SqlConnectionStringBuilder{DataSource=settings.Server,InitialCatalog=settings.Database,UserID="sa",Password=settings.Password,Encrypt=true,TrustServerCertificate=true}.ConnectionString; + await using var db=new SqlConnection(cs);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!=settings.Database)throw new Exception("Database mismatch"); + var scope=await db.QueryFirstAsync("SELECT TOP(1) a.ProjectID,a.UserID FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.IsActive=1 AND a.AccessRole=N'Owner' AND p.IsArchived=0 ORDER BY a.ProjectID"); + var factory=new Factory(cs);var catalogue=new NameIntelligenceRepository(factory);var text=new NameManuscriptRepository(factory);var sqlRoot=Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,"../../../../PlotLine/Sql")); + async Task Apply(string file){foreach(var batch in Regex.Split(await File.ReadAllTextAsync(Path.Combine(sqlRoot,file)),@"^GO\s*$",RegexOptions.Multiline|RegexOptions.IgnoreCase))if(!string.IsNullOrWhiteSpace(batch))await db.ExecuteAsync(batch);} + void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Names refinements database: "+message);} + async Task> All(string sort,int size=25){var list=new List();for(var page=1;page<=100;page++){var rows=await catalogue.SearchAsync(scope.UserID,new(){ProjectID=scope.ProjectID,Search="R",SortOrder=sort,Page=page,PageSize=size});list.AddRange(rows);if(rows.Count==0||list.Count>=rows[0].TotalRows)return list;}throw new Exception("Unbounded test catalogue");} + var clock=Stopwatch.StartNew();var beforeText=await text.Search(scope.UserID,scope.ProjectID,"Rose");var beforeMs=clock.Elapsed.TotalMilliseconds; + List old; + try{await Apply("333_NameSearchPlanStability.sql");old=(await db.QueryAsync("dbo.GivenName_Search",new{scope.UserID,scope.ProjectID,Search="Rose",PageSize=100},commandType:CommandType.StoredProcedure)).ToList();}finally{await Apply("334_NamesWorkspaceSorting.sql");} + var suggested=await catalogue.SearchAsync(scope.UserID,new(){ProjectID=scope.ProjectID,Search="Rose",SortOrder="suggested",PageSize=100}); + Check(old.Select(r=>(r.DisplayName,r.UsageWeight)).SequenceEqual(suggested.Select(r=>(r.DisplayName,r.UsageWeight))),"Suggested retains exact-match, usage-weight and display-name ranking"); + var asc=await All("name-asc");var desc=await All("name-desc");Check(asc.Count>25&&asc.Count==desc.Count&&asc.Select(r=>r.GivenNameID).ToHashSet().SetEquals(desc.Select(r=>r.GivenNameID)),"A–Z and Z–A cover the complete filtered set across pages"); + Check(asc.First().DisplayName==desc.Last().DisplayName&&asc.Last().DisplayName==desc.First().DisplayName,"name direction reverses global extremes rather than sorting one page"); + Check(asc.Select(r=>r.GivenNameID).SequenceEqual((await All("name-asc",100)).Select(r=>r.GivenNameID)),"pagination size does not change the complete ordered sequence"); + foreach(var order in new[]{"common-desc","common-asc"}){var rows=await All(order);var weights=rows.Where(r=>r.UsageWeight.HasValue).Select(r=>r.UsageWeight!.Value).ToArray();Check(weights.SequenceEqual(order=="common-desc"?weights.OrderByDescending(x=>x):weights.OrderBy(x=>x)),order+" uses selected catalogue commonness across page boundaries");Check(rows.SkipWhile(r=>r.UsageWeight.HasValue).All(r=>!r.UsageWeight.HasValue),"unrecorded usage is last, not falsely classified as rare");Check(rows.Select(r=>r.GivenNameID).SequenceEqual((await All(order)).Select(r=>r.GivenNameID)),"ties are deterministic for "+order);} + try{await db.QueryAsync("dbo.GivenName_Search",new{scope.UserID,scope.ProjectID,SortOrder="random"},commandType:CommandType.StoredProcedure);throw new Exception("Invalid sort accepted");}catch(SqlException error)when(error.Number==51012){} + Check(!(await catalogue.SearchAsync(int.MinValue,new(){ProjectID=scope.ProjectID,SortOrder="name-desc"})).Any(),"sorting does not widen project authorisation"); + clock.Restart();var afterText=await text.Search(scope.UserID,scope.ProjectID,"Rose");var afterMs=clock.Elapsed.TotalMilliseconds;Check(beforeText.TextualMatches==afterText.TextualMatches&&beforeText.Scope.Fingerprint==afterText.Scope.Fingerprint&&beforeText.Complete==afterText.Complete,"textual search results, scope and completeness remain unchanged"); + Console.WriteLine("PERFORMANCE unchanged textual search milliseconds "+JsonSerializer.Serialize(new{before=beforeMs,after=afterMs,matches=afterText.TextualMatches})); + } + private sealed record Settings(string Server,string Database,string Password); + private sealed record Scope(int ProjectID,int UserID); + private sealed class Factory(string cs):ISqlConnectionFactory{public IDbConnection CreateConnection()=>new SqlConnection(cs);} +} diff --git a/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs b/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs index d5722a60..515c2d9d 100644 --- a/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs +++ b/PlotLine.Tests/NamesWorkspaceBrowserFixture.cs @@ -18,7 +18,7 @@ internal static class NamesWorkspaceBrowserFixture var library=ContextNamesBrowserFixture.Panel(f).Library!; var name=context.Request.Query["name"].ToString(); object model=part=="details"?new NameDetailsViewModel(7,name,new(){Recognised=true,Name=new(){DisplayName=name,NameType="Canonical",Notes="Retained catalogue metadata"}},[new(){CharacterID=501,CharacterName="George",CharacterTypeCode="animal",Species="Cat",CharacterImportance=10,MatchType="Character"},new(){CharacterID=502,CharacterName="Hamish",CharacterTypeCode="animal",Species="Dog",CharacterImportance=6,MatchType="Alias"}]):library; - if(model is NameDetailsViewModel details){var associations=name.StartsWith("George",StringComparison.OrdinalIgnoreCase)?details.Associations:[];model=details with{Associations=associations,Verification=context.Request.Query["verified"]=="true"?NameVerificationBrowserFixture.Result(name,context.Request.Query["outdated"]=="true",name=="NoSuchSyntheticName",context.Request.Query["interrupted"]=="true"):null};} + if(model is NameDetailsViewModel details){var associations=name.StartsWith("George",StringComparison.OrdinalIgnoreCase)?details.Associations:[];model=details with{ContextNavigation=context.Request.Query.ContainsKey("contextBookId"),Associations=associations,Verification=context.Request.Query["verified"]=="true"?NameVerificationBrowserFixture.Result(name,context.Request.Query["outdated"]=="true",name=="NoSuchSyntheticName",context.Request.Query["interrupted"]=="true"):null};} var path=part switch{"details"=>"/Views/Shared/_NameDetails.cshtml","results"=>"/Views/Shared/_NamesResults.cshtml",_=>"/Views/Names/Index.cshtml"}; var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,path,part=="page"); using var writer=new StringWriter();await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 77150f07..eefbb470 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -191,6 +191,7 @@ if(args.Contains("--character-workspace-database")){await CharacterWorkspaceData if(args.Contains("--character-workspace")){await CharacterWorkspaceTests.Run();return;} if(args.Contains("--context-family")){ContextFamilyTests.Run();return;} if(args.Contains("--context-lenses")){await ContextRelationshipLensTests.Run();return;} +if(args.Contains("--names-refinement-database")){await NamesRefinementDatabaseTests.Run(args.Last());return;} if(args.Contains("--character-editor-precision-database")){await CharacterEditorPrecisionDatabaseTests.Run(args.Last());return;} if(args.Contains("--name-verification-database")){await NameVerificationDatabaseTests.Run(args.Last());return;} if(args.Contains("--name-verification")){await NameVerificationTests.Run();return;} diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index c654ee96..02e69877 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -268,7 +268,7 @@ internal static class ToolbarBrowserHost await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,id); await RenderFullAsync(context,"Scenes","Edit",model); }).WithOrder(-1); - app.MapGet("/character-attribute-definitions-fixture",()=>Results.Json(CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male"},new(){CharacterSexValueID=2,SexName="Female"},new(){CharacterSexValueID=3,SexName="Custom recorded sex"}]).Select(g=>new{g.Id,g.Label,values=g.Values.Select(v=>new{v.Value,v.Label,v.Icon,v.Tone,path=ApplicationRibbon.Icon(v.Icon).IconPath})}))); + app.MapGet("/character-attribute-definitions-fixture",()=>Results.Json(CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male",IsSystem=true},new(){CharacterSexValueID=2,SexName="Female",IsSystem=true},new(){CharacterSexValueID=3,SexName="Custom recorded sex"}]).Select(g=>new{g.Id,g.Label,values=g.Values.Select(CharacterQuickAttributes.Presentation),fallback=g.RecordedFallback is {} fallback?CharacterQuickAttributes.Presentation(fallback):null}))); app.MapGet("/character-attributes-fixture",async (HttpContext context)=>{ var count=int.TryParse(context.Request.Query["count"],out var n)?Math.Clamp(n,1,500):10; await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Character attribute acceptance fixture",AccessRole="Owner"},Characters=Enumerable.Range(1,count).Select(i=>new Character{CharacterID=i,ProjectID=7,CharacterName=$"Fixture character {i:D3}",CharacterImportance=i%3==0?10:i%3==1?6:2,DefaultDescription=string.Join(" ",Enumerable.Repeat($"Complete biography for character {i}: remembered history, motivations and relationships.",i%9+1))}).ToArray()}); diff --git a/PlotLine/Controllers/CharacterAttributesController.cs b/PlotLine/Controllers/CharacterAttributesController.cs index 83bd9549..d6c74f94 100644 --- a/PlotLine/Controllers/CharacterAttributesController.cs +++ b/PlotLine/Controllers/CharacterAttributesController.cs @@ -25,7 +25,7 @@ public sealed class CharacterAttributesController(IProjectRepository projects,IC var definitions=CharacterQuickAttributes.Definitions(owner.HasValue?await characters.ListSexValuesAsync(owner.Value):[]); using var db=connections.CreateConnection(); var rows=await db.QueryAsync("dbo.Character_QuickAttributes_Read",new {ProjectID=projectId,UserID=author},commandType:CommandType.StoredProcedure); - return Json(new {canEdit=ContextEditPolicy.CanEdit(project),groups=definitions.Select(g=>new {g.Id,g.Label,values=g.Values.Select(v=>new {v.Value,v.Label,v.Tone,v.Icon,path=ApplicationRibbon.Icon(v.Icon).IconPath})}),characters=rows.Select(CharacterQuickAttributes.Snapshot)}); + return Json(new {canEdit=ContextEditPolicy.CanEdit(project),groups=definitions.Select(g=>new {g.Id,g.Label,values=g.Values.Select(CharacterQuickAttributes.Presentation),fallback=g.RecordedFallback is {} fallback?CharacterQuickAttributes.Presentation(fallback):null}),characters=rows.Select(CharacterQuickAttributes.Snapshot)}); } public sealed record UndoChange(int Id,string Value,string? Sex,string Version); diff --git a/PlotLine/Controllers/ContextNamesController.cs b/PlotLine/Controllers/ContextNamesController.cs index 5271bf96..393e33d9 100644 --- a/PlotLine/Controllers/ContextNamesController.cs +++ b/PlotLine/Controllers/ContextNamesController.cs @@ -16,7 +16,7 @@ public sealed class ContextNamesController(ContextNames names,IWordCompanionRepo 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();} + 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 with {ContextNavigation=true});}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/Controllers/NamesController.cs b/PlotLine/Controllers/NamesController.cs index 1083c4f9..f6bd1459 100644 --- a/PlotLine/Controllers/NamesController.cs +++ b/PlotLine/Controllers/NamesController.cs @@ -10,7 +10,7 @@ public sealed class NamesController(INameIntelligenceService names, NamesWorkspa { public async Task Index([FromQuery] NameSearchFilter filter, CancellationToken cancellationToken) { - if (filter.ProjectID <= 0) + if (!ModelState.IsValid || filter.ProjectID <= 0) { return BadRequest("ProjectID is required."); } diff --git a/PlotLine/Data/NameIntelligenceRepository.cs b/PlotLine/Data/NameIntelligenceRepository.cs index a235df45..047c1a54 100644 --- a/PlotLine/Data/NameIntelligenceRepository.cs +++ b/PlotLine/Data/NameIntelligenceRepository.cs @@ -128,6 +128,7 @@ public sealed class NameIntelligenceRepository(ISqlConnectionFactory connectionF filter.MinimumUsage, filter.UsedScope, filter.UsedOnly, + filter.SortOrder, filter.Page, filter.PageSize }, diff --git a/PlotLine/Models/NameIntelligenceModels.cs b/PlotLine/Models/NameIntelligenceModels.cs index d293dc94..fd7a5edc 100644 --- a/PlotLine/Models/NameIntelligenceModels.cs +++ b/PlotLine/Models/NameIntelligenceModels.cs @@ -110,6 +110,8 @@ public sealed class NameSearchFilter public decimal? MinimumUsage { get; set; } public string UsedScope { get; set; } = "Project"; public bool? UsedOnly { get; set; } + [System.ComponentModel.DataAnnotations.RegularExpression("suggested|name-asc|name-desc|common-desc|common-asc")] + public string SortOrder { get; set; } = "suggested"; public int Page { get; set; } = 1; public int PageSize { get; set; } = 25; } diff --git a/PlotLine/Services/CharacterQuickAttributes.cs b/PlotLine/Services/CharacterQuickAttributes.cs index 9952ba7f..0143f79f 100644 --- a/PlotLine/Services/CharacterQuickAttributes.cs +++ b/PlotLine/Services/CharacterQuickAttributes.cs @@ -3,16 +3,26 @@ namespace PlotLine.Services; // One vocabulary for the directory legend, indicators and assignment menus. public sealed record CharacterQuickValue(string Value,string Label,string Icon,string Tone="secondary"); -public sealed record CharacterQuickGroup(string Id,string Label,IReadOnlyList Values); +public sealed record CharacterQuickGroup(string Id,string Label,IReadOnlyList Values, CharacterQuickValue? RecordedFallback=null); public static class CharacterQuickAttributes { public static IReadOnlyList Definitions(IEnumerable sex) => [ - new("type", "Character Type", CharacterTypes.Values), - new("importance","Story importance",[new("10","Major","attribute-star","warning"),new("6","Supporting","characters","info"),new("2","Minor","attribute-person"),new("","Unclassified","help")]), + new("importance","Story importance",[new("10","Major","attribute-star-filled","warning"),new("6","Supporting","attribute-star-half","info"),new("2","Minor","attribute-star"),new("","Unclassified","help")]), new("life","Life status",[new("0","Living","attribute-heart","success"),new("1","Deceased","attribute-flower","data-5"),new("","Unrecorded","help")]), - new("sex","Sex",new[]{new CharacterQuickValue("","Not set","help")}.Concat(sex.Select(s=>new CharacterQuickValue(s.CharacterSexValueID.ToString(),s.SexName,"attribute-person"))).ToArray()), + new("sex","Sex",new[]{new CharacterQuickValue("","Not set","help")}.Concat(sex.Select(SexValue)).ToArray(), new("","Recorded sex","sex-other","data-5")), + new("type", "Character Type", CharacterTypes.Values), new("quickAdd","Quick Add Bar",[new("1","Included","attribute-pin","primary"),new("0","Excluded","attribute-unpin")]) ]; + private static CharacterQuickValue SexValue(CharacterSexValue value) + { + var (icon,tone)=(value.IsSystem?value.SexName:"") switch {"Male"=>("sex-male","info"),"Female"=>("sex-female","data-7"),_=>("sex-other","data-5")}; + return new(value.CharacterSexValueID.ToString(),value.SexName,icon,tone); + } + public static object Presentation(CharacterQuickValue value) + { + var icon=ApplicationRibbon.Icon(value.Icon); + return new{value.Value,value.Label,value.Tone,value.Icon,path=icon.IconPath,icon.Filled}; + } public static object Snapshot(Character c)=>new {id=c.CharacterID,name=c.CharacterName,version=c.UpdatedDate.ToString("O"),values=new Dictionary{["type"]=c.CharacterTypeCode,["importance"]=c.CharacterImportance?.ToString()??"",["life"]=c.IsDeceased.HasValue?(c.IsDeceased.Value?"1":"0"):"",["sex"]=c.SexValueID?.ToString()??(string.IsNullOrWhiteSpace(c.Sex)?"":"legacy:"+c.Sex),["quickAdd"]=c.ShowInQuickAddBar?"1":"0"}}; } public sealed record CharacterQuickChange(int Id,string? Value,string Version); diff --git a/PlotLine/Services/RibbonPresentation.cs b/PlotLine/Services/RibbonPresentation.cs index daf11349..2f79fd79 100644 --- a/PlotLine/Services/RibbonPresentation.cs +++ b/PlotLine/Services/RibbonPresentation.cs @@ -1,6 +1,6 @@ namespace PlotLine.Services; -public sealed record RibbonIcon(string Key, string IconPath, string Tone); +public sealed record RibbonIcon(string Key, string IconPath, string Tone, bool Filled = false); // Presentation metadata only. Routes, permissions and command execution stay with their owners. public static class RibbonPresentation @@ -51,6 +51,11 @@ public static class RibbonPresentation new("attribute-sparkles", "M12 2l3 7 7 3-7 3-3 7-3-7-7-3 7-3z M21 2v4 M19 4h4 M3 19v4 M1 21h4", "characters"), new("attribute-robot", "M4 7h16v14H4z M12 3v4 M10 3h4 M8 11h1 M15 11h1 M8 17h8 M1 11v6 M23 11v6", "characters"), new("attribute-star", "M12 2l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z", "characters"), + new("attribute-star-filled", "M12 2l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z", "characters", true), + new("attribute-star-half", "M12 2l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z M12.7 5.4l1.3 4 5 .8-3.7 3.5.8 4.6-3.4-1.7z", "characters", true), + new("sex-male", "M15 15a6 6 0 1 0-12 0 6 6 0 0 0 12 0 M13 11l8-8 M15 3h6v6", "characters"), + new("sex-female", "M17 7a5 5 0 1 0-10 0 5 5 0 0 0 10 0 M12 12v10 M8 18h8", "characters"), + new("sex-other", "M14 10a5 5 0 1 0-10 0 5 5 0 0 0 10 0 M9 15v7 M5 19h8 M12.5 6.5L21 2 M16 2h5v5", "characters"), new("attribute-person", "M16 6a4 4 0 1 0-8 0 4 4 0 0 0 8 0 M4 22v-3a8 8 0 0 1 16 0v3z", "characters"), new("attribute-heart", "M12 21L3 12C-3 4 7-1 12 6c5-7 15-2 9 6z", "characters"), new("attribute-flower", "M12 22v-8 M12 19l6-3 M12 5c-6-9-10 2-5 4-8 3 0 10 5 5 5 5 13-2 5-5 5-2 1-13-5-4z", "characters"), diff --git a/PlotLine/Sql/334_NamesWorkspaceSorting.sql b/PlotLine/Sql/334_NamesWorkspaceSorting.sql new file mode 100644 index 00000000..28f6606c --- /dev/null +++ b/PlotLine/Sql/334_NamesWorkspaceSorting.sql @@ -0,0 +1,148 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- Add optional complete-result sorting using the existing selected catalogue UsageWeight. +-- Avoid reusing a narrow-prefix or small-cast plan for an unfiltered directory. +-- Earlier live migrations remain immutable; matching, filtering and default ranking are retained. +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, + @SortOrder varchar(20) = 'suggested' +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 @SortOrder NOT IN('suggested','name-asc','name-desc','common-desc','common-asc') OR @SortOrder IS NULL + THROW 51012,'Invalid name sort order',1; + + 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 CandidateNames AS + ( + SELECT * FROM dbo.GivenNames g + WHERE g.IsActive=1 AND (@NameType IS NULL OR g.NameType=@NameType) + 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'%') + ), 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 CandidateNames candidates ON candidates.GivenNameID=u.GivenNameID + INNER JOIN dbo.NameLocales l ON l.NameLocaleID = u.NameLocaleID + WHERE u.IsActive = 1 + AND (@NameLocaleID IS NULL OR u.NameLocaleID = @NameLocaleID) + ), + Used AS + ( + SELECT g.GivenNameID, COUNT(DISTINCT c.CharacterID) AS UsedCount, + SUM(CASE WHEN c.MatchType=N'Character' THEN 1 ELSE 0 END) AS PrimaryCount, + SUM(CASE WHEN c.MatchType=N'Alias' THEN 1 ELSE 0 END) AS AliasCount, + MAX(CASE WHEN c.CharacterTypeCode='animal' THEN 1 ELSE 0 END) AS HasAnimalAssociation, + CASE WHEN COUNT(DISTINCT c.CharacterTypeCode)=1 THEN MIN(c.CharacterTypeCode) END AS AssociationTypeCode, + CAST(N'' AS nvarchar(max)) AS UsedSummary + FROM CandidateNames g + INNER JOIN + ( + SELECT c.CharacterID, c.ProjectID, c.CharacterName AS MatchedName, c.CharacterTypeCode, N'Character' AS MatchType + FROM dbo.Characters c WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID + UNION + SELECT c.CharacterID, c.ProjectID, ca.Alias, c.CharacterTypeCode, N'Alias' + FROM dbo.CharacterAliases ca JOIN dbo.Characters c ON c.CharacterID=ca.CharacterID + WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID + AND UPPER(LTRIM(RTRIM(ca.Alias))) COLLATE Latin1_General_100_CI_AI_SC <> UPPER(LTRIM(RTRIM(c.CharacterName))) + ) c ON UPPER(LTRIM(RTRIM(c.MatchedName))) = g.NormalisedName COLLATE Latin1_General_100_CI_AI_SC + GROUP BY g.GivenNameID + ), + Related AS + ( + SELECT x.GivenNameID, + STRING_AGG(CONVERT(nvarchar(max), x.DisplayName), N', ') AS RelatedForms + FROM + ( + SELECT r.FromGivenNameID AS GivenNameID, t.DisplayName + FROM dbo.NameRelationships r + INNER JOIN dbo.GivenNames t ON t.GivenNameID = r.ToGivenNameID + WHERE r.IsActive = 1 + UNION + SELECT r.ToGivenNameID AS GivenNameID, f.DisplayName + FROM dbo.NameRelationships r + INNER JOIN dbo.GivenNames f ON f.GivenNameID = r.FromGivenNameID + WHERE r.IsActive = 1 AND r.IsBidirectional = 1 + ) x + GROUP BY x.GivenNameID + ), + Filtered AS + ( + SELECT + g.GivenNameID, g.GivenNameKey, g.DisplayName, g.NormalisedName, g.NameType, g.IsWordAmbiguous, + u.MaleWeight, u.FemaleWeight, u.UsageWeight, u.Confidence, u.BirthYearFrom, u.BirthYearTo, u.LocaleCode, u.LocaleDisplayName, u.SourceType, + rel.RelatedForms, + COALESCE(used.UsedSummary, N'') AS UsedSummary, + COALESCE(used.UsedCount, 0) AS UsedCount, + COALESCE(used.PrimaryCount,0) AS PrimaryCount, COALESCE(used.AliasCount,0) AS AliasCount, COALESCE(used.HasAnimalAssociation,0) AS HasAnimalAssociation, used.AssociationTypeCode, + COUNT(1) OVER() AS TotalRows + FROM CandidateNames 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 @SortOrder='suggested' AND @Search IS NOT NULL AND NormalisedName = UPPER(LTRIM(RTRIM(@Search))) COLLATE Latin1_General_100_CI_AI_SC THEN 0 ELSE 1 END, + CASE WHEN @SortOrder IN('common-asc','common-desc') AND UsageWeight IS NULL THEN 1 ELSE 0 END, + CASE WHEN @SortOrder IN('suggested','common-desc') THEN UsageWeight END DESC, + CASE WHEN @SortOrder='common-asc' THEN UsageWeight END ASC, + CASE WHEN @SortOrder='name-desc' THEN DisplayName END DESC, + DisplayName ASC, + GivenNameID ASC + OFFSET (@Page - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY + OPTION (RECOMPILE); +END; +GO + diff --git a/PlotLine/ViewModels/NameDetailsViewModel.cs b/PlotLine/ViewModels/NameDetailsViewModel.cs index 34005e90..5ac81f27 100644 --- a/PlotLine/ViewModels/NameDetailsViewModel.cs +++ b/PlotLine/ViewModels/NameDetailsViewModel.cs @@ -1,3 +1,3 @@ using PlotLine.Models; namespace PlotLine.ViewModels; -public sealed record NameDetailsViewModel(int ProjectID, string Name, NameRecognitionResult Reference, IReadOnlyList Associations) {public NameVerificationView? Verification{get;init;}} +public sealed record NameDetailsViewModel(int ProjectID, string Name, NameRecognitionResult Reference, IReadOnlyList Associations) {public bool ContextNavigation{get;init;} public NameVerificationView? Verification{get;init;}} diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index c7198bf9..d8b089e3 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -190,7 +190,7 @@ diff --git a/PlotLine/Views/Shared/_NameDetails.cshtml b/PlotLine/Views/Shared/_NameDetails.cshtml index 0506cd41..552c6043 100644 --- a/PlotLine/Views/Shared/_NameDetails.cshtml +++ b/PlotLine/Views/Shared/_NameDetails.cshtml @@ -14,7 +14,7 @@ var type=CharacterTypes.Definition(association.CharacterTypeCode);

@association.CharacterName

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

@type.Label @if(!string.IsNullOrWhiteSpace(association.Species)){· @association.Species} · @CharacterWorkspace.Classification(association.CharacterImportance)

-
+ }
@if(Model.Verification is {} saved){}else{}
diff --git a/PlotLine/Views/Shared/_NamesWorkspace.cshtml b/PlotLine/Views/Shared/_NamesWorkspace.cshtml index 85dc3f06..162d7a7a 100644 --- a/PlotLine/Views/Shared/_NamesWorkspace.cshtml +++ b/PlotLine/Views/Shared/_NamesWorkspace.cshtml @@ -5,9 +5,10 @@ @Html.AntiForgeryToken()