PlotDirector/PlotLine.Tests/Browser/workspace-refinements.cjs

43 lines
17 KiB
JavaScript

// Actual Razor and shared assets; catalogue snapshot exported from a disposable qualified SQL clone.
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
const taxonomy=JSON.parse(fs.readFileSync(process.env.PD_TAXONOMY_FIXTURE||'/tmp/pd-refinements-taxonomy.json','utf8'));
const base='http://127.0.0.1:5238',out='/tmp/pd-refinements-evidence',installed=process.argv.includes('--installed');fs.mkdirSync(out,{recursive:true});
const type=key=>taxonomy.find(t=>t.key===key).value;
(async()=>{let browser,context,cdp,profile;const results=[];try{
if(installed){profile=fs.mkdtempSync('/tmp/pd-refinements-pwa-');context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}});browser=context.browser();cdp=await browser.newBrowserCDPSession();await context.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});
}else browser=await chromium.launch();
for(const count of [50,500,1000]){
let page;if(installed){const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId:base+'/Projects',url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await browser.newPage({viewport:{width:1440,height:1000}});
const errors=[];page.on('pageerror',e=>errors.push(e.message));let clock=0,requests=[],receipts=new Map();let records=Array.from({length:count},(_,i)=>({id:i+1,name:i===0?'Zeta system':i===1?'Alpha country':i===2||i===4?'Control room':i===3?'Western district':i===5?'Omega colony':`Level ${String(i+1).padStart(4,'0')}`,parent:i<6?([null,null,1,2,4,null][i]):i<105?(i===6?6:i):null,type:type(['house','city','room','residential','flat'][i%5]),typeName:'',classification:'',description:i%3===0?'Complete, author-entered synthetic description.\n'+('A substantial location history remains visible. '.repeat(15)):'',aliases:i===4?['Old observatory']:[],maps:[],floors:[],scenes:0,relationships:0,characters:0,assets:0,quickAdd:'0',detection:'0',version:`v${clock++}`}));
for(const [offset,name]of ['Amber bay','Zebra gate','Birch lane'].entries()){const record=records[(count===50?9:105)+offset];record.parent=4;record.name=name;}
const directory=()=>({canEdit:true,types:taxonomy.filter(t=>t.assignable),taxonomy,locations:records});
await page.route('**/LocationWorkspace/Directory?*',route=>route.fulfill({json:directory()}));await page.route('**/LocationWorkspace/Picker?*',route=>route.fulfill({json:directory()}));await page.route('**/LocationWorkspace/Taxonomy',route=>route.fulfill({json:taxonomy}));
await page.route('**/LocationWorkspace/Assign',route=>{const input=route.request().postDataJSON(),previous=[];requests.push(input);for(const c of input.changes){const r=records.find(r=>r.id===c.id);assert.equal(r.version,c.version);const old=input.attribute==='parent'?r.parent==null?'':String(r.parent):r[input.attribute];if(old===c.value)continue;previous.push({id:r.id,value:old});if(input.attribute==='parent')r.parent=c.value?Number(c.value):null;else r[input.attribute]=c.value;r.version=`v${clock++}`;}const token=`receipt-${clock}`;receipts.set(token,{attribute:input.attribute,previous});return route.fulfill({json:{attribute:input.attribute,changes:previous.map(c=>({id:c.id,value:input.changes.find(x=>x.id===c.id).value,version:records.find(r=>r.id===c.id).version})),undoToken:token}});});
await page.route('**/LocationWorkspace/Undo',route=>{const receipt=receipts.get(route.request().postDataJSON().token);const changes=receipt.previous.map(c=>{const r=records.find(r=>r.id===c.id);if(receipt.attribute==='parent')r.parent=c.value?Number(c.value):null;else r[receipt.attribute]=c.value;r.version=`v${clock++}`;return{id:r.id,value:c.value,version:r.version};});return route.fulfill({json:{attribute:receipt.attribute,changes}});});
await page.route('**/LocationWorkspace/Merge',route=>{const input=route.request().postDataJSON();requests.push({merge:input});assert(input.confirm);assert.equal(input.sourceVersion,records.find(r=>r.id===input.sourceId).version);assert.equal(input.targetVersion,records.find(r=>r.id===input.targetId).version);for(const r of records)if(r.parent===input.sourceId)r.parent=input.targetId;records=records.filter(r=>r.id!==input.sourceId);return route.fulfill({json:{id:input.targetId}});});
const start=performance.now();await page.goto(base+`/locations-workspace-fixture?count=${count}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();const loadMs=Math.round(performance.now()-start),row=id=>page.locator(`[data-location-id="${id}"]`),attribute=key=>page.locator(`[data-attribute=type][data-value="${type(key)}"]`),group=key=>page.locator(`[data-attribute=type][data-value="@${key}"]`),expand=async locator=>{const b=locator.locator('.pd-attribute-expand');if(await b.getAttribute('aria-expanded')==='false')await b.click();};
await expand(group('premises'));await expand(attribute('residential'));assert(await attribute('house').isVisible());assert.equal(await group('premises').locator('[data-assign]').count(),0);assert.equal(await attribute('residential').locator('[data-assign]').count(),1);
const residentialValues=new Set(['residential','house','flat'].map(type)),expected=records.filter(r=>residentialValues.has(r.type)).length;assert.equal(Number(await attribute('residential').locator('[data-count]').textContent()),expected);
await attribute('residential').locator('[data-attribute-filter]').click();assert.match(await page.locator('[data-result-count]').textContent(),new RegExp(`^${expected} of `));await page.getByRole('button',{name:'Cards',exact:true}).click();assert.equal(await page.locator('[data-location-id]').count(),expected);
await page.getByRole('button',{name:'Select displayed',exact:true}).click();await expand(attribute('institutional'));await attribute('hospital').locator('[data-assign]').click();await page.waitForTimeout(100);assert.equal(requests.at(-1).changes.length,expected);assert.equal(await page.locator('[data-location-id]').count(),0);await page.locator('[data-undo]').click();await page.waitForTimeout(100);assert.equal(records.filter(r=>residentialValues.has(r.type)).length,expected);await page.locator('[data-clear-filters]').click();await page.getByRole('button',{name:'Hierarchy',exact:true}).click();
if(count===50){
await row(1).locator('[data-location-name]').click();await page.locator('[data-clear-selection]').click();await attribute('house').locator('[data-attribute-filter]').dragTo(row(2));await page.waitForTimeout(100);assert.equal(records[1].type,type('house'));await page.locator('[data-undo]').click();await page.waitForTimeout(100);assert.equal(records[1].type,type('city'));
await row(2).locator('[data-drag-location]').dragTo(attribute('house'));await page.waitForTimeout(100);assert.equal(records[1].type,type('house'));await page.locator('[data-undo]').click();await page.waitForTimeout(100);
await page.reload();await page.locator('[data-location-records][aria-busy=false]').waitFor();assert(await attribute('house').isVisible(),'nested category state persists');await row(1).locator('[data-location-name]').click();
await page.locator('[data-details]').getByRole('button',{name:'Location type',exact:true}).click();const typeDialog=page.locator('dialog.pd-location-picker-dialog');await typeDialog.getByRole('searchbox',{name:'Search location types'}).fill('Office');assert.equal(await typeDialog.getByRole('button',{name:'Office',exact:true}).count(),2);assert.equal(await typeDialog.locator('[data-picker-id=office-room] svg').evaluate(n=>getComputedStyle(n).color),await attribute('room').locator('svg').evaluate(n=>getComputedStyle(n).color));await typeDialog.locator('[data-picker-id=office-room] .pd-location-picker-name').click();assert.match(await typeDialog.locator('[role=status]').textContent(),/Interior spaces \/ Room \/ Office/);await typeDialog.getByRole('button',{name:'Choose type',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[0].type,type('office-room'));await page.locator('[data-undo]').click();await page.waitForTimeout(100);
await page.getByRole('button',{name:'Change parent',exact:true}).click();let dialog=page.locator('[data-location-dialog]');const roots=await dialog.locator('[data-picker-id][aria-level="1"]').evaluateAll(ns=>ns.map(n=>n.dataset.pickerId));assert.deepEqual(roots,['','2','6','1']);assert.equal(await dialog.locator('[data-picker-id="1"]').getAttribute('aria-disabled'),'true');await dialog.locator('[data-picker-id="1"]>button').click();assert.equal(await dialog.locator('[data-picker-id="3"]').getAttribute('aria-disabled'),'true');await dialog.locator('[data-picker-id="2"]>button').click();await dialog.locator('[data-picker-id="4"]>button').click();assert.deepEqual(await dialog.locator('[aria-level="3"] .pd-location-picker-name').allTextContents(),['Amber bay','Birch lane','Control room','Zebra gate']);
await dialog.getByRole('searchbox',{name:'Search locations'}).fill('old observatory');assert(await dialog.locator('[data-picker-id="5"]').isVisible());assert(await dialog.locator('[data-picker-id="2"]').isVisible());await dialog.getByRole('searchbox',{name:'Search locations'}).fill('Alpha country / Western district');assert(await dialog.locator('[data-picker-id="5"]').isVisible());await dialog.locator('[data-picker-id="5"] .pd-location-picker-name').click();assert.match(await dialog.locator('[role=status]').textContent(),/Alpha country \/ Western district \/ Control room/);await page.screenshot({path:`${out}/picker-${installed?'pwa':'browser'}.png`});await page.locator('[data-dialog-save]').click();await page.waitForTimeout(100);assert.equal(records[0].parent,5);assert.equal(records[2].parent,1);await page.reload();await page.locator('[data-location-records][aria-busy=false]').waitFor();assert.equal(records[0].parent,5);
await page.locator('[data-expand=true]').click();await row(1).locator('[data-location-name]').click();await page.getByRole('button',{name:'Change parent',exact:true}).click();dialog=page.locator('[data-location-dialog]');await dialog.getByRole('searchbox',{name:'Search locations'}).fill('nothing matches this');assert(await dialog.getByText(/No matching locations/).isVisible());await dialog.getByRole('button',{name:'Clear search',exact:true}).click();await dialog.locator('[data-picker-id=""]').focus();await page.keyboard.press('ArrowDown');await page.keyboard.press('Enter');assert.match(await dialog.locator('[role=status]').textContent(),/Alpha country/);await dialog.locator('[data-picker-id=""]').click();await page.locator('[data-dialog-save]').click();await page.waitForTimeout(100);assert.equal(records[0].parent,null);assert.equal(records[2].parent,1);
await row(1).locator('[data-location-name]').click();await page.locator('[data-details]').getByRole('button',{name:'Location type',exact:true}).click();await typeDialog.getByRole('searchbox',{name:'Search location types'}).fill('house');await typeDialog.getByRole('button',{name:'House',exact:true}).click();await typeDialog.getByRole('button',{name:'Choose type',exact:true}).click(); // Existing value is a no-op.
await row(1).evaluate(n=>n.scrollIntoView({block:'center',behavior:'instant'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));await row(1).click({button:'right'});await page.getByRole('menuitem',{name:'Location type',exact:true}).hover();await page.getByRole('menuitem',{name:'Buildings and premises',exact:true}).hover();await page.getByRole('menuitem',{name:'Residential',exact:true}).hover();await page.getByRole('menuitemradio',{name:'Assign Residential',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[0].type,type('residential'));
await page.locator('[data-sort]').selectOption('desc');await row(1).evaluate(n=>n.scrollIntoView({block:'center',behavior:'instant'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));await row(1).click({button:'right'});await page.getByRole('menuitem',{name:'Merge with another location…',exact:true}).click();dialog=page.locator('[data-location-dialog]');await dialog.getByRole('searchbox',{name:'Search locations'}).fill('Control room');assert.equal(await dialog.getByRole('button',{name:'Control room',exact:true}).count(),2);assert.equal(await dialog.locator('[data-picker-id="3"]').getAttribute('aria-disabled'),'true');await dialog.locator('[data-picker-id="5"] .pd-location-picker-name').click();await page.locator('[data-dialog-save]').click();assert.match(await page.locator('[data-dialog-error]').textContent(),/confirm/);await dialog.locator('input[type=checkbox]').check();await page.locator('[data-dialog-save]').click();await dialog.waitFor({state:'hidden'});assert(requests.some(r=>r.merge?.targetId===5));
}
if(count>50){await row(1).locator('[data-location-name]').click();const pickerStart=performance.now();await page.getByRole('button',{name:'Change parent',exact:true}).click();const dialog=page.locator('[data-location-dialog]');await dialog.getByRole('searchbox',{name:'Search locations'}).fill('Level 0105');const deep=dialog.locator('[data-picker-id="105"]');await deep.waitFor();assert(Number(await deep.getAttribute('aria-level'))>=99);await deep.locator('.pd-location-picker-name').click();assert((await dialog.locator('[role=status]').textContent()).length>1000);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));if(count===1000)await page.screenshot({path:`${out}/picker-large-${installed?'pwa':'browser'}.png`});await page.locator('[data-dialog-save]').click();await page.waitForTimeout(100);assert.equal(records[0].parent,105);assert.equal(records[2].parent,1);console.log('Large/deep picker',count,Math.round(performance.now()-pickerStart),'ms');}
await page.locator('[data-clear-filters]').click();await page.getByRole('button',{name:'Cards',exact:true}).click();const heights=await page.locator('.location-record').evaluateAll(ns=>ns.slice(0,10).map(n=>Math.round(n.getBoundingClientRect().height)));assert(new Set(heights).size>1);
const measurements=[];for(const width of [1024,1440,1920]){await page.setViewportSize({width,height:1000});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);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));if(count===50&&width===1440)await page.screenshot({path:`${out}/taxonomy-${installed?'pwa':'browser'}-${theme}.png`});if(count===50&&width===1440){await page.locator('[data-details]').getByRole('button',{name:'Location type',exact:true}).click();const popup=page.locator('dialog.pd-location-picker-dialog');await popup.getByRole('searchbox',{name:'Search location types'}).fill('Office');assert.equal(await popup.locator('[data-picker-id=office-room] svg').evaluate(n=>getComputedStyle(n).color),await attribute('room').locator('svg').evaluate(n=>getComputedStyle(n).color));await popup.getByRole('button',{name:'Cancel',exact:true}).click();}}measurements.push(width);}
const divider=page.getByRole('separator',{name:'Resize left panel'});for(const direction of ['Shift+ArrowRight','Shift+ArrowLeft']){for(let step=0;step<12;step++)await divider.press(direction);const rects=await page.locator('[data-groups] .pd-attribute-row').evaluateAll(ns=>ns.filter(n=>n.getClientRects().length&&n.querySelector('[data-assign]')).map(n=>({count:n.querySelector('[data-count]').getBoundingClientRect().right,assign:n.querySelector('[data-assign]').getBoundingClientRect().right})));assert(new Set(rects.map(r=>Math.round(r.assign))).size<=1,'Assign column aligns');assert(new Set(rects.map(r=>Math.round(r.count))).size<=1,'count column aligns: '+JSON.stringify(rects));}
assert.deepEqual(errors,[]);results.push({count,loadMs,assignments:requests.length,themes:7,widths:measurements});await page.close();
}
fs.writeFileSync(`${out}/results-${installed?'pwa':'browser'}.json`,JSON.stringify({status:'passed',results},null,2));console.log('PASS hierarchical picker, canonical taxonomy, nested counts/filtering/assignment/Undo, native bidirectional drag, menus, merge review, persistence, seven themes, widths and variable cards',results);
}finally{if(cdp)await cdp.send('PWA.uninstall',{manifestId:base+'/Projects'}).catch(()=>{});if(context)await context.close();else if(browser)await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1;});