PlotDirector/PlotLine.Tests/Browser/pwa-context-menu.cjs
Nick Beckley e48889ac05 Complete desktop workspaces, context menus and plot health
Commit the pending application, help and browser regression work. Pin the patched PKCS dependency for the production release.
2026-10-31 09:27:04 +00:00

149 lines
14 KiB
JavaScript

const { chromium } = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const base = 'http://127.0.0.1:5238';
const rootMenu = page => page.locator('body > .pd-context-popup').first();
async function right(page, target, modifiers = {}) {
return target.evaluate((node, keys) => { const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 130, clientY: 240, ...keys }); node.dispatchEvent(event); return event.defaultPrevented; }, modifiers);
}
async function open(page, target) { assert.equal(await right(page, target), true); await rootMenu(page).waitFor(); }
(async () => {
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-context-'));
const context = await chromium.launchPersistentContext(profile, { headless: false, viewport: { width: 1440, height: 1000 } });
const cdp = await context.browser().newBrowserCDPSession();
const errors = []; context.on('page', page => page.on('pageerror', error => errors.push(error.message)));
try {
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: base });
const tab = context.pages()[0]; await tab.goto(base + '/fixture?desktop=StoryBible');
assert.equal(await right(tab, tab.locator('[data-pwa-page-content]')), false, 'browser right-click untouched');
assert.equal(await tab.locator('.pd-context-popup').count(), 0);
const manifestId = base + '/Projects';
await cdp.send('PWA.install', { manifestId, installUrlOrBundleUrl: base + '/fixture' });
await cdp.send('PWA.changeAppUserSettings', { manifestId, displayMode: 'standalone' });
const opened = context.waitForEvent('page'); await cdp.send('PWA.launch', { manifestId, url: base + '/fixture?desktop=StoryBible' });
const app = await opened; await app.waitForLoadState();
assert(await app.evaluate(() => window.PlotDirectorPwa.standalone));
if (await app.locator('#ribbon-surface').isHidden()) { await app.locator('[data-ribbon-collapse]').click(); await app.locator('[data-ribbon-collapse]:not([disabled])').waitFor(); }
for (const url of ['/fixture?desktop=StoryBible','/fixture?desktop=Characters&context=objects','/fixture?page=timeline-render']) {
await app.goto(base + url);
for (const target of [app.locator('[data-pwa-page-content]'), app.locator('main a').first(), app.locator('button').first()]) {
assert.equal(await right(app, target, { ctrlKey: true }), false, 'Ctrl native override');
assert.equal(await app.locator('.pd-context-popup').count(), 0);
}
}
await app.locator('.timeline-scene-card').first().click({button:'right'});
await rootMenu(app).waitFor();await app.keyboard.press('Escape');
// Original route / target selection, not any prior selected scene.
await app.goto(base + '/fixture?page=timeline-render');
await app.locator('.timeline-scene-card[data-scene-id="101"]').evaluate(node => node.classList.add('selected'));
for (const id of [102, 101]) {
const card = app.locator(`.timeline-scene-card[data-scene-id="${id}"]`);
const href = await card.getAttribute('href');
await app.route('**/Timeline?**', route => route.fulfill({ contentType: 'text/html', body: '<p>Original route reached</p>' }));
if (id === 101) { await card.focus(); await app.keyboard.press('Shift+F10'); await rootMenu(app).waitFor(); await app.keyboard.press('Enter'); }
else { await open(app, card); await rootMenu(app).getByRole('menuitem', { name: 'Inspect scene', exact: true }).click(); }
await app.waitForURL(new URL(href, base).href);
assert.equal(new URL(app.url()).searchParams.get('FocusID'), String(id));
await app.unroute('**/Timeline?**'); await app.goto(base + '/fixture?page=timeline-render');
}
// Actual Razor cards: original confirmations, per-object ID and disabled state.
await app.goto(base + '/fixture?desktop=Characters&context=objects');
const cardB = app.locator('[data-pd-context="character"][data-pd-context-id="72"]');
await cardB.locator('button[type=submit]').evaluate(node=>node.addEventListener('click',()=>window.contextArchiveTarget=node.form.querySelector('[name=id]').value));
await open(app, cardB);
assert(await rootMenu(app).getByRole('menuitem', { name: 'Open character', exact: true }).count());
await rootMenu(app).getByRole('menuitem', { name: 'Archive', exact: true }).click();
await app.locator('#plotlineConfirmModal.show').waitFor();
assert.equal(await app.evaluate(()=>window.contextArchiveTarget),'72');
assert.equal(await app.locator('form[data-confirm-message] input[name=id][value="72"]').count(), 1);
await app.locator('#plotlineConfirmModal [data-bs-dismiss=modal]').first().click();
await app.locator('#plotlineConfirmModal').waitFor({ state: 'hidden' });
await cardB.locator('button[type=submit]').evaluate(node => node.disabled = true);
await open(app, cardB);
const unavailable = rootMenu(app).getByRole('menuitem', { name: 'Archive', exact: true });
assert.equal(await unavailable.getAttribute('aria-disabled'), 'true'); await app.screenshot({path:'/tmp/pd-context-disabled-archive.png'}); await unavailable.dispatchEvent('click');
assert.equal(await app.locator('#plotlineConfirmModal.show').count(), 0);
await app.keyboard.press('Escape');
// Keyboard context invocation and focus restoration.
const edit = cardB.locator('a.btn'); await edit.focus(); await app.keyboard.press('Shift+F10');
await rootMenu(app).waitFor(); await app.keyboard.press('ArrowDown'); await app.keyboard.press('Escape');
assert(await edit.evaluate(node => node === document.activeElement));
await app.keyboard.press('ContextMenu');await rootMenu(app).waitFor();await app.keyboard.press('Escape');
await app.goto(base + '/fixture?desktop=Archives&context=objects');
await open(app,app.locator('[data-pd-context="archived item"]'));
assert.equal(await rootMenu(app).getByRole('menuitem',{name:/Edit|Associate/}).count(),0);
await rootMenu(app).getByRole('menuitem',{name:'Delete Forever',exact:true}).click();
await app.locator('#plotlineConfirmModal.show').waitFor();
assert.equal(await app.locator('#plotlineConfirmModal input[data-confirm-delete-input]').count() || await app.locator('#plotlineConfirmModal input').count(),1);
await app.locator('#plotlineConfirmModal [data-bs-dismiss=modal]').first().click();
await app.locator('#plotlineConfirmModal').waitFor({state:'hidden'});
// Clipboard uses the real API and real fields; read-only and disabled remain restricted.
await app.goto(base + '/fixture?desktop=ProjectEdit');
const field = app.locator('textarea[name=Description]');
await field.fill('alpha beta'); await field.evaluate(node => { node.focus(); node.setSelectionRange(6,10); });
assert.equal(await right(app, field, { ctrlKey: true }), false);
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Copy', exact: true }).click();
assert.equal(await app.evaluate(() => navigator.clipboard.readText()), 'beta');
await field.evaluate(node => node.setSelectionRange(6,10));
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Cut', exact: true }).click();
await app.waitForFunction(() => document.querySelector('textarea[name=Description]').value === 'alpha ');
await field.evaluate(node => { node.focus(); node.setSelectionRange(6,6); });
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Paste', exact: true }).click();
await app.waitForFunction(() => document.querySelector('textarea[name=Description]').value === 'alpha beta');
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Select All', exact: true }).click();
assert.deepEqual(await field.evaluate(node => [node.selectionStart,node.selectionEnd]), [0,10]);
await field.evaluate(node => node.readOnly=true); await open(app, field);
assert.equal(await rootMenu(app).getByRole('menuitem',{name:'Cut',exact:true}).getAttribute('aria-disabled'), 'true');
assert.equal(await rootMenu(app).getByRole('menuitem',{name:'Paste',exact:true}).getAttribute('aria-disabled'), 'true');
await app.screenshot({path:'/tmp/pd-context-readonly.png'});
await app.keyboard.press('Escape');
await field.evaluate(node=>{node.readOnly=false;const group=document.createElement('fieldset');group.disabled=true;node.before(group);group.append(node);});
await open(app,field);assert.equal(await rootMenu(app).getByRole('menuitem',{name:'Paste',exact:true}).getAttribute('aria-disabled'),'true');await app.keyboard.press('Escape');
await field.evaluate(node=>node.parentElement.disabled=false);
await field.evaluate(node => { node.readOnly=false; Object.defineProperty(navigator, 'clipboard', { configurable:true, value: { readText:()=>Promise.reject(new DOMException('Denied','NotAllowedError')), writeText:()=>Promise.reject(new DOMException('Denied','NotAllowedError')) } }); });
await open(app, field); await rootMenu(app).getByRole('menuitem',{name:'Paste',exact:true}).click();
await app.locator('.pd-context-feedback').waitFor();
assert.equal(await field.inputValue(),'alpha beta');
// Scene/card primary and drag handlers are not invoked by opening a menu.
await app.goto(base + '/fixture?page=timeline-render');
await app.evaluate(() => { window.primaryClicks=0; document.querySelector('.timeline-scene-card').addEventListener('click',()=>window.primaryClicks++); });
await open(app, app.locator('.timeline-scene-card').first());
assert.equal(await app.evaluate(() => window.primaryClicks), 0);
await app.keyboard.press('Escape');
assert.equal(await app.locator('.timeline-scene-card').first().getAttribute('draggable'), 'true');
// One-level submenus and all corners, real themes and narrow desktop.
await app.goto(base + '/fixture?desktop=StoryBible');
const themes = await app.locator('[data-app-theme-choice]').evaluateAll(nodes=>nodes.map(node=>node.dataset.appThemeChoice));
for (const width of [1440,900]) for (const theme of themes) {
await app.setViewportSize({width,height:900});
await app.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
await app.evaluate(theme=>{const root=document.documentElement;root.dataset.appTheme=theme;root.dataset.theme=root.dataset.bsTheme=theme.endsWith('-dark')?'dark':'light';},theme);
for (const [x,y] of [[1,1],[width-1,1],[1,899],[width-1,899]]) {
await app.locator('[data-pwa-page-content]').evaluate((node,p)=>node.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:p[0],clientY:p[1]})),[x,y]);
const menu=rootMenu(app); const rect=await menu.boundingBox(); const usableWidth=await app.evaluate(()=>document.documentElement.clientWidth);
assert(rect.x>=0&&rect.y>=0&&rect.x+rect.width<=usableWidth&&rect.y+rect.height<=900);
const exp=menu.getByRole('menuitem',{name:'Export',exact:true});
await exp.focus(); await app.keyboard.press('ArrowRight');
const sub=app.locator('body > .pd-context-popup').nth(1); await sub.waitFor();
const subRect=await sub.boundingBox(); assert(subRect.x>=0&&subRect.x+subRect.width<=usableWidth&&subRect.y+subRect.height<=900);
assert.equal(await exp.getAttribute('aria-expanded'),'true'); await app.keyboard.press('ArrowLeft');
assert(await exp.evaluate(node=>node===document.activeElement));
if(x===width-1&&y===899) { await app.mouse.move(10,400); await exp.hover(); await sub.waitFor(); await app.screenshot({path:`/tmp/pd-context-${theme}-${width}.png`}); }
await app.keyboard.press('Escape');
}
}
// Lifecycle and no stale menus through updates/scroll/navigation.
await open(app,app.locator('[data-pwa-page-content]')); await app.mouse.click(800,400); assert.equal(await app.locator('.pd-context-popup').count(),0);
await open(app,app.locator('[data-pwa-page-content]')); await right(app,app.locator('[data-pwa-page-content]')); assert.equal(await app.locator('body > .pd-context-popup').count(),1);
await app.evaluate(()=>window.dispatchEvent(new Event('plotdirector:context-changed'))); assert.equal(await app.locator('.pd-context-popup').count(),0);
await open(app,app.locator('[data-pwa-page-content]')); await app.evaluate(()=>document.dispatchEvent(new Event('scroll'))); assert.equal(await app.locator('.pd-context-popup').count(),0);
const timing = await app.evaluate(()=>{const samples=performance.getEntriesByName('pd-context-menu-open').map(entry=>entry.duration); return { count:samples.length, meanMs:samples.reduce((a,b)=>a+b,0)/samples.length, maxMs:Math.max(...samples) };});
console.log('Context-menu timings ' + JSON.stringify(timing));
await open(app,app.locator('[data-pwa-page-content]')); await app.goto(base+'/fixture?desktop=Characters'); assert.equal(await app.locator('.pd-context-popup').count(),0);
assert.deepEqual(errors,[]);
console.log('PASS PWA context menus: native browser and Ctrl override; exact A/B scene routes; original archive confirmation; disabled/read-only commands; real clipboard Cut/Copy/Paste/Select All; keyboard/focus; all six themes/corners/1440+900 submenu direction; click-away, second context, scroll, update and navigation dismissal; primary click/drag preserved.');
} finally { await context.close(); fs.rmSync(profile,{recursive:true,force:true}); }
})().catch(error=>{console.error(error);process.exitCode=1;});