Update ribbon focus state in place without workspace layout flash

This commit is contained in:
Nick Beckley 2026-10-31 21:30:14 +00:00
parent 9294ee89d6
commit 95a9b0b4e2
5 changed files with 104 additions and 3 deletions

View File

@ -55,3 +55,13 @@ Display contains the original Book, Chapter, Scene and Character focus selectors
## PWA maximise correction
Maximise contributes a separate essential Workspace ribbon group, outside Display, so the command does not collapse into a dropdown. Browser placement is unchanged. The old PWA maximised bounds matched the already full-height normal workspace, making the state toggle appear ineffective. Maximising now temporarily hides the title and ribbon-heading rows while preserving the command row, allowing the existing header ResizeObserver to give the reclaimed height to the canvas. The same canonical class, Restore action and Escape handler restore the normal view; no native fullscreen or saved ribbon preference is involved. Browser tests assert direct command placement and a measurable canvas-height increase, as well as Restore and Escape.
## PWA focus stability
Instrumentation reproduced a contextual-ribbon rebuild on every Focus caption text change. The main-content MutationObserver treated the label replacement as a structural contribution change and called refresh, which cleared and rebuilt the ribbon. Display briefly rendered its stacked form in the expanded layout before the next animation-frame fitting pass restored the compact menu. At 1440px the measured header jumped from 179px to 348px and the workspace moved down 169px for a frame; the same focus sequence in ordinary browser mode retained its bounds. Cytoscape and the canvas DOM were not remounted.
The observer now distinguishes text/decorative caption updates on already bound buttons from actual contribution-structure changes. It updates existing command bindings and full-label tooltips in place without clearing ribbon nodes or accounting markers and without rerunning the ribbon fitting pass. Expanded Focus controls reserve fixed label/clear-action space and truncate long names; compact-menu visibility rules are preserved. Genuine additions/removals of commands, fields or contributions still trigger composition. No delays, overlays, fades, animation or interaction blocking are involved.
Maximise retains its existing PWA ribbon placement and behaviour; the browser control is also unchanged.
`relationship-focus-stability.cjs` exercises diagram-node focus changes, short/long captions, rapid sequences and clearing focus in browser/PWA presentation at 1440px and 1700px. It samples the header, workspace, four palettes/panels, canvas and timeline on every animation frame, asserts the ribbon nodes remain identical with zero rebuilds, and checks graph instance, node positions, zoom, Details and Focus updates. Existing ribbon, workspace and shared-toolbar tests remain regression gates.

View File

@ -16,7 +16,8 @@
"test:desktop-promotion": "node desktop-promotion.cjs",
"test:record-workspaces": "node record-workspaces.cjs",
"test:relationships": "node relationship-workspace.cjs",
"test:relationships-ribbon": "node relationships-ribbon.cjs"
"test:relationships-ribbon": "node relationships-ribbon.cjs",
"test:relationship-focus": "node relationship-focus-stability.cjs"
},
"devDependencies": {
"chart.js": "4.4.9",

View File

@ -0,0 +1,61 @@
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const base='http://127.0.0.1:5238';
(async()=>{
const browser=await chromium.launch();
try {
for(const pwa of [false,true]) for(const width of [1440,1700]) {
const context=await browser.newContext({viewport:{width,height:1000}});
if(pwa) await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base+'/fixture?page=relationships',{waitUntil:'domcontentloaded'});
await page.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace);
const result=await page.evaluate(async()=>{
const frame=()=>new Promise(r=>requestAnimationFrame(r)); await frame();await frame();await frame();
const w=window.PlotDirectorRelationshipWorkspace, cy=w.cy, canvas=document.getElementById('relationshipMapGraph');
const selectors=['.pd-application-header','#rwApp','.rw-top','.rw-navigation','.rw-rail','.rw-centre','#relationshipMapGraph','.rw-timeline','.rw-bottom'];
const bounds=()=>selectors.map(s=>{const r=document.querySelector(s).getBoundingClientRect();return [r.x,r.y,r.width,r.height]});
const baseline=bounds(), samples=[];
const controls=document.querySelector('[data-pwa-context-controls]');
const nodes=[...controls.children], focusButton=controls.querySelector('[data-command-identity="handler:rwFocusName"]');
let rebuilds=0;const observer=new MutationObserver(records=>{rebuilds+=records.filter(r=>r.target===controls).length});
observer.observe(controls,{childList:true});
const sourceReplace=controls.replaceChildren;controls.replaceChildren=function(...args){rebuilds++;return sourceReplace.apply(this,args)};
const long='Alexandra Catherine Montgomery With An Exceptionally Long Character Name';
w.cast.find(c=>c.characterID===2).characterName='Jo';
w.cast.find(c=>c.characterID===3).characterName=long;
cy.$id('c-2').data('label','Jo');cy.$id('c-3').data('label',long);
cy.zoom(.9);
const positions=cy.nodes().map(n=>({id:n.id(),p:{...n.position()}}));
for(const id of [1,2,3,2,1,3]) {
cy.$id(`c-${id}`).emit('tap');samples.push(bounds());
for(let f=0;f<5;f++){await frame();samples.push(bounds())}
if(document.querySelector('[data-map-detail-title]').textContent!==w.cast.find(c=>c.characterID===id).characterName) throw new Error('Details did not track focus');
if(!cy.$id(`c-${id}`).hasClass('is-focus'))throw new Error('Graph focus did not update');
}
for(const id of [1,3,2,3,1,2,1,3,2,3]) {cy.$id(`c-${id}`).emit('tap');samples.push(bounds())}
for(let f=0;f<5;f++){await frame();samples.push(bounds())}
const caption=focusButton?.textContent.trim(), tooltip=focusButton?.title;
document.getElementById('rwClearFocus').click();
for(let f=0;f<5;f++){await frame();samples.push(bounds())}
observer.disconnect();
const sameNodes=nodes.length===controls.children.length&&nodes.every((n,i)=>n===controls.children[i]);
return {baseline,samples,rebuilds,sameNodes,caption,tooltip,long,positionsUnchanged:positions.every(({id,p})=>Math.abs(cy.$id(id).position().x-p.x)<.01&&Math.abs(cy.$id(id).position().y-p.y)<.01),sameGraph:w.cy===cy&&document.getElementById('relationshipMapGraph')===canvas,zoom:cy.zoom(),clearLabel:focusButton?.textContent.trim()};
});
result.samples.forEach((sample,index)=>sample.forEach((rect,region)=>rect.forEach((value,axis)=>assert(Math.abs(value-result.baseline[region][axis])<=1,`${pwa?'PWA':'web'} ${width}: shifted region ${region} axis ${axis} sample ${index}: ${value} vs ${result.baseline[region][axis]}`))));
if(pwa) {assert.equal(result.rebuilds,0,'focus must not rebuild contextual ribbon');assert(result.sameNodes,'ribbon nodes retained');}
assert(result.sameGraph&&result.positionsUnchanged,'canvas instance and node layout retained');assert.equal(result.zoom,.9);
if(pwa){assert.equal(result.caption,'Focus: '+result.long);assert.equal(result.tooltip,result.caption);assert.equal(result.clearLabel,'Full cast');
assert.equal(await page.locator('[data-pwa-context-controls]').getByRole('button',{name:'Maximise workspace',exact:true,includeHidden:true}).count(),1);
assert.equal(await page.locator('[data-pwa-context-controls] .pd-context-group:empty').count(),0);
await page.evaluate(()=>{const source=document.createElement('button');source.id='focusFixtureCommand';source.type='button';source.textContent='Fixture command';source.dataset.ribbonIcon='list';source.onclick=()=>window.__fixtureInvoked=true;document.querySelector('.rw-view-switch').append(source)});
const fixture=page.locator('[data-pwa-context-controls]').getByRole('button',{name:'Fixture command',exact:true,includeHidden:true});
await fixture.waitFor({state:'attached'});await fixture.evaluate(button=>button.click());assert(await page.evaluate(()=>window.__fixtureInvoked),'new structural contribution still binds its source');
await page.locator('#focusFixtureCommand').evaluate(button=>button.remove());await fixture.waitFor({state:'detached'});
} else {assert(await page.locator('.rw-toolbar').isVisible());assert(await page.locator('#rwMaximise').isVisible());}
assert.deepEqual(errors,[]);console.log(`PASS focus stability: ${pwa?'PWA':'web'} ${width}px, ${result.samples.length} frame/bounds samples${pwa ? ', no ribbon rebuilds' : ''}`);
await context.close();
}
}finally{await browser.close()}
})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -157,3 +157,14 @@ body.rw-page [data-pwa-context-controls] .pd-context-form[data-pwa-fields="stack
/* Maximise gains real canvas height while retaining the ribbon's Restore action. */
html[data-standalone="true"] body.rw-page:has(#rwApp.rw-maximised) .pd-application-header .pd-titlebar,
html[data-standalone="true"] body.rw-page:has(#rwApp.rw-maximised) .pd-application-header .pd-ribbon-heading { display: none; }
/* Reserve focus and clear-action space across short/long captions and clear state. */
body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] details[data-compact="false"] > .pd-ribbon-commands {
display: grid; grid-template-columns: 150px 65px; gap: 4px; width: 219px;
}
body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] .pd-context-command {
width: 100%; min-width: 0; max-width: 100%;
}
body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] .pd-context-command > span {
display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
}

View File

@ -15,6 +15,7 @@
const icons = shell.querySelector('[data-pwa-icon-catalog]')?.content;
let queued = false, bindings = [], lastInvoker = null, nextKey = 0;
const sourceKeys = new WeakMap();
const boundCommands = new WeakSet();
const borrowedCommands = new Map();
function restoreRibbonCommands() {
for (const [command, marker] of borrowedCommands) marker.replaceWith(command);
@ -174,6 +175,7 @@
return content;
}
function bindState(source, target) {
boundCommands.add(source);
const update = () => {
const disabled = source.matches(':disabled, .disabled, [aria-disabled="true"]');
if ('disabled' in target) target.disabled = disabled;
@ -185,7 +187,11 @@
else target.removeAttribute(attribute);
}
target.classList.toggle('is-active', source.getAttribute('aria-pressed') === 'true');
if (source.matches('button')) target.querySelector('span').textContent = caption(source);
if (source.matches('button')) {
const label = caption(source);
if (target.querySelector('span').textContent !== label) target.querySelector('span').textContent = label;
target.title = label;
}
};
bindings.push(update); update();
}
@ -406,7 +412,19 @@
}
function queueRefresh() { if (!queued) { queued = true; requestAnimationFrame(refresh); } }
const observer = new MutationObserver(records => {
if (records.some(record => record.type === 'childList' && (record.target.closest?.(sourceSelector) || [...record.addedNodes, ...record.removedNodes].some(node => node.nodeType === 1 && (node.matches(sourceSelector) || node.querySelector(sourceSelector)))))) { sourceRoots = [main]; queueRefresh(); }
const structural = records.some(record => {
if (record.type !== 'childList') return false;
const command = record.target.closest?.('button');
const nodes = [...record.addedNodes, ...record.removedNodes];
const declarations = `${sourceSelector},a,button,form,input,select,textarea`;
// A bound button's caption is live state, not a new contribution.
// Keep its ribbon node, accounted markers and fitted groups intact.
if (command && boundCommands.has(command) && nodes.every(node => node.nodeType === 3
|| (node.nodeType === 1 && !node.matches(declarations) && !node.querySelector(declarations)))) return false;
return record.target.closest?.(sourceSelector) || nodes.some(node => node.nodeType === 1
&& (node.matches(sourceSelector) || node.querySelector(sourceSelector)));
});
if (structural) { sourceRoots = [main]; queueRefresh(); }
else bindings.forEach(update => update());
});
function observe() { observer.observe(main, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled', 'hidden', 'aria-disabled', 'aria-pressed', 'aria-current', 'aria-selected', 'aria-expanded', 'class'] }); }