Reuse workspace dividers for Characters and Names, order ribbon, and recognise recorded sex

This commit is contained in:
Nick Beckley 2026-11-26 21:19:57 +00:00
parent add3aa7c96
commit 26cc8a56fe
18 changed files with 101 additions and 32 deletions

View File

@ -25,7 +25,7 @@ The directory retains its existing `CharacterCardLayout.ColumnSpan`, full `Defau
| Deceased | attribute-flower | data-5 (existing purple theme palette) |
| 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 |
| Other / custom / unrecognised recorded legacy sex | sex-other (combined Venus/Mars) | data-5 |
| Quick Add included | attribute-pin | primary |
| Quick Add excluded | attribute-unpin | secondary |
@ -74,3 +74,5 @@ The Character Editor concurrency version is sent explicitly as Dapper `DbType.Da
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.
Recorded Male/Female text without a SexValueID uses exact trimmed, case-insensitive matching metadata from the system catalogue definitions. It shares Mars/Venus icons, blue/rose tones, filters/counts and current-value menu ticks with catalogue-backed values. No record is rewritten or inferred. Other/custom legacy labels remain recorded, with the combined symbol. Female uses the theme rose data tone directly (or a danger/character-tone rose blend) to retain its pink hue.

View File

@ -44,3 +44,5 @@ Sort codes are `suggested`, `name-asc`, `name-desc`, `common-desc`, `common-asc`
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.
The main Names page mounts the existing `PlotDirectorWorkspaceSurface.split` divider for results/details. Its independent user-scoped local workspace preference survives refresh, navigation and PWA restart. Pointer/keyboard resizing changes only grid sizing; it does not call the search/verification lifecycle. Displayed widths are bounded by the available space without saving viewport clamps. The existing container breakpoint and Context pane architecture are unchanged.

View File

@ -0,0 +1,9 @@
# Workspace dividers
`workspace-surface.js` owns editor and management-panel resizing. `PlotDirectorWorkspaceSurface.split(root, options)` uses the same pointer capture, keyboard interaction, `.pd-panel-divider` styling and `plotdirector.workspace.panels.*` local preferences as the existing Maps, Relationships and Floor Plans panels. Its returned `dispose()` disconnects observers/listeners. Context's separate split-pane lifecycle is unchanged.
Main Characters uses `characters.<user>` (224–480px, 256px default, at least 320px for cards). Main Names uses `names.<user>` (at least 280px results, 320px details, initial existing 1:0.8 proportions). The preference stores the author's chosen pixel width; window/container changes constrain only the displayed width and never save a temporary clamp. Keys are independent and persist across visits, refresh and installed-PWA restart in the same browser profile. They do not synchronise devices.
Drag the visible gutter, use Left/Right (10px), Shift+Left/Right (40px), or Home/double-click to reset. Separators expose orientation, label and current/minimum/maximum width. Pointer capture and resize cursor/text-selection protection end on pointer up/cancel/lost capture. The handle does not accept HTML drag sources or intercept card/attribute drag targets.
Characters retains its collapsed and narrow stacked modes, sticky sidebar and independent sidebar scrolling. Names retains its existing container breakpoint and narrow details/Back mode. Only main Names mounts this divider; Context does not. Resizing changes grid sizing only, without search, textual/AI requests, state reset or shared-focus changes. No database migration or new preference service is involved.

View File

@ -1,8 +1,10 @@
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']);
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','legacy:Male','legacy:Female','legacy: female '][i%8],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 male=p.locator('.character-card[data-drag-id="6"] [title="Sex: Male"]'),female=p.locator('.character-card[data-drag-id="7"] [title="Sex: Female"]');assert.equal(await male.locator('path').getAttribute('d'),groups.find(g=>g.id==='sex').values.find(v=>v.label==='Male').path);assert.equal(await female.locator('path').getAttribute('d'),groups.find(g=>g.id==='sex').values.find(v=>v.label==='Female').path);assert.equal(await p.locator('.character-card[data-drag-id="8"] [title="Sex: Female"]').count(),1);assert(await male.locator('svg').evaluate(n=>n.classList.contains('text-info')));assert(await female.locator('svg').evaluate(n=>n.classList.contains('text-data-7')));const maleFilter=p.locator('[data-attribute="sex"][data-value="1"] button').first();await maleFilter.click();assert(await p.locator('.character-card[data-drag-id="6"]').isVisible());assert(await p.locator('.character-card[data-drag-id="7"]').isHidden());await maleFilter.click();
await p.locator('.character-card[data-drag-id="7"]').scrollIntoViewIfNeeded();await p.evaluate(()=>getSelection()?.removeAllRanges());await p.locator('.character-card[data-drag-id="7"]').click({button:'right'});await p.getByRole('menuitem',{name:'Sex',exact:true}).hover();assert.equal(await p.getByRole('menuitemradio',{name:'Female',exact:true}).getAttribute('aria-checked'),'true');assert.equal(await p.getByRole('menuitemradio',{name:'Male',exact:true}).getAttribute('aria-checked'),'false');await p.keyboard.press('Escape');await p.evaluate(()=>scrollTo({top:0,behavior:'instant'}));
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')<menus.indexOf('Sex')&&menus.indexOf('Sex')<menus.indexOf('Character Type')&&menus.indexOf('Character Type')<menus.indexOf('Quick Add Bar'));await p.getByRole('menuitem',{name:'Story importance',exact:true}).hover();await p.getByRole('menuitemradio',{name:'Supporting',exact:true}).waitFor();assert.equal(await p.getByRole('menuitemradio',{name:'Supporting',exact:true}).locator('path').getAttribute('fill'),'currentColor');await p.screenshot({path:`${out}/importance-menu-${installed?'pwa':'browser'}.png`});await p.keyboard.press('Escape');fs.writeFileSync(`${out}/contrast-${installed?'pwa':'browser'}.json`,JSON.stringify(contrast,null,2));console.log('PASS shared importance/sex symbols, canonical order, legacy/custom labels, menu filled SVG and all seven theme icon contrasts',contrast);

View File

@ -41,6 +41,7 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require(
await page.goto('http://127.0.0.1:5238/relationship-evolution-fixture');assert.equal(await page.locator('.pd-record-canvas').count(),1);assert.equal(await page.locator('.pd-workspace-full-width').count(),0,'other pages do not opt in');assert(await page.locator('.pd-record-canvas').evaluate(n=>n.getBoundingClientRect().width<document.documentElement.clientWidth-100));
assert.deepEqual(errors,[]);fs.writeFileSync(`${directory}/${before?'before':'after'}-${installed?'pwa':'browser'}.json`,JSON.stringify(measurements,null,2));console.log('PASS workspace widths',measurements);await page.close();continue;
}
const divider=page.getByRole('separator',{name:'Resize Attributes panel'});await divider.press('ArrowRight');await divider.press('ArrowRight');
if(groups.some(g=>g.id==='type')){
await forward('type','person',1);await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Person"]'));
await reverse(2,'type','artificial');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Artificial being"]'));

View File

@ -3,7 +3,7 @@ const {chromium}=require('playwright'),assert=require('assert/strict'),fs=requir
await c.route('https://cdn.jsdelivr.net/**',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules',r.request().url().includes('chart.umd')?'chart.js/dist/chart.umd.js':'@microsoft/signalr/dist/browser/signalr.min.js'))}));
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 errors=[];p.on('pageerror',e=>errors.push(e.message));let archivePosts=0;await p.route('**/Characters/Archive',r=>{archivePosts++;return r.fulfill({contentType:'text/html',body:'<p>Disposable archive endpoint</p>'})});
for(const tab of ['overview','relationships','evolution','appearances','knowledge']){await p.goto(base+'/character-workspace-fixture?tab='+tab);await p.setViewportSize({width:1920,height:1080});const group=p.locator('[data-character-ribbon]');assert.deepEqual((await group.locator('.pd-ribbon-command span').allTextContents()).filter(text=>text!=='More'),['Edit Character','Merge Character','Reanalyse Biography','Archive Character']);assert.match(await group.getByRole('link',{name:'Merge Character',exact:true}).getAttribute('href'),/Characters\/Merge\/5/);assert.match(await group.locator('[data-character-reanalyse-form]').getAttribute('action'),/Characters\/Reanalyse/);assert.equal(await group.locator('[data-character-reanalyse-button] svg').count(),1);await p.getByRole('button',{name:'Export',exact:true}).click();const menu=p.locator('[data-character-actions-for="5"]');await menu.waitFor({state:'visible'});assert.deepEqual(await menu.locator('.dropdown-item').allTextContents(),['Export character','Markdown']);assert.equal(await menu.locator('form').count(),0);await p.keyboard.press('Escape');}
for(const tab of ['overview','relationships','evolution','appearances','knowledge']){await p.goto(base+'/character-workspace-fixture?tab='+tab);await p.setViewportSize({width:1920,height:1080});const group=p.locator('[data-character-ribbon]');assert.deepEqual((await group.locator('.pd-ribbon-command span').allTextContents()).filter(text=>text!=='More'),['Edit Character','Merge Character','Reanalyse Biography','Archive Character']);assert.deepEqual(await p.locator('#ribbon-panel-characters > .pd-ribbon-group').evaluateAll(nodes=>nodes.map(n=>n.getAttribute('aria-label'))),['Cast','Connections','Selected character','Output','Focus']);assert.match(await group.getByRole('link',{name:'Merge Character',exact:true}).getAttribute('href'),/Characters\/Merge\/5/);assert.match(await group.locator('[data-character-reanalyse-form]').getAttribute('action'),/Characters\/Reanalyse/);assert.equal(await group.locator('[data-character-reanalyse-button] svg').count(),1);await p.getByRole('button',{name:'Export',exact:true}).click();const menu=p.locator('[data-character-actions-for="5"]');await menu.waitFor({state:'visible'});assert.deepEqual(await menu.locator('.dropdown-item').allTextContents(),['Export character','Markdown']);assert.equal(await menu.locator('form').count(),0);await p.keyboard.press('Escape');}
await p.locator('[data-character-ribbon] form[action*=Archive] button').click();await p.locator('#plotlineConfirmModal.show').waitFor();assert((await p.locator('[data-character-ribbon] form[action*=Archive]').getAttribute('data-confirm-message')).includes('data will be retained for restoration'));assert((await p.locator('#plotlineConfirmModal').innerText()).toLowerCase().includes('archiv'));assert.equal(archivePosts,0);await p.locator('#plotlineConfirmModal').getByRole('button',{name:'Cancel',exact:true}).last().click();await p.locator('#plotlineConfirmModal').waitFor({state:'hidden'});assert.equal(archivePosts,0);
const out='/tmp/pd-ui-refinements';fs.mkdirSync(out,{recursive:true});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);await p.screenshot({path:`${out}/ribbon-${installed?'pwa':'browser'}-${theme}.png`});}
for(const width of [1280,1920,2560,3840,768,390]){await p.setViewportSize({width,height:1080});await p.getByRole('button',{name:'Export',exact:true}).click();await p.locator('[data-character-actions-for="5"]').waitFor({state:'visible'});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.keyboard.press('Escape');}

View File

@ -6,7 +6,7 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=r
await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});
const queries=[];await context.route('**/Writing/Context/Names/*',async r=>{const u=new URL(r.request().url()),part=u.pathname.split('/').at(-1).toLowerCase();queries.push({part,params:u.searchParams});await r.fulfill({response:await r.fetch({url:base+'/names-workspace-fixture/'+(part==='search'?'results':part)+u.search})});});
let page;if(installed){await persistent.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await context.newPage();const errors=[];page.on('pageerror',error=>errors.push(error.message));await page.goto(base+'/Writing/Context');await page.locator('[data-context-tab]').first().selectOption('names');
const pane=index=>page.locator(`[data-context-pane="${index}"]`),first=pane(0);await first.locator('[data-name-select]').first().waitFor();assert.equal(queries.length,0);
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);assert.equal(await page.locator('[data-single-panel]').count(),0,'Context keeps its existing split-pane architecture');
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');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');

View File

@ -0,0 +1,14 @@
// Compiled production pages; the existing shared divider and local preference store.
const {chromium}=require('playwright'),assert=require('assert/strict'),fs=require('fs'),os=require('os'),path=require('path');
(async()=>{const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync(path.join(os.tmpdir(),'pd-directory-dividers-')),base='http://127.0.0.1:5238',manifestId=base+'/Projects',out='/tmp/pd-directory-dividers';fs.mkdirSync(out,{recursive:true});let c,cdp,p;const errors=[],calls={attributes:0,search:0,details:0,other:0},saved={},measurements=[];
async function launch(restart=false){c=await chromium.launchPersistentContext(profile,{headless:!installed,viewport:{width:1920,height:1080}});p=c.pages()[0];await c.route('https://cdn.jsdelivr.net/**',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules',r.request().url().includes('chart.umd')?'chart.js/dist/chart.umd.js':'@microsoft/signalr/dist/browser/signalr.min.js'))}));const groups=await(await p.request.get(base+'/character-attribute-definitions-fixture')).json();await c.route('**/CharacterAttributes/Directory?*',r=>{calls.attributes++;return r.fulfill({json:{canEdit:true,groups,characters:Array.from({length:100},(_,n)=>({id:n+1,name:'Fixture character '+(n+1),version:'v1',values:{importance:'6',life:'',sex:'',type:'unclassified',quickAdd:'0'}}))}})});for(const part of ['Results','Details'])await c.route('**/Names/'+part+'?*',async r=>{calls[part==='Results'?'search':'details']++;const u=new URL(r.request().url());return r.fulfill({response:await p.request.get(base+'/names-workspace-fixture/'+part.toLowerCase()+'?'+u.searchParams)})});c.on('request',r=>{if(/\/NameVerification\/|\/CharacterAttributes\/(Assign|Undo)/.test(new URL(r.url()).pathname))calls.other++});await p.goto(base+'/fixture?page=calendar-test');if(installed){cdp=await c.browser().newBrowserCDPSession();if(!restart){await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:p.url()});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'})}const opened=c.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:p.url()});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));await p.setViewportSize({width:1920,height:1080})}p.on('pageerror',e=>errors.push(e.message));}
const width=selector=>p.locator(selector).evaluate(n=>n.getBoundingClientRect().width),pause=()=>p.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))));
async function drag(handle,delta){const b=await handle.boundingBox(),y=Math.max(220,Math.min(550,b.y+40));await p.mouse.move(b.x+b.width/2,y);await p.mouse.down();await p.mouse.move(b.x+b.width/2+delta,y,{steps:15});await p.mouse.up();await pause();assert.equal(await p.evaluate(()=>document.documentElement.classList.contains('pd-panel-resizing')),false)}
async function preference(name){return p.evaluate(name=>{const key=Object.keys(localStorage).find(k=>k.startsWith('plotdirector.workspace.panels.'+name+'.'));return {key,...JSON.parse(localStorage.getItem(key))}},name)}
try{await launch();await p.goto(base+'/character-attributes-fixture?count=100');await p.locator('[data-attribute-groups] details').first().waitFor();const ch=p.getByRole('separator',{name:'Resize Attributes panel'}),side='[data-attribute-sidebar]',grid='.character-card-grid';await ch.waitFor();const biographies=await p.locator('.visual-card-heading p.muted').allTextContents(),gridBefore=await width(grid),before={...calls};await drag(ch,160);assert(Math.abs(await width(side)-416)<2);assert(await width(grid)<gridBefore-150);await ch.press('ArrowLeft');assert(Math.abs(await width(side)-406)<2);await drag(ch,1000);assert(Math.abs(await width(side)-480)<2);await drag(ch,-1000);assert(Math.abs(await width(side)-224)<2);await ch.press('Home');assert(Math.abs(await width(side)-256)<2);await drag(ch,150);saved.characters=await preference('characters');assert.deepEqual(calls,before);await p.reload();await ch.waitFor();assert(Math.abs(await width(side)-406)<2);await p.locator('[data-attributes-toggle]').click();await pause();assert(await ch.isHidden());assert(await width(grid)>gridBefore+250);await p.locator('[data-attributes-toggle]').click();await ch.waitFor();assert(Math.abs(await width(side)-406)<2);await p.evaluate(()=>scrollTo({top:1200,behavior:'instant'}));const sticky=await p.locator(side).boundingBox();assert(sticky.y>=0&&sticky.y+sticky.height<=1081);await p.evaluate(()=>scrollTo({top:0,behavior:'instant'}));assert.deepEqual(await p.locator('.visual-card-heading p.muted').allTextContents(),biographies);
await p.goto(base+'/names-workspace-fixture/page');await p.locator('[name=Search]').fill('George');await p.locator('[name=SortOrder]').selectOption('name-desc');await p.waitForFunction(()=>JSON.parse(document.querySelector('[data-names-applied]').textContent).SortOrder==='name-desc');await p.locator('[data-name-select]').first().click();await p.locator('[data-name-details-fragment]').waitFor();const nh=p.getByRole('separator',{name:'Resize name results and details'}),results='[data-names-results-host]';await nh.waitFor();const initial=await width(results),namesBefore={...calls},selected=await p.locator('[data-name-details-fragment] h2').innerText();await drag(nh,-150);assert(Math.abs(await width(results)-(initial-150))<2);await drag(nh,5000);assert(await width('[data-names-details]')>=319);await drag(nh,-5000);assert(Math.abs(await width(results)-280)<2);await drag(nh,initial-150-280);saved.names=await preference('names');assert(saved.names.left!==saved.characters.left);assert.deepEqual(calls,namesBefore);assert.equal(await p.locator('[name=SortOrder]').inputValue(),'name-desc');assert.equal(await p.locator('[data-name-details-fragment] h2').innerText(),selected);await p.reload();await nh.waitFor();assert(Math.abs(await width(results)-saved.names.left)<2);
for(const kind of ['names','characters']){await p.goto(base+(kind==='names'?'/names-workspace-fixture/page':'/character-attributes-fixture?count=100'));const handle=kind==='names'?nh:ch;await handle.waitFor();for(const w of [1280,1920,2560,3840,800,390,1920]){await p.setViewportSize({width:w,height:1080});await pause();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),kind+' overflow '+w);if(w===390)assert(await handle.isHidden());const current=await preference(kind);assert.equal(current.left,saved[kind].left,'viewport changes must not overwrite preference');if(w===2560)await p.screenshot({path:`${out}/${installed?'pwa':'browser'}-${kind}-2560.png`});measurements.push({kind,viewport:w,leftWidth:await width(kind==='names'?results:side),columns:kind==='characters'?await p.locator(grid).evaluate(n=>getComputedStyle(n).gridTemplateColumns.split(' ').length):null});}for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await p.evaluate(t=>{document.documentElement.dataset.appTheme=t;document.documentElement.dataset.bsTheme=t.endsWith('dark')?'dark':'light'},theme);await p.screenshot({path:`${out}/${installed?'pwa':'browser'}-${kind}-${theme}.png`})}}
// Persisted main Names state remains untouched by these panel controls; Context never mounts them.
await c.close();await launch(true);for(const kind of ['names','characters']){await p.goto(base+(kind==='names'?'/names-workspace-fixture/page':'/character-attributes-fixture?count=100'));await p.getByRole('separator').waitFor();assert(Math.abs(await width(kind==='names'?results:side)-saved[kind].left)<2,kind+' survives complete Chromium/PWA restart')}
assert.equal(calls.other,0);assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/${installed?'pwa':'browser'}.json`,JSON.stringify({status:'passed',actualInstalledPwa:installed,restartedPersistentProfile:true,saved,calls,measurements,biographiesPreserved:true},null,2));console.log('PASS independent pointer/keyboard dividers, bounds, sticky/collapse, no lookup/AI requests on resize, navigation/refresh/profile restart, seven themes, 390–3840 widths and '+(installed?'actual installed PWA':'browser'));
}finally{if(cdp)await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await c?.close();fs.rmSync(profile,{recursive:true,force:true})}})().catch(e=>{console.error(e.name+': '+e.message.split('Call log:')[0]);process.exitCode=1});

View File

@ -17,6 +17,8 @@ internal static class CharacterQuickAttributesTests
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(sex.Values.Single(v=>v.Value=="1").RecordedLabels?.Single()=="male"&&sex.Values.Single(v=>v.Value=="2").RecordedLabels?.Single()=="female"&&sex.Values.Single(v=>v.Value=="4").RecordedLabels is null,"recorded legacy Male/Female reuse system definitions without reclassifying custom text");
Check(JsonSerializer.Serialize(CharacterQuickAttributes.Presentation(sex.Values.Single(v=>v.Value=="2"))).Contains("female"),"shared presentation carries legacy matching metadata for cards, filters and menus");
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");

View File

@ -2,7 +2,7 @@ using PlotLine.Models;
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 CharacterQuickValue(string Value,string Label,string Icon,string Tone="secondary",IReadOnlyList<string>? RecordedLabels=null);
public sealed record CharacterQuickGroup(string Id,string Label,IReadOnlyList<CharacterQuickValue> Values, CharacterQuickValue? RecordedFallback=null);
public static class CharacterQuickAttributes
{
@ -16,12 +16,12 @@ public static class CharacterQuickAttributes
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);
return new(value.CharacterSexValueID.ToString(),value.SexName,icon,tone,value.IsSystem?[value.SexName.Trim().ToLowerInvariant()]:null);
}
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};
return new{value.Value,value.Label,value.Tone,value.Icon,value.RecordedLabels,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<string,string>{["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"}};
}

View File

@ -86,4 +86,6 @@
</div>
</div>
<link rel="stylesheet" href="~/css/workspace-surface.css" asp-append-version="true" />
<script src="~/js/workspace-surface.js" asp-append-version="true" defer></script>
<script src="~/js/character-attributes.js" asp-append-version="true" defer></script>

View File

@ -4,4 +4,5 @@
<partial name="_ProjectSectionNav" model="Model.Project"/>
<div data-pwa-header class="page-heading compact"><div><h1>Names <help-icon key="names.overview"/></h1><p class="muted">Explore catalogue names and recorded names and aliases across this series.</p></div></div>
<partial name="_NamesWorkspace" model="Model"/>
@section Scripts {<script src="~/js/names-workspace.js" asp-append-version="true"></script>}
<link rel="stylesheet" href="~/css/workspace-surface.css" asp-append-version="true" />
@section Scripts {<script src="~/js/workspace-surface.js" asp-append-version="true"></script><script src="~/js/names-workspace.js" asp-append-version="true"></script>}

View File

@ -128,7 +128,6 @@
@foreach (var category in ApplicationRibbon.Categories)
{
<div class="pd-ribbon-panel" id="ribbon-panel-@category.Key" role="tabpanel" aria-labelledby="ribbon-tab-@category.Key" hidden="@(category.Key != selectedCategory)">
@if(category.Key=="characters"&&ViewData["CharacterRibbonModel"] is CharacterDetailViewModel characterRibbon){<partial name="_CharacterRibbonCommands" model="characterRibbon"/>}
@foreach (var group in category.Key == "writer" ? WriterNavigation.RibbonGroups(Model.WriterDestination,controller=="WriterInvestigations") : category.Groups)
{
<div class="pd-ribbon-group" role="group" aria-label="@group.Label">
@ -169,6 +168,7 @@
<span class="pd-ribbon-group-label">@group.Label</span>
</div>
}
@if(category.Key=="characters"&&ViewData["CharacterRibbonModel"] is CharacterDetailViewModel characterRibbon){<partial name="_CharacterRibbonCommands" model="characterRibbon"/>}
@if(category.Key==selectedCategory && book!=null && category.Key is "writer" or "book" or "story"){
<div class="pd-ribbon-group" role="group" aria-label="Word caret"><div class="pd-ribbon-commands" data-word-ribbon>
@foreach(var target in new[]{("chapter","Chapter","bible"),("scene","Scene","threads"),("paragraph","Paragraph","point")}){

View File

@ -27,7 +27,7 @@
}
}
.text-data-7{color:color-mix(in srgb,var(--pd-data-7,var(--pd-danger)) 65%,var(--pd-text) 35%)!important}
.text-data-7{color:var(--pd-data-7,color-mix(in srgb,var(--pd-danger) 65%,var(--pd-icon-characters) 35%))!important}
.character-attribute-icon.text-info,.pd-context-popup .pd-icon.text-info{color:var(--pd-info)!important}
.character-attribute-icon.text-warning,.pd-context-popup .pd-icon.text-warning{color:var(--pd-warning)!important}

View File

@ -25,3 +25,19 @@ html.pd-panel-resizing, html.pd-panel-resizing * { cursor:col-resize!important;
/* Retain the contextual commands while recovering the outer PWA shell space. */
html[data-standalone=true]:has(.pd-workspace-maximised) .pd-application-header .pd-titlebar,
html[data-standalone=true]:has(.pd-workspace-maximised) .pd-application-header .pd-ribbon-heading { display:none; }
/* Two-pane management workspaces use the same divider, capture and preferences as editors. */
[data-single-panel] > .pd-panel-divider { left:calc(var(--workspace-left) + 4px); right:auto; border-radius:4px; }
@media(min-width:851px) {
.character-attribute-layout[data-single-panel] { grid-template-columns:var(--workspace-left) minmax(0,1fr); }
.character-attribute-layout[data-single-panel] > .pd-panel-divider { display:block!important; }
}
.attributes-collapsed .character-attribute-layout[data-single-panel] > .pd-panel-divider { display:none!important; }
.names-workspace-columns[data-single-panel] { grid-template-columns:var(--workspace-left) minmax(0,1fr); }
@container(min-width:761px) { .names-workspace-columns[data-single-panel] > .pd-panel-divider { display:block!important; } }
@container(max-width:760px) {
.names-workspace-columns[data-single-panel] { grid-template-columns:minmax(0,1fr); }
.names-workspace-columns[data-single-panel] > .pd-panel-divider { display:none!important; }
}
[data-single-panel] > .pd-panel-divider[hidden] { display:none!important; }

View File

@ -9,7 +9,7 @@
function scope(id){return selected.has(id)?[...selected]:[id];}
function selection(){for(const [id,c]of byId){c.classList.toggle('is-selected',selected.has(id));c.querySelector('[data-character-select]').checked=selected.has(id);}root.querySelector('[data-selection-count]').textContent=`${selected.size} selected`;groupsHost.querySelectorAll('[data-assign]').forEach(b=>b.disabled=!canEdit||busy||!selected.size);}
function matching(record,except){return [...filter].every(([a,v])=>a===except||displayValue(a,record?.values[a])===v);}
function displayValue(a,v){if(a==='importance'&&v!=='')return Number(v)>=8?'10':Number(v)>=4?'6':Number(v)>=1?'2':'';return v;}
function displayValue(a,v){if(a==='sex'&&v?.startsWith('legacy:')){const label=v.slice(7).trim().toLowerCase(),recorded=groups.find(g=>g.id==='sex')?.values.find(value=>value.recordedLabels?.includes(label));return recorded?.value??v;}if(a==='importance'&&v!=='')return Number(v)>=8?'10':Number(v)>=4?'6':Number(v)>=1?'2':'';return v;}
function render(){
for(const [id,card]of byId){const r=records.get(id);if(!r)continue;card.hidden=!matching(r);const indicators=card.querySelector('[data-attribute-indicators]'),signature=JSON.stringify(r.values);if(indicators.dataset.values===signature)continue;indicators.dataset.values=signature;indicators.replaceChildren();for(const g of groups){const v=g.values.find(v=>v.value===displayValue(g.id,r.values[g.id]))||(g.id==='sex'&&r.values.sex?.startsWith('legacy:')?{...g.fallback,label:r.values.sex.slice(7)}:null);if(!v)continue;const span=document.createElement('span');span.title=`${g.label}: ${v.label}`;span.setAttribute('role','img');span.setAttribute('aria-label',span.title);span.append(icon(v));indicators.append(span);}}
for(const row of groupsHost.querySelectorAll('[data-attribute]')){const g=row.dataset.attribute,v=row.dataset.value,b=row.firstElementChild,count=[...records.values()].filter(r=>matching(r,g)&&displayValue(g,r.values[g])===v).length;b.querySelector('[data-count]').textContent=` (${count})`;b.setAttribute('aria-pressed',String(filter.get(g)===v));b.classList.toggle('active',filter.get(g)===v);}
@ -26,6 +26,7 @@
root.querySelector('[data-select-visible]').addEventListener('click',()=>{shown().forEach(c=>selected.add(Number(c.dataset.dragId)));selection();});root.querySelector('[data-clear-selection]').addEventListener('click',()=>{selected.clear();selection();});root.querySelector('[data-clear-filter]').addEventListener('click',()=>{filter.clear();render();});
// Reuse the user-scoped local UI preference convention used by the character workspace.
const user=document.querySelector('[data-toast-host]')?.dataset.toastUser||'session',preference=`pd.character.attributes.v1.${user}.${project}`;
window.PlotDirectorWorkspaceSurface?.split(root,{name:`characters.${user}`,layout:'.character-attribute-layout',left:'[data-attribute-sidebar]',defaultWidth:256,minimum:224,maximum:480,remaining:320,breakpoint:850,label:'Resize Attributes panel'});
function collapse(value){root.classList.toggle('attributes-collapsed',value);sidebar.hidden=value;toggle.setAttribute('aria-expanded',String(!value));}
try{collapse(localStorage.getItem(preference)==='collapsed');}catch{}
toggle.addEventListener('click',()=>{const value=!sidebar.hidden;collapse(value);try{localStorage.setItem(preference,value?'collapsed':'expanded');}catch{}});

View File

@ -2,6 +2,7 @@
'use strict';
window.PlotDirectorNames={mount(root,{state:prior,onState=()=>{}}={}){
const lifetime=new AbortController(),form=root.querySelector('[data-names-search]'),results=root.querySelector('[data-names-results-host]'),details=root.querySelector('[data-names-details]'),status=root.querySelector('[data-names-status]');
const divider=!root.closest('[data-context-pane]')?window.PlotDirectorWorkspaceSurface?.split(root,{name:`names.${root.dataset.user}`,layout:'.names-workspace-columns',left:'[data-names-results-host]',minimum:280,remaining:320,breakpoint:760,label:'Resize name results and details'}):null;
const paneHost=root.closest('[data-context-pane-content]');let sizeObserver;if(paneHost){root.classList.add('names-workspace--context');sizeObserver=new ResizeObserver(()=>root.style.setProperty('--names-available-height',paneHost.clientHeight+'px'));sizeObserver.observe(paneHost);}
function scrollHost(){for(let node=root.parentElement;node&&node!==document.body&&node!==document.documentElement;node=node.parentElement)if(/auto|scroll/.test(getComputedStyle(node).overflowY)&&node.scrollHeight>node.clientHeight)return node;return document.scrollingElement;}
let selected='',page=Number(form.elements.Page.value)||1,searchRequest,detailRequest,searchEpoch=0,detailEpoch=0,featureBusy=false;
@ -69,7 +70,7 @@
});
listen(scrollHost(),'scroll',save);listen(form,'change',save);listen(details,'scroll',save);listen(window,'pagehide',save);
if(prior){apply(prior.fields||[]);root.querySelector('[data-names-filters]').open=Boolean(prior.expanded);const restore=[search(prior.page||1,{restore:true})];if(prior.selected)restore.push(select(prior.selected,{restore:true}));void Promise.all(restore).then(()=>{if(!lifetime.signal.aborted)requestAnimationFrame(()=>{scrollHost().scrollTo({top:prior.scroll||0,behavior:'instant'});save();});});if(!prior.detailsOpen)root.removeAttribute('data-details-open');}
return {state:snapshot,refresh(){void search(page);if(selected)void select(selected,{preserveScroll:true});},dispose(){save();sizeObserver?.disconnect();lifetime.abort();searchRequest?.abort();detailRequest?.abort();}};
return {state:snapshot,refresh(){void search(page);if(selected)void select(selected,{preserveScroll:true});},dispose(){save();divider?.dispose();sizeObserver?.disconnect();lifetime.abort();searchRequest?.abort();detailRequest?.abort();}};
}};
function main(){const root=document.querySelector('body:not(.context-window) [data-names-workspace]');if(!root||root.closest('[data-context-pane]'))return;const key='pd.names.workspace.v1:'+root.dataset.user+':'+root.dataset.project;let state;try{state=JSON.parse(sessionStorage.getItem(key)||'null');}catch{}const workspace=window.PlotDirectorNames.mount(root,{state,onState:value=>{try{sessionStorage.setItem(key,JSON.stringify(value));}catch{}}});let connection,timer;function wire(c){if(connection||!c)return;connection=c;c.on('ContextInvalidated',hint=>{if((!hint.projectId||Number(hint.projectId)===Number(root.dataset.project))&&(!hint.kind||hint.kind==='characters'||hint.kind==='names')){clearTimeout(timer);timer=setTimeout(()=>workspace.refresh(),150);}});c.onreconnected(()=>workspace.refresh());}document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));wire(window.PlotDirectorPresenceConnection);window.addEventListener('pageshow',e=>{if(e.persisted)workspace.refresh();});}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',main,{once:true});else main();

View File

@ -1,56 +1,65 @@
(() => {
if(window.PlotDirectorWorkspaceSurface)return;
function panels(app, signal) {
function panels(app, signal, single) {
const profiles = [
['relationships', '.rw-board', '.rw-navigation', '.rw-rail', 185, 230],
['maps', '.maps-body', '.maps-library', '.maps-details', 220, 280],
['floorplans', '.floor-plan-layout', '.floor-plan-build', '.floor-plan-inspector', 240, 280]
];
const profile = profiles.find(([, selector]) => app.querySelector(selector));
const profile = single ? [single.name, single.layout, single.left, null, single.defaultWidth, 0] : profiles.find(([, selector]) => app.querySelector(selector));
if (!profile) return () => {};
const [name, selector, leftSelector, rightSelector, leftDefault, rightDefault] = profile;
const layout = app.querySelector(selector);
if (layout.dataset.resizablePanels) return () => {};
layout.dataset.resizablePanels = name;
const defaults = { left: leftDefault, right: rightDefault };
if (single) layout.dataset.singlePanel = name;
const defaults = { left: leftDefault ?? Math.round(layout.clientWidth / 1.8), right: rightDefault };
const sides = single ? ['left'] : ['left', 'right'];
const minimum = single?.minimum ?? 150;
const maximum = () => single ? Math.max(minimum, Math.min(single.maximum ?? Infinity, layout.clientWidth - single.remaining - 16)) : 480;
const key = `plotdirector.workspace.panels.${name}`;
let saved = {};
try { saved = JSON.parse(localStorage.getItem(key) || '{}') || {}; } catch { /* Optional preferences. */ }
const widths = { ...defaults };
for (const side of ['left', 'right']) if (Number.isFinite(saved[side])) widths[side] = Math.max(150, Math.min(480, saved[side]));
for (const side of sides) if (Number.isFinite(saved[side])) widths[side] = Math.max(minimum, Math.min(single ? Infinity : 480, saved[side]));
const handles = {};
let dragging;
let dragging, frame;
const persist = () => { try { localStorage.setItem(key, JSON.stringify(widths)); } catch { /* Optional preferences. */ } };
const refresh = () => {
const available = Math.max(300, layout.clientWidth - 320);
const scale = Math.min(1, available / (widths.left + widths.right));
for (const side of ['left', 'right']) layout.style.setProperty(`--workspace-${side}`, `${Math.round(widths[side] * scale)}px`);
for (const [side, panelSelector] of [['left', leftSelector], ['right', rightSelector]]) {
const scale = single ? 1 : Math.min(1, available / (widths.left + widths.right));
for (const side of sides) layout.style.setProperty(`--workspace-${side}`, `${Math.round(single ? Math.max(minimum, Math.min(widths[side], maximum())) : widths[side] * scale)}px`);
for (const side of sides) {
const panelSelector = side === 'left' ? leftSelector : rightSelector;
const panel = layout.querySelector(panelSelector);
const handle = handles[side];
handle.hidden = layout.clientWidth < 900 || !panel || !panel.getClientRects().length;
handle.hidden = layout.clientWidth <= (single?.breakpoint ?? 899) || !panel || panel.hidden || !panel.getClientRects().length;
if (handle.hidden) continue;
const bounds = panel.getBoundingClientRect();
handle.setAttribute('aria-valuemin', String(minimum));
handle.setAttribute('aria-valuemax', String(Math.round(maximum())));
handle.setAttribute('aria-valuenow', String(Math.round(bounds.width)));
handle.setAttribute('aria-valuetext', `${Math.round(bounds.width)} pixels`);
}
};
const resize = (side, value) => {
const other = side === 'left' ? 'right' : 'left';
widths[side] = Math.max(150, Math.min(480, layout.clientWidth - widths[other] - 320, value));
widths[side] = Math.max(minimum, Math.min(maximum(), single ? Infinity : layout.clientWidth - widths[other] - 320, value));
refresh();
window.dispatchEvent(new Event('resize'));
if (!single) window.dispatchEvent(new Event('resize'));
};
for (const side of ['left', 'right']) {
for (const side of sides) {
const handle = document.createElement('div');
handles[side] = handle;
handle.className = 'pd-panel-divider'; handle.tabIndex = 0; handle.dataset.panelSide = side;
handle.setAttribute('role', 'separator');
handle.setAttribute('aria-orientation', 'vertical');
handle.setAttribute('aria-label', `Resize ${side} panel`);
handle.setAttribute('aria-valuemin', '150'); handle.setAttribute('aria-valuemax', '480');
handle.setAttribute('aria-label', single?.label ?? `Resize ${side} panel`);
handle.setAttribute('aria-valuemin', String(minimum)); handle.setAttribute('aria-valuemax', String(maximum()));
layout.append(handle);
handle.addEventListener('dragstart', event => event.preventDefault(), { signal });
handle.addEventListener('pointerdown', event => {
if (event.button !== 0) return;
if (event.button !== 0 || handle.hidden || app.matches('.dragging-attribute,.dragging-characters')) return;
event.preventDefault(); event.stopPropagation();
dragging = { side, x: event.clientX, width: layout.querySelector(side === 'left' ? leftSelector : rightSelector).getBoundingClientRect().width };
handle.setPointerCapture(event.pointerId);
@ -64,6 +73,7 @@
const finish = () => { if (!dragging) return; dragging = null; document.documentElement.classList.remove('pd-panel-resizing'); persist(); };
handle.addEventListener('pointerup', finish, { signal });
handle.addEventListener('lostpointercapture', finish, { signal });
handle.addEventListener('pointercancel', finish, { signal });
handle.addEventListener('dblclick', event => { event.preventDefault(); event.stopPropagation(); resize(side, defaults[side]); persist(); }, { signal });
handle.addEventListener('keydown', event => {
if (!['ArrowLeft', 'ArrowRight', 'Home'].includes(event.key)) return;
@ -72,13 +82,19 @@
persist();
}, { signal });
}
const observer = new ResizeObserver(refresh); observer.observe(layout);
const mutations = new MutationObserver(refresh); mutations.observe(layout, { attributes: true, attributeFilter: ['class', 'hidden'] });
window.addEventListener('resize', refresh, { signal });
const schedule = () => { if (!frame) frame = requestAnimationFrame(() => { frame = null; refresh(); }); };
const observer = new ResizeObserver(schedule); observer.observe(layout);
const mutations = new MutationObserver(schedule); mutations.observe(layout, { attributes: true, attributeFilter: ['class', 'hidden'] });
if (single) { mutations.observe(app, { attributes: true, attributeFilter: ['class'] }); mutations.observe(layout.querySelector(leftSelector), { attributes: true, attributeFilter: ['hidden'] }); }
window.addEventListener('resize', schedule, { signal });
refresh();
return () => { observer.disconnect(); mutations.disconnect(); dragging = null; document.documentElement.classList.remove('pd-panel-resizing'); Object.values(handles).forEach(handle => handle.remove()); delete layout.dataset.resizablePanels; };
return () => { observer.disconnect(); mutations.disconnect(); cancelAnimationFrame(frame); dragging = null; document.documentElement.classList.remove('pd-panel-resizing'); Object.values(handles).forEach(handle => handle.remove()); delete layout.dataset.resizablePanels; delete layout.dataset.singlePanel; };
}
window.PlotDirectorWorkspaceSurface={attach(app,button,{className='pd-workspace-maximised',onChange=()=>{},allowPwa=false,hideChrome=false}={}){
window.PlotDirectorWorkspaceSurface={split(app, options) {
const lifecycle = new AbortController();
const dispose = panels(app, lifecycle.signal, options);
return { dispose() { dispose(); lifecycle.abort(); } };
},attach(app,button,{className='pd-workspace-maximised',onChange=()=>{},allowPwa=false,hideChrome=false}={}){
const lifecycle = new AbortController(), listenerOptions = {signal:lifecycle.signal};
const disposePanels = panels(app, lifecycle.signal);
const isPwa = () => document.documentElement.dataset.standalone === 'true' || !!window.PlotDirectorPwa?.standalone;