PlotDirector/PlotLine.Tests/Browser/character-attributes.cjs

93 lines
21 KiB
JavaScript

// Real compiled Razor + production shell/assets, with isolated in-memory HTTP fixtures.
const {chromium}=require('playwright');const os=require('node:os'),path=require('node:path');const assert=require('node:assert/strict');const fs=require('node:fs');
(async()=>{const installed=process.argv.includes('--installed'),profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-attributes-pwa-')):null;
const persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}):null;
const browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null;
const manifestId='http://127.0.0.1:5238/Projects';
if(installed){await persistent.pages()[0].goto('http://127.0.0.1:5238/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:'http://127.0.0.1:5238/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:'http://127.0.0.1:5238/fixture?page=calendar-test'});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return page;}
const results=[];try{
const widthCheck=process.argv.includes('--width-check'),before=process.argv.includes('--before');
for(const count of widthCheck?[100]:[10,100,500]){
const page=await newPage(),errors=[];console.log('ACCEPTANCE',installed?'installed':'browser',count);page.on('pageerror',e=>errors.push(e.message));
const groups=await (await page.request.get('http://127.0.0.1:5238/character-attribute-definitions-fixture')).json();
let clock=0,requests=[],undo=new Map(),records=Array.from({length:count},(_,i)=>({id:i+1,name:`Fixture character ${String(i+1).padStart(3,'0')}`,version:`v${clock++}`,values:{type:'unclassified',importance:(i+1)%3===0?'10':(i+1)%3===1?'6':'2',life:'',sex:i===0?'legacy:Recorded custom sex':i%4===1?'1':i%4===2?'2':i%4===3?'3':'',quickAdd:'0'}}));
await page.route('**/CharacterAttributes/Directory?*',route=>route.fulfill({json:{canEdit:true,groups,characters:records}}));
await page.route('**/CharacterAttributes/Assign',async route=>{const input=route.request().postDataJSON();requests.push(input);assert(route.request().headers().requestverificationtoken);const previous=[],changed=[];for(const c of input.changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Characters changed in another window.'}});if(r.values[input.attribute]!==c.value){previous.push(structuredClone(r));r.values[input.attribute]=c.value;r.version=`v${clock++}`;changed.push(r);}}const token=`undo-${clock}`;undo.set(token,{previous,versions:changed.map(r=>[r.id,r.version])});await route.fulfill({json:{saved:true,characters:changed,undoToken:token}});});
await page.route('**/CharacterAttributes/Undo',async route=>{const token=route.request().postDataJSON().token,state=undo.get(token);assert(state);if(state.versions.some(([id,version])=>records.find(r=>r.id===id).version!==version))return route.fulfill({status:409,json:{message:'Characters changed in another window.'}});const changed=state.previous.map(old=>{const r=records.find(r=>r.id===old.id);r.values=old.values;r.version=`v${clock++}`;return r;});await route.fulfill({json:{saved:true,characters:changed}});});
assert.deepEqual(groups.map(g=>g.id),['importance','life','sex','type','quickAdd']);
const start=Date.now();await page.goto(`http://127.0.0.1:5238/character-attributes-fixture?count=${count}`);await page.locator('[data-attribute="importance"]').first().waitFor();const load=Date.now()-start;
await page.locator('[data-attribute-groups] details[data-attribute-group=type]').evaluate(n=>n.open=true); // Independent fixture cases explicitly restore this now-persisted group.
const expose=async node=>{await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^="Dismiss"]').forEach(b=>b.click()));await node.scrollIntoViewIfNeeded();};
const card=id=>page.locator(`.character-card[data-drag-id="${id}"]`),value=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`);
assert.deepEqual(await card(1).locator('[data-attribute-indicators]>span').evaluateAll(nodes=>nodes.map(n=>n.title.split(':')[0])),['Story importance','Life status','Sex','Character Type','Quick Add Bar']);
assert.equal(await card(1).locator('[title="Sex: Recorded custom sex"] path').getAttribute('d'),groups.find(g=>g.id==='sex').fallback.path);
// Use native mouse drags with both endpoints visible; Bootstrap smooth scrolling
// otherwise moves a sticky sidebar endpoint after Playwright locates the source.
async function nativeAssignment(id,a,v,toCharacter){await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^="Dismiss"]').forEach(b=>b.click()));await card(id).evaluate(n=>n.scrollIntoView({block:'start',inline:'nearest',behavior:'instant'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));const row=value(a,v);await row.evaluate(n=>{const host=n.closest('[data-attribute-sidebar]'),r=n.getBoundingClientRect(),h=host.getBoundingClientRect(),bottom=Math.min(h.bottom,innerHeight),top=Math.max(h.top,0);if(r.bottom>bottom-8)host.scrollTop+=r.bottom-bottom+8;if(r.top<top+8)host.scrollTop-=top-r.top+8});const source=toCharacter?row.locator('button').first():card(id).locator('[data-character-drag]'),target=toCharacter?card(id):row,from=await source.boundingBox(),to=await target.boundingBox(),x=to.x+to.width/2,y=Math.min(to.y+to.height/2,950);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+8,from.y+from.height/2,{steps:3});await page.mouse.move(x,y,{steps:12});await page.mouse.move(x+1,y+1);await page.mouse.up();}
const reverse=(id,a,v)=>nativeAssignment(id,a,v,false),forward=(a,v,id)=>nativeAssignment(id,a,v,true);
if(widthCheck){
const measurements=[],directory='/tmp/pd-character-width';fs.mkdirSync(directory,{recursive:true});
for(const width of [1280,1920,2560,3840]){
await page.setViewportSize({width,height:1080});await page.evaluate(()=>window.scrollTo({top:0,behavior:'instant'}));
const measure=await page.evaluate(()=>{const rect=s=>document.querySelector(s).getBoundingClientRect();const workspace=rect('[data-character-attributes]'),parent=rect('.plotline-help-main'),sidebar=rect('[data-attribute-sidebar]'),grid=rect('.character-card-grid'),toolbar=rect('.character-attribute-toolbar');return {viewport:innerWidth,parentWidth:parent.width,workspaceWidth:workspace.width,left:workspace.left-parent.left,right:parent.right-workspace.right,sidebarWidth:sidebar.width,gridWidth:grid.width,columns:getComputedStyle(document.querySelector('.character-card-grid')).gridTemplateColumns.split(' ').length,toolbarWidth:toolbar.width,overflow:document.documentElement.scrollWidth>innerWidth};});
assert(!measure.overflow);assert(Math.abs(measure.sidebarWidth-256)<1);assert(Math.abs(measure.toolbarWidth-measure.workspaceWidth)<1);
if(!before){assert(Math.abs(measure.left-16)<1);assert(Math.abs(measure.right-16)<1);assert(Math.abs(measure.workspaceWidth-(measure.parentWidth-32))<1);}
await page.screenshot({path:`${directory}/${before?'before':'after'}-${installed?'pwa':'browser'}-${width}.png`});
await page.locator('[data-attributes-toggle]').click();const collapsed=await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width);assert(collapsed>measure.gridWidth+250);assert(await page.locator('[data-attribute-sidebar]').isHidden());await page.locator('[data-attributes-toggle]').click();
await page.evaluate(()=>window.scrollTo({top:1200,behavior:'instant'}));const sticky=await page.locator('[data-attribute-sidebar]').boundingBox();assert(sticky.y>=0&&sticky.y+sticky.height<=1081);await page.evaluate(()=>window.scrollTo({top:0,behavior:'instant'}));measure.collapsedGridWidth=collapsed;measurements.push(measure);
}
if(!before){assert(measurements[3].columns>measurements[1].columns);assert(measurements[3].gridWidth>measurements[1].gridWidth+1500);}
await page.goto('http://127.0.0.1:5238/relationship-evolution-fixture');assert.equal(await page.locator('.pd-record-canvas').count(),1);assert.equal(await page.locator('.pd-workspace-full-width').count(),0,'other pages do not opt in');assert(await page.locator('.pd-record-canvas').evaluate(n=>n.getBoundingClientRect().width<document.documentElement.clientWidth-100));
assert.deepEqual(errors,[]);fs.writeFileSync(`${directory}/${before?'before':'after'}-${installed?'pwa':'browser'}.json`,JSON.stringify(measurements,null,2));console.log('PASS workspace widths',measurements);await page.close();continue;
}
const divider=page.getByRole('separator',{name:'Resize Attributes panel'});await divider.press('ArrowRight');await divider.press('ArrowRight');
if(groups.some(g=>g.id==='type')){
await forward('type','person',1);await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Person"]'));
await reverse(2,'type','artificial');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Artificial being"]'));
await card(1).locator('[data-character-select]').check();await card(2).locator('[data-character-select]').check();
await value('type','animal').getByRole('button',{name:/Assign/}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Animal"]'));
await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Artificial being"]'));assert.equal(records[0].values.type,'person');
await value('type','unclassified').getByRole('button',{name:/Assign/}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Unclassified"]'));
await page.locator('[data-clear-selection]').click();
await forward('type','animal',1);await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Animal"]'));assert.equal(await value('type','animal').locator('button').first().getAttribute('aria-pressed'),'false');
if(count===100){fs.mkdirSync('/tmp/pd-character-types',{recursive:true});await page.screenshot({path:`/tmp/pd-character-types/${installed?'pwa':'browser'}-assigned.png`});}
await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Unclassified"]'));
await reverse(2,'type','animal');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Animal"]'));await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Character Type: Unclassified"]'));
await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'Character Type',exact:true}).hover();assert.equal(await page.getByRole('menuitemradio',{name:'Unclassified',exact:true}).getAttribute('aria-checked'),'true');
if(count===100)await page.screenshot({path:`/tmp/pd-character-types/${installed?'pwa':'browser'}-context-menu.png`});
await page.getByRole('menuitemradio',{name:'Animal',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Animal"]'));await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Character Type: Unclassified"]'));
await page.locator('[data-attribute-groups] summary').filter({hasText:'Character Type'}).click();
}
assert.equal(await page.locator('.character-card').count(),count);const biography=await card(1).locator('.visual-card-heading p.muted').textContent();assert(biography.includes('Complete biography for character 1'));const heights=await page.locator('.character-card').evaluateAll(ns=>ns.slice(0,9).map(n=>n.getBoundingClientRect().height));assert(new Set(heights.map(Math.round)).size>1);
await forward('importance','10',1);await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [data-attribute-indicators]').textContent===''&&document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Major"]'));assert.equal(records[0].values.importance,'10');
await reverse(2,'importance','6');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]'));assert.equal(records[1].values.importance,'6');
await card(1).locator('[data-character-select]').check();await card(2).locator('[data-character-select]').check();await value('importance','2').getByRole('button',{name:/Assign/}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2);
await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Major"]'));assert.equal(records[1].values.importance,'6');
await reverse(1,'importance','2');await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2);await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]'));
await card(1).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'2 characters selected',exact:true}).waitFor();await page.getByRole('menuitem',{name:'Life status',exact:true}).hover();await page.getByRole('menuitemradio',{name:'Living',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Life status: Living"]'));assert.equal(requests.at(-1).changes.length,2);
await page.locator('[data-clear-selection]').click();
// Modifier selection follows displayed order and does not navigate character links.
await card(1).locator('h2 a').click({modifiers:['Control']});await card(3).locator('h2 a').click({modifiers:['Shift']});assert.equal(await page.locator('[data-character-select]:checked').count(),3);assert(page.url().includes('character-attributes-fixture'));
await card(4).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(4).click({button:'right'});assert.equal(await page.getByRole('menuitem',{name:'Open character',exact:true}).count(),1);await page.keyboard.press('Escape');
await card(1).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'Story importance · Mixed values',exact:true}).hover();assert.equal(await page.getByRole('menuitemradio',{checked:true}).count(),0);await page.keyboard.press('Escape');
await page.locator('[data-clear-selection]').click();await card(3).focus();await page.waitForTimeout(400);await page.keyboard.press('Shift+F10');await page.getByRole('menuitem',{name:'Story importance',exact:true}).focus();await page.keyboard.press('ArrowRight');await page.getByRole('menuitemradio',{name:'Major',exact:true}).waitFor();assert.equal(await page.getByRole('menuitemradio',{name:'Major',exact:true}).getAttribute('aria-checked'),'true');await page.keyboard.press('Escape');assert.equal(await page.locator('.pd-context-popup').count(),0);
await card(4).evaluate(n=>n.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:innerWidth-2,clientY:innerHeight-2})));await page.getByRole('menuitem',{name:'Quick Add Bar',exact:true}).hover();const menus=await page.locator('.pd-context-popup').evaluateAll(ns=>ns.map(n=>{const r=n.getBoundingClientRect();return {x:r.x,y:r.y,right:r.right,bottom:r.bottom}}));assert(menus.every(r=>r.x>=0&&r.y>=0&&r.right<=1440&&r.bottom<=1000));await page.getByRole('menuitemradio',{name:'Included',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="4"] [title="Quick Add Bar: Included"]'));assert.equal(requests.at(-1).changes.length,1);
const beforeCancel=requests.length;await page.evaluate(()=>{const b=document.querySelector('[data-attribute="importance"][data-value="10"] button'),transfer=new DataTransfer();b.dispatchEvent(new DragEvent('dragstart',{bubbles:true,dataTransfer:transfer}));document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));document.dispatchEvent(new DragEvent('dragend',{bubbles:true,dataTransfer:transfer}));});assert.equal(requests.length,beforeCancel);await page.waitForTimeout(260);
await value('importance','10').locator('button').first().click();assert(await card(2).isHidden());await page.locator('[data-select-visible]').click();const visibleCount=await page.locator('.character-card:visible').count();assert.equal(await page.locator('[data-character-select]:checked').count(),visibleCount);await page.locator('[data-clear-filter]').click();await page.locator('[data-clear-selection]').click();
const width=await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width);await page.locator('[data-attributes-toggle]').click();assert(await page.locator('[data-attribute-sidebar]').isHidden());assert(await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width)>width);await page.locator('[data-attributes-toggle]').click();
if(count>=100){await page.evaluate(()=>{let n=document.querySelector('[data-character-attributes]');for(;n;n=n.parentElement){if(/auto|scroll/.test(getComputedStyle(n).overflowY)&&n.scrollHeight>n.clientHeight){n.scrollTo({top:1200,behavior:'instant'});return;}}window.scrollTo({top:1200,behavior:'instant'});});const box=await page.locator('[data-attribute-sidebar]').boundingBox();assert(box.y>=0&&box.y<1000&&box.y+box.height<=1001);await page.evaluate(()=>{let n=document.querySelector('[data-character-attributes]');for(;n;n=n.parentElement)n.scrollTo({top:0,left:0,behavior:'instant'});window.scrollTo({top:0,behavior:'instant'});});}
await page.evaluate(()=>document.querySelectorAll('.pd-toast button[aria-label^="Dismiss"]').forEach(b=>b.click()));
if(count===100){
for(const direction of ['Shift+ArrowRight','Shift+ArrowLeft']){for(let step=0;step<12;step++)await divider.press(direction);const positions=await page.locator('[data-attribute-groups] .pd-attribute-row').evaluateAll(ns=>ns.filter(n=>n.getClientRects().length).map(n=>({count:Math.round(n.querySelector('[data-count]').getBoundingClientRect().right),assign:Math.round(n.querySelector('[data-assign]').getBoundingClientRect().right)})));assert.equal(new Set(positions.map(p=>p.count)).size,1);assert.equal(new Set(positions.map(p=>p.assign)).size,1);}
await divider.press('Home');
}
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);if(count===100)await page.screenshot({path:`/tmp/character-attributes-${installed?'installed-':''}${theme}.png`});}
for(const [width,height] of [[1920,1080],[1440,900],[1366,768],[1280,720],[1024,768],[768,1024],[390,844]]){await page.setViewportSize({width,height});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));if(width>850&&count>=100){await page.evaluate(()=>window.scrollTo({top:1200,behavior:'instant'}));const bounds=await page.locator('[data-attribute-sidebar]').boundingBox();assert(bounds.y>=0&&bounds.y+bounds.height<=height+1);await page.evaluate(()=>window.scrollTo({top:0,behavior:'instant'}));}}
assert.equal(await card(1).locator('.visual-card-heading p.muted').textContent(),biography);assert.deepEqual(errors,[]);results.push({count,loadMs:load,assignments:requests.length});await page.close();
}
fs.writeFileSync(`/tmp/character-attributes-${installed?'installed-':''}performance.json`,JSON.stringify(results,null,2));console.log('PASS rendered directory: biography/card dimensions, bidirectional drag, bulk, individual prior-value Undo, individual/multi context, keyboard, filters/counts/selection scope, sticky/collapse, themes and responsive widths',results);
}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;});