PlotDirector/PlotLine.Tests/Browser/record-workspaces-dev.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

59 lines
10 KiB
JavaScript

// Explicit Dev-only operational check. Credentials remain in the private identity file.
const {chromium}=require('playwright');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const assert=require('node:assert/strict');
const base='https://dev.plotdirector.com';let stage='setup';
async function frames(p){await p.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))))}
async function group(p,label='Record'){const menu=p.locator(`.pd-context-group[aria-label="${label}"] details[data-compact=true]`);if(await menu.count()&&await menu.getAttribute('open')===null)await menu.locator('summary').click()}
(async()=>{
const file=process.argv[2];assert(file?.startsWith('/tmp/pd-dev-browser-'));const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));
const profile=fs.mkdtempSync(path.join(os.tmpdir(),'pd-record-dev-'));const context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1080}});const cdp=await context.browser().newBrowserCDPSession();let installed=false;
const failures=[];context.on('page',p=>p.on('pageerror',e=>failures.push(e.message)));
try{
const tab=context.pages()[0];await tab.goto(base+'/Account/Login');await tab.locator('[name=Email]').fill(identity.Email);await tab.locator('[name=Password]').fill(identity.Password);await tab.locator('form button[type=submit]').click();await tab.waitForURL(base+'/Projects');
const ids=identity.Records||{};const write=()=>{identity.Records=ids;fs.writeFileSync(file,JSON.stringify(identity),{mode:0o600})};
async function create(area,query,fields){
if(ids[area])return ids[area];stage='create '+area;assert.equal((await tab.goto(base+`/${area}/Create${query}`)).status(),200);
for(const [name,value]of Object.entries(fields)){const el=tab.locator(`[name="${name}"]`);if(await el.evaluate(e=>e.tagName)==='SELECT')await el.selectOption(String(value));else await el.fill(String(value))}
await Promise.all([tab.waitForNavigation(),tab.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).click()]);
assert(!new URL(tab.url()).pathname.endsWith('/Save'),area+' validation: '+await tab.locator('main .validation-summary-errors, main .field-validation-error').allTextContents());
let id=Number(new URL(tab.url()).pathname.match(/\/Details\/(\d+)/)?.[1]);
if(!id){const href=await tab.locator(`main a[href*="/${area}/Edit/"],main a[href*="/${area}/Details/"]`).first().getAttribute('href');id=Number(href.match(/\/(?:Edit|Details)\/(\d+)/)[1])}
assert(id>0);ids[area]=id;write();return id;
}
const project=await create('Projects','',{ProjectName:'Desktop record layout verification',Description:'An isolated fixture for desktop workspace checks.'});
const book=await create('Books',`?projectId=${project}`,{BookTitle:'Record layout verification',BookNumber:1});
const chapter=await create('Chapters',`?bookId=${book}`,{ChapterTitle:'Opening chapter',ChapterNumber:1});
const character=await create('Characters',`?projectId=${project}`,{CharacterName:'Verification character',DefaultDescription:'A record with profile information and a broad description.\n\nThe image editor should sit alongside this text in a wide Desktop window.'});
const location=await create('Locations',`?projectId=${project}`,{LocationName:'Verification location',Description:'A location used only by the automated record-layout check.'});
const asset=await create('StoryAssets',`?projectId=${project}`,{AssetName:'Verification object',Description:'An object record with state and location metadata.'});
const line=await create('PlotLines',`?projectId=${project}`,{PlotLineName:'Verification plot line'});
const thread=await create('PlotThreads',`?projectId=${project}`,{ThreadTitle:'Verification thread',PlotLineID:line});
const editors=[['Projects',project],['Books',book],['Chapters',chapter],['Characters',character],['Locations',location],['StoryAssets',asset],['PlotLines',line],['PlotThreads',thread]];
for(const [area,id]of editors){stage='browser '+area;assert.equal((await tab.goto(base+`/${area}/Edit/${id}`)).status(),200);assert(await tab.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).isVisible());assert((await tab.locator('form.pd-record-form').boundingBox()).width<=980.5);}
stage='install and launch';const manifestId=base+'/Projects';await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/Projects'});installed=true;await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+`/Books/Edit/${book}`});const app=await opened;await app.waitForLoadState();assert(await app.evaluate(()=>window.PlotDirectorPwa.standalone));
for(const [area,id]of editors){
stage='desktop '+area;assert.equal((await app.goto(base+`/${area}/Edit/${id}`)).status(),200);await frames(app);await group(app);
assert.equal(await app.locator('[data-pwa-context-controls] button').filter({hasText:/^Save /}).count(),1);assert(await app.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).isHidden());
for(const width of [1920,1440,800,390]){await app.setViewportSize({width,height:1080});await frames(app);assert(await app.locator('form.pd-record-form').evaluate(e=>e.scrollWidth<=e.clientWidth+1),area+' overflow '+width)}
await app.setViewportSize({width:1920,height:1080});await app.screenshot({path:`/tmp/pd-record-dev-${area}.png`,fullPage:true});
}
stage='validation and save';await app.goto(base+`/Books/Edit/${book}`);await app.locator('[name=BookTitle]').fill('');await group(app);await app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).click();await app.locator('[data-valmsg-for=BookTitle].field-validation-error').waitFor();
await app.locator('[name=BookTitle]').fill('Updated layout verification');await group(app);await Promise.all([app.waitForURL(base+`/Books/Details/${book}`),app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).click()]);
await app.goto(base+`/Books/Edit/${book}`);assert.equal(await app.inputValue('[name=BookTitle]'),'Updated layout verification');
stage='themes and keyboard';await app.goto(base+`/Characters/Edit/${character}`);for(const theme of ['warm-light','modern-light','modern-dark','warm-dark','rose-pink','baby-blue']){await app.evaluate(t=>{const r=document.documentElement;r.dataset.appTheme=t;r.dataset.theme=t.endsWith('-dark')?'dark':'light';r.dataset.bsTheme=r.dataset.theme;dispatchEvent(new CustomEvent('plotdirector:theme-changed',{detail:{theme:t}}));},theme);await app.screenshot({path:`/tmp/pd-record-dev-theme-${theme}.png`,fullPage:true});}
await app.bringToFront();await app.locator('[name=CharacterName]').press('Tab');assert(await app.locator('[data-remove-alias]').first().evaluate(e=>document.activeElement===e),'existing alias actions follow the name');await app.keyboard.press('Tab');assert(await app.locator('[data-alias-input]').evaluate(e=>document.activeElement===e),'alias input follows existing alias');
await app.locator('[name=Height]').press('Tab');assert(await app.locator('[name=EyeColour]').evaluate(e=>document.activeElement===e),'logical profile tab sequence');await app.keyboard.press('Shift+Tab');assert(await app.locator('[name=Height]').evaluate(e=>document.activeElement===e),'reverse tab sequence');
await app.locator('[name=CharacterName]').click({button:'right'});assert(await app.locator('.pd-context-popup').isVisible(),'existing edit context menu');await app.keyboard.press('Escape');
await app.keyboard.down('Control');await app.locator('[name=CharacterName]').click({button:'right'});await app.keyboard.up('Control');assert.equal(await app.locator('.pd-context-popup').count(),0,'Ctrl+right-click native fallback');await app.keyboard.press('Escape');
const other=[`/Books/Details/${book}`,`/Chapters/Details/${chapter}`,`/Characters/Details/${character}`,`/Locations/Details/${location}`,`/StoryAssets/Details/${asset}`,`/ProjectCollaborators?projectId=${project}`,`/Timeline/Settings?projectId=${project}`,'/ManageAccount',`/PlotThreads?projectId=${project}`];
for(const route of other){stage='details/management '+route.split('?')[0];assert.equal((await tab.goto(base+route)).status(),200);assert.equal((await app.goto(base+route)).status(),200);for(const width of [1920,800,390]){await app.setViewportSize({width,height:1080});assert(await app.locator('main').evaluate(e=>e.scrollWidth<=e.clientWidth+1),'main overflow '+route+' '+width)}await app.setViewportSize({width:1920,height:1080});}
// Pause real HTML before activation, compare key geometry on several domain shapes.
for(const [area,id]of editors.filter(([a])=>['Books','Characters','Chapters','Locations','PlotLines'].includes(a))){
stage='first paint '+area;let release,reached;const gate=new Promise(r=>release=r),blocked=new Promise(r=>reached=r);const url=base+`/${area}/Edit/${id}?recordpaint=1`;
await app.route('**/record-parser-gate.js',async r=>{reached();await gate;await r.fulfill({contentType:'application/javascript',body:''})});
await app.route(url,async r=>{const response=await r.fetch();await r.fulfill({response,body:(await response.text()).replace('</main>','<script src="/record-parser-gate.js"></script></main>')})});
const loading=app.goto(url);try{await Promise.race([blocked,new Promise((_,reject)=>setTimeout(()=>reject(Error('Parser gate not reached')),10000))]);await frames(app);const sample=()=>app.locator('form.pd-record-form').evaluate(e=>{const r=e.getBoundingClientRect();return[r.x,r.y,r.width,...[...e.querySelectorAll('.pd-record-fields>div')].flatMap(n=>{const x=n.getBoundingClientRect();return[x.x,x.y,x.width,x.height]})]});const before=await sample();release();await loading;await frames(app);assert.deepEqual(await sample(),before,area+' initial layout shift');console.log('PASS zero record layout shift '+area)}finally{release();await app.unroute(url);await app.unroute('**/record-parser-gate.js')}
}
assert.deepEqual(failures,[]);console.log('PASS real authenticated Dev record workspaces: eight domains, real standalone install, four widths, Browser controls, validation/round-trip Save, six themes, keyboard/context menus, details/settings/management and first paint.');
}finally{if(installed)await cdp.send('PWA.uninstall',{manifestId:base+'/Projects'}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true})}
})().catch(e=>{console.error('Stage:',stage,e);process.exitCode=1});