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

59 lines
20 KiB
JavaScript

// Actual compiled Locations Razor + shared shell. All mutations use synthetic HTTP fixtures.
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:5238',out='/tmp/pd-locations-evidence'+(installed?'/pwa':'');fs.mkdirSync(out,{recursive:true});
(async()=>{const profile=installed?fs.mkdtempSync('/tmp/pd-locations-pwa-'):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null,manifestId=origin+'/Projects',results=[];if(installed){await persistent.pages()[0].goto(origin+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:origin+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});}async function newPage(){if(!installed)return browser.newPage({viewport:{width:1440,height:1000}});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:origin+'/fixture?page=calendar-test'});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return page;}try{for(const count of process.argv.includes('--persistence-only')?[50]:[50,200,500,1000]){
const page=await newPage(),errors=[],timings={};page.on('pageerror',e=>errors.push(e.message));
const types=await (await page.request.get(`${origin}/locations-workspace-types-fixture`)).json();let clock=0,requests=[],undo=new Map(),rejectNext=false,delayDirectory=false,releaseDirectory=null;const records=Array.from({length:count},(_,i)=>({id:i+1,name:['Meridian','Northern coast','Port Halcyon','Observatory','Reading room'][i]||`Location ${String(i+1).padStart(3,'0')}`,parent:i===0||i%13===0?null:i<10?i:Math.floor((i-1)/12)*12+1,type:String(i%9+1),typeName:types[i%9].label,classification:i%4===0?'Fictional':'',description:i%5===0?'':('Salt air drifts through the open windows. The old charts record a coastline changed by generations of storms. ').repeat(i%7+1),quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:i===4?['Quiet study']:[],maps:i%5===0?[{id:1,name:'Coast chart'}]:[],floors:i%7===0?[{id:2,name:'Observatory floors'}]:[],scenes:i%3}));
records[count-1].parent=2147483647;
records[0].maps.push({id:2,name:'Northern chart'});records[0].floors.push({id:3,name:'Annex floor plan'});
if(count>=500){for(let i=count-100;i<count;i++)records[i].parent=i===count-100?1:i;records[count-2].name='Reading room';records[count-1].name='Reading room';}
await page.route('**/LocationWorkspace/Directory?*',async r=>{const snapshot=structuredClone(records);if(delayDirectory){delayDirectory=false;await new Promise(resolve=>releaseDirectory=resolve);}await r.fulfill({json:{canEdit:true,types,locations:snapshot}});});
await page.route('**/LocationWorkspace/Assign',async route=>{assert(route.request().headers().requestverificationtoken);const input=route.request().postDataJSON();requests.push(input);if(rejectNext){rejectNext=false;return route.fulfill({status:409,json:{message:'Simulated concurrent edit rejected.'}});}let changes=input.changes;const ids=new Set(changes.map(c=>c.id));if(input.attribute==='parent')changes=changes.filter(c=>{let p=records.find(r=>r.id===c.id).parent;const seen=new Set();while(p&&!seen.has(p)){if(ids.has(p))return false;seen.add(p);p=records.find(r=>r.id===p)?.parent;}return true;});const previous=[],changed=[];for(const c of changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Changed in another window.'}});previous.push({id:r.id,value:r[input.attribute],version:r.version});r[input.attribute]=input.attribute==='parent'?(c.value?Number(c.value):null):c.value;r.version=`v${clock++}`;changed.push({id:r.id,value:c.value,version:r.version});}const token=`u${clock}`;undo.set(token,{attribute:input.attribute,previous});await route.fulfill({json:{saved:true,changes:changed,attribute:input.attribute,undoToken:token}});});
await page.route('**/LocationWorkspace/Undo',async route=>{const receipt=undo.get(route.request().postDataJSON().token),changes=[];for(const old of receipt.previous){const r=records.find(r=>r.id===old.id);r[receipt.attribute]=old.value;r.version=`v${clock++}`;changes.push({id:r.id,value:old.value?.toString()||'',version:r.version});}await route.fulfill({json:{saved:true,changes,attribute:receipt.attribute,undoToken:'unused-redo-token'}});});
await page.route('**/LocationWorkspace/Create',async route=>{const input=route.request().postDataJSON(),id=records.length+1;records.push({id,name:input.name,parent:input.parentId,type:'',classification:'',description:'',quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:[],maps:[],floors:[],scenes:0});await route.fulfill({json:{id}});});
const shot=async name=>{if(count===50){await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^=Dismiss]').forEach(b=>b.click()));await page.screenshot({path:`${out}/${name}.png`});}};const row=id=>page.locator(`[data-location-id="${id}"]`),attribute=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`);
const start=performance.now();await page.goto(`${origin}/locations-workspace-fixture?count=${count}`);await row(1).waitFor();const loadMs=Math.round(performance.now()-start);const detailsStart=performance.now();await row(1).locator('[data-location-name]').click();timings.detailsMs=Math.round(performance.now()-detailsStart);assert.equal(await page.locator('[data-related] a[href^="/Maps"]').count(),2);assert.equal(await page.locator('[data-related] a[href^="/FloorPlans"]').count(),2);assert.equal(await page.locator('[data-related] a[target]').count(),0);await shot('workspace');
const expandStart=performance.now();await page.getByRole('button',{name:'Expand all',exact:true}).click();await row(5).waitFor();const expandMs=Math.round(performance.now()-expandStart);assert.match(await row(count).getAttribute('title'),/Parent unavailable/);await shot('hierarchy');if(count===50){
const parents=records.map(r=>r.parent);await page.locator('[data-sort]').selectOption('desc');const order=await page.locator('[data-location-id]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.locationId)));for(const r of records)if(r.parent)assert(order.indexOf(r.parent)<order.indexOf(r.id));assert.deepEqual(records.map(r=>r.parent),parents);await page.locator('[data-sort]').selectOption('asc');
await row(1).focus();await page.keyboard.press('Space');assert(await row(1).locator('[data-select-location]').isChecked());await page.keyboard.press('Space');assert(!(await row(1).locator('[data-select-location]').isChecked()));
}
const drag=async(source,target)=>{await source.dragTo(target);await page.waitForTimeout(100);};
await drag(attribute('type','6').locator('button').first(),row(1));await page.waitForFunction(()=>document.querySelector('[data-undo]').hidden===false);assert.equal(records[0].type,'6');await shot('attribute-assignment');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(60);assert.equal(records[0].type,'1');assert(await page.locator('[data-undo]').isHidden());
if(count===50){await page.evaluate(()=>{window.fixtureHints={};document.dispatchEvent(new CustomEvent('pd-presence-connection',{detail:{on:(name,fn)=>window.fixtureHints[name]=fn,onreconnected:()=>{}}}));});delayDirectory=true;await page.evaluate(()=>{const handlers=Object.values(window.PlotDirectorPresenceConnection||{}).find(v=>v&&typeof v==='object'&&Array.isArray(v.contextinvalidated))?.contextinvalidated;if(handlers?.length)for(const handler of handlers)handler({projectId:7});else if(window.fixtureHints.ContextInvalidated)window.fixtureHints.ContextInvalidated({projectId:7});else throw Error('No live invalidation handler registered.');});for(let attempt=0;!releaseDirectory&&attempt<50;attempt++)await page.waitForTimeout(20);assert(releaseDirectory,'live invalidation requests fresh data');await page.waitForTimeout(30);await drag(attribute('type','6').locator('button').first(),row(1));assert.equal(records[0].type,'6');releaseDirectory();await page.waitForTimeout(150);assert.equal(await row(1).getByRole('img',{name:'Room',exact:true}).count(),1);await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(100);}
const noOpRequests=requests.length;await drag(attribute('type','1').locator('button').first(),row(1));assert.equal(requests.length,noOpRequests);rejectNext=true;await drag(attribute('type','6').locator('button').first(),row(1));assert.equal(records[0].type,'1');assert.match(await page.locator('[data-workspace-error]').textContent(),/concurrent/);
await row(2).locator('[data-select-location]').check();await row(3).locator('[data-select-location]').check();const bulkStart=performance.now();await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert.equal(records[1].classification,'Real');assert.equal(records[2].classification,'Real');timings.bulkMs=Math.round(performance.now()-bulkStart);await shot('bulk-assignment');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(60);assert.equal(records[1].classification,'');if(count===50){await page.locator('.locations-centre').evaluate(n=>n.scrollTo({top:0,behavior:'instant'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));await page.locator('[data-selection-menu]').click();await page.getByRole('menuitem',{name:'2 locations selected',exact:true}).waitFor();assert.equal(await page.getByRole('menuitem',{name:'Rename',exact:true}).count(),0);await shot('bulk-context-menu');await page.keyboard.press('Escape');}
if(count===50){
await row(1).locator('[data-expand-id]').click();await page.locator('.locations-centre').evaluate(n=>n.scrollTop=0);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));const from=await row(14).locator('[data-drag-location]').boundingBox(),to=await row(1).boundingBox();
await page.mouse.move(from.x+from.width/2,from.y+from.height/2);await page.mouse.down();await page.mouse.move(from.x+from.width/2+9,from.y+from.height/2,{steps:3});await page.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:10});await page.mouse.move(to.x+to.width/2+1,to.y+to.height/2+1);await page.waitForTimeout(850);assert.equal(await row(1).getAttribute('aria-expanded'),'true');await shot('hover-reparent');await page.mouse.move(to.x+to.width/2+1,to.y+to.height/2);await page.mouse.up();await page.waitForTimeout(150);assert.equal(records[13].parent,1);await row(14).locator('[data-drag-location]').dragTo(page.locator('[data-root-drop]'));await page.waitForTimeout(150);assert.equal(records[13].parent,null);await shot('root-drop');
const beforeInvalid=requests.length;await row(1).locator('[data-drag-location]').dragTo(row(11));await page.waitForTimeout(80);assert.equal(requests.length,beforeInvalid);assert.equal(records[0].parent,null);
}
await page.locator('[data-clear-selection]').click();const reparentStart=performance.now();await row(5).locator('[data-drag-location]').dragTo(row(3));await page.waitForTimeout(100);assert.equal(records[4].parent,3);assert.equal(records[5].parent,5);timings.reparentMs=Math.round(performance.now()-reparentStart);await shot('reparenting');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(100);assert.equal(records[4].parent,4);
await row(4).focus();await page.keyboard.press('F2');const rename=row(4).getByRole('textbox',{name:'Location name'});await rename.fill('West observatory');await shot('inline-rename');const renameStart=performance.now();await rename.press('Enter');await page.waitForTimeout(80);timings.renameMs=Math.round(performance.now()-renameStart);assert.equal(records[3].name,'West observatory');if(count===50){await row(4).focus();await page.keyboard.press('F2');await row(4).getByRole('textbox',{name:'Location name'}).fill('Discard this name');await page.keyboard.press('Escape');assert.equal(records[3].name,'West observatory');}
await row(4).click({button:'right'});await page.getByRole('menu').first().waitFor();await shot('context-menu');await page.keyboard.press('Escape');if(count===50){await row(4).focus();await page.keyboard.press('Shift+F10');await page.getByRole('menu').first().waitFor();await page.keyboard.press('Escape');}
await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.getByRole('textbox',{name:'New location name'}).fill('Chart room');await shot('create-child');await page.locator('[data-dialog-save]').click();await page.waitForTimeout(150);assert.equal(records.at(-1).parent,4);
await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Edit description',exact:true}).click();const description=page.getByRole('textbox',{name:'Location description'});await description.fill('Preserved author prose.\nSecond paragraph.');if(count===50){await row(4).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');page.once('dialog',d=>d.accept());await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.locator('[data-dialog-cancel]').click();assert.equal(await page.locator('[data-description-editor]').count(),0);await page.getByRole('button',{name:'Edit description',exact:true}).click();await description.fill('Preserved author prose.\nSecond paragraph.');}page.once('dialog',d=>d.dismiss());await row(1).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');await shot('details-edit');if(count===50){await drag(attribute('type','6').locator('button').first(),row(4));assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');assert.equal(await page.locator('[data-details]').getByRole('combobox',{name:'Location type',exact:true}).inputValue(),'6');}await page.locator('[data-details]').getByRole('button',{name:'Save',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[3].description,'Preserved author prose.\nSecond paragraph.');
const searchStart=performance.now();await page.locator('[data-search]').fill('Quiet study');await page.waitForTimeout(80);assert(await row(5).isVisible());assert(await row(1).isVisible());const searchMs=Math.round(performance.now()-searchStart);await shot('search-context');await page.locator('[data-clear-search]').click();
await row(1).locator('[data-select-location]').check();const cardsStart=performance.now();await page.getByRole('button',{name:'Cards',exact:true}).click();timings.cardsMs=Math.round(performance.now()-cardsStart);assert(await row(1).locator('[data-select-location]').isChecked());await shot('cards');const heights=await page.locator('.location-record').evaluateAll(ns=>ns.slice(0,12).map(n=>n.getBoundingClientRect().height));assert(new Set(heights.map(Math.round)).size>3);
if(count===50){
const fictional=attribute('classification','Fictional').locator('button').first();await fictional.click();assert(await row(1).isVisible());assert(!(await row(2).count()));const matching=records.filter(r=>r.classification==='Fictional').length;assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+matching+' of '));
await page.getByRole('button',{name:'Hierarchy',exact:true}).click();assert.equal(await fictional.getAttribute('aria-pressed'),'true');assert(await row(1).locator('[data-select-location]').isChecked());await page.getByRole('button',{name:'Cards',exact:true}).click();
await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert(!(await row(1).count()));assert.equal(records[0].classification,'Real');assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+(matching-1)+' of '));await page.getByRole('button',{name:'Undo',exact:true}).first().click();await row(1).waitFor();
await page.locator('[data-clear-filters]').click();await attribute('mapState','yes').locator('button').click();assert.equal(await page.locator('[data-location-id]').count(),records.filter(r=>r.maps.length).length);assert.equal(await attribute('mapState','yes').locator('[data-assign]').count(),0);await page.locator('[data-clear-filters]').click();
await page.locator('[data-branch-filter]').click();await page.getByRole('listbox',{name:'Parent location'}).selectOption('1');await page.locator('[data-dialog-save]').click();const inBranch=r=>{const seen=new Set();while(r&&!seen.has(r.id)){if(r.id===1)return true;seen.add(r.id);r=records.find(x=>x.id===r.parent);}return false;};assert.equal(await page.locator('[data-location-id]').count(),records.filter(inBranch).length);await page.locator('[data-clear-filters]').click();
}
await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await page.locator('[data-clear-selection]').click();const divider=page.getByRole('separator',{name:'Resize left panel'});await divider.press('ArrowRight');const right=page.getByRole('separator',{name:'Resize right panel'});await right.press('ArrowLeft');if(count===50)for(const [handle,delta]of [[divider,55],[right,-55]]){const box=await handle.boundingBox(),before=Number(await handle.getAttribute('aria-valuenow'));await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width/2+delta,box.y+box.height/2,{steps:8});await page.mouse.up();assert(Number(await handle.getAttribute('aria-valuenow'))>=before+50);}await shot('resized-panels');
for(const panel of ['attributes','details']){await page.getByRole('button',{name:panel==='attributes'?'Attributes':'Details',exact:true}).click();assert(await page.locator(`.locations-${panel}`).isHidden());await page.getByRole('button',{name:panel==='attributes'?'Attributes':'Details',exact:true}).click();}
for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(t=>{document.documentElement.dataset.appTheme=t;document.documentElement.dataset.bsTheme=t.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=t.endsWith('dark')?'dark':'light';},theme);await shot(`theme-${theme}`);}
for(const [width,height]of [[1920,1080],[1440,900],[1280,720],[1024,768],[768,1024],[390,844]]){await page.setViewportSize({width,height});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),`no horizontal overflow at ${width}`);}
await page.setViewportSize({width:1440,height:1000});if(count===1000)await page.screenshot({path:`${out}/large-hierarchy.png`});if(count===50){
const widths=await page.locator('.locations-layout').evaluate(n=>[n.style.getPropertyValue('--workspace-left'),n.style.getPropertyValue('--workspace-right')]);
await page.locator('[data-groups]>details').first().evaluate(n=>n.open=false);await page.waitForTimeout(20);
await page.getByRole('button',{name:'Cards',exact:true}).click();await page.getByRole('button',{name:'Details',exact:true}).click();await page.reload();await row(1).waitFor();
assert(await page.locator('.locations-details').isHidden());assert(await page.locator('.locations-cards').count());assert.equal(await page.locator('[data-groups]>details').first().evaluate(n=>n.open),false);
assert.deepEqual(await page.locator('.locations-layout').evaluate(n=>[n.style.getPropertyValue('--workspace-left'),n.style.getPropertyValue('--workspace-right')]),widths);
await page.getByRole('button',{name:'Details',exact:true}).click();await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await row(5).waitFor();await page.locator('[data-groups]>details').first().evaluate(n=>n.open=true);
}
assert.deepEqual(errors,[]);results.push({count,loadMs,expandMs,searchMs,...timings,assignments:requests.length});console.log('PASS',results.at(-1));await page.close();
}fs.writeFileSync(`${out}/after.json`,JSON.stringify(results,null,2));}finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});