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

181 lines
16 KiB
JavaScript

const { chromium } = require('playwright');
const assert = require('node:assert/strict');
const base = 'http://127.0.0.1:5238';
(async () => {
const browser = await chromium.launch();
const errors = [];
try {
const context = await browser.newContext({ viewport: { width: 1600, height: 1100 } });
const page = await context.newPage();
page.on('pageerror', e => errors.push(e.message));
let state, posted;
await page.route('**/RelationshipMap/State?**', async route => {
const scene = Number(new URL(route.request().url()).searchParams.get('sceneId'));
const model = structuredClone(state);
if (scene >= 100 && scene < 200) model.relationships.find(r => r.characterRelationshipID === 1).currentStateName = 'Distrustful';
await route.fulfill({ json: model });
});
await page.route('**/RelationshipMap/Save', async route => { posted = route.request().postData(); await route.fulfill({ status: 200 }); });
assert.equal((await page.goto(base + '/fixture?page=relationships')).status(), 200);
await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace);
state = await page.evaluate(() => {
const w = window.PlotDirectorRelationshipWorkspace;
return { cast: w.cast, relationships: w.relationships(), links: w.cy.edges().map(e => ({ characterRelationshipID: e.data('relationshipID'), sourceCharacterID: Number(e.data('source').slice(2)), targetCharacterID: Number(e.data('target').slice(2)), relationshipLabel: e.data('label'), cssClass: e.classes().join(' '), intensity: e.data('intensity') })) };
});
assert.equal(await page.locator('[data-rw-character]').count(), 75);
await page.locator('[data-map-fit]').click();
assert(await page.evaluate(() => { const cy = window.PlotDirectorRelationshipWorkspace.cy, box = cy.nodes(':visible').renderedBoundingBox(); return box.w <= cy.width()+1 && box.h <= cy.height()+1; }), 'Fit all contains the large cast');
for (const [side, min, max] of [['top',8,10],['left',4,7],['bottom',0,3]]) {
const values = await page.locator(`.rw-${side} [data-rw-character]`).evaluateAll(nodes => nodes.map(n => Number(n.dataset.importance)));
assert(values.length && values.every(n => n >= min && n <= max), side + ' importance population');
}
const supportingIds = await page.locator('.rw-left [data-rw-character]').evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.rwCharacter)));
assert.deepEqual(supportingIds,state.cast.filter(c=>c.characterImportance>=4&&c.characterImportance<8).map(c=>c.characterID),'complete Supporting collection in existing order');
assert.equal(await page.locator('.rw-rail [data-rw-entry], #rwPaletteTab, #rwDetailTab, #rwImportance, [data-rw-group]').count(),0,'Details-only right rail and no redundant importance controls');
assert(await page.locator('#rwDetailPanel').isVisible(),'contextual Details permanently available on desktop');
const filteringMs = await page.evaluate(() => { const start = performance.now(); const search = document.getElementById('rwSearch'); for (let i=0;i<100;i++) { search.value = i%2 ? 'cast' : 'elan'; search.dispatchEvent(new Event('input')); } return performance.now()-start; });
assert(filteringMs < 1500, '100 large-cast filter updates remain responsive');
console.log(`75-character filtering: ${filteringMs.toFixed(1)}ms for 100 updates`);
await page.locator('#rwSearch').fill('elan');
assert.equal(await page.locator('[data-rw-entry]:not([hidden])').count(), 1, 'accent-insensitive search');
await page.locator('[data-rw-character="1"]').click();
let centred = await page.evaluate(() => {
const cy = window.PlotDirectorRelationshipWorkspace.cy, p = cy.$id('c-1').renderedPosition();
return Math.abs(p.x - cy.width()/2) < 2 && Math.abs(p.y - cy.height()/2) < 2 && cy.$id('c-1').hasClass('is-focus');
});
assert(centred, 'click focuses and centres');
await page.locator('#rwSearch').fill('');
for (const [id,name] of [[10,'Cast 10'],[7,'Cast 07'],[3,'Cast 03']]) {
await page.locator('#rwSearch').fill(name);
assert.equal(await page.locator('[data-rw-entry]:not([hidden])').count(),1,'whole-cast search '+name);
await page.locator(`[data-rw-character="${id}"]`).click();
assert(await page.evaluate(id=>{const cy=window.PlotDirectorRelationshipWorkspace.cy,n=cy.$id(`c-${id}`),p=n.renderedPosition();return n.hasClass('is-focus')&&Math.abs(p.x-cy.width()/2)<2&&Math.abs(p.y-cy.height()/2)<2},id),'search focuses and centres '+name);
assert.match(await page.locator('[data-map-detail-title]').innerText(),new RegExp(name),'Details tracks search selection');
}
await page.locator('#rwSearch').fill('elan');await page.locator('[data-rw-character="1"]').click();await page.locator('#rwSearch').fill('');
// Exercise actual HTML drag events with a DataTransfer and rendered Cytoscape hit-testing.
async function drag(id, target, mapHandle = false) {
await page.evaluate(({id,target,mapHandle}) => {
const button = mapHandle ? document.querySelector('[aria-label="Drag to another character, or click to add a relationship"]') : document.querySelector(`[data-rw-character="${id}"]`), graph = document.getElementById('relationshipMapGraph');
const cy = window.PlotDirectorRelationshipWorkspace.cy;
let p = target ? cy.$id(`c-${target}`).renderedPosition() : null;
if (!p) {
const boxes=cy.nodes(':visible').map(n=>n.renderedBoundingBox());
for(let y=24;y<graph.clientHeight-15&&!p;y+=24) for(let x=64;x<graph.clientWidth-15&&!p;x+=24)
if(!boxes.some(b=>x>=b.x1-4&&x<=b.x2+4&&y>=b.y1-4&&y<=b.y2+4))p={x,y};
if(!p)throw new Error('Fixture has no empty drop location');
}
const box = graph.getBoundingClientRect(), dataTransfer = new DataTransfer();
button.dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer }));
for (const type of ['dragover','drop']) graph.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, clientX: box.left+p.x, clientY: box.top+p.y }));
}, {id,target,mapHandle});
}
await drag(7, null);
assert.equal(await page.locator('#rwDialog').evaluate(e=>e.open),false,'Supporting blank drop does not create a relationship');
assert(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.$id('c-7').visible()));
await drag(7,1);await page.locator('#rwDialog[open]').waitFor();
assert.equal(await page.locator('[name="SourceID"]').inputValue(),'7','Supporting drag onto another character opens editor');
await page.keyboard.press('Escape');
await drag(75, null);
assert.equal(await page.locator('#rwDialog').evaluate(e => e.open), false, 'blank drop does not create relationship');
assert(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-75').visible()));
await drag(1, 2, true);
await page.locator('#rwDialog[open]').waitFor();
assert.equal(await page.locator('[name="SourceID"]').inputValue(), '1', 'map connector supplies source');
await page.keyboard.press('Escape');
await drag(2, 1);
await page.locator('#rwDialog[open]').waitFor();
assert.equal(await page.locator('[name="SourceID"]').inputValue(), '2');
assert.equal(await page.locator('[name="TargetID"]').inputValue(), '1');
assert.equal(await page.locator('[name="SceneID"]').inputValue(), '');
const zoom = await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom());
await page.locator('#rwForm [type="submit"]').click();
await page.waitForFunction(() => !document.getElementById('rwDialog').open);
await page.waitForTimeout(300);
assert(posted.includes('SourceID') && posted.includes('__RequestVerificationToken'), 'canonical POST with antiforgery token');
assert.equal(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()), zoom, 'save preserves zoom');
assert(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-1').hasClass('is-focus')), 'save preserves focus');
await page.locator('#rwTimeline').fill('100');
await page.waitForFunction(() => document.getElementById('rwStatus').textContent.includes('relationships.'));
await page.waitForTimeout(250);
await page.locator('#rwListView').click();
assert(await page.locator('#rwListPanel').isVisible(), 'List replaces the canvas rather than extending the page');
assert.match(await page.locator('.relationship-map-list').innerText(), /Distrustful/, 'timeline and list share state');
await page.locator('#rwMapView').click();
await page.locator('#rwConnect').focus(); await page.keyboard.press('Enter');
assert.equal(await page.locator('[name="SceneID"]').inputValue(), '100', 'timeline defaults editor scene');
await page.keyboard.press('Escape');
await page.locator('#rwNext').click(); await page.waitForTimeout(300);
assert.equal(await page.locator('#rwTimeline').inputValue(), '200');
await page.locator('#rwPrevious').click(); await page.waitForTimeout(300);
assert.equal(await page.locator('#rwTimeline').inputValue(), '100');
await page.evaluate(() => { window.PlotDirectorRelationshipWorkspace.cy.zoom(.7); window.PlotDirectorRelationshipWorkspace.cy.pan({x:50,y:70}); });
await page.waitForTimeout(350);
await page.reload(); await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace);
assert(Math.abs(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()) - .7) < .01, 'layout restores zoom');
assert.deepEqual(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.pan()), {x:50,y:70}, 'layout restores manual pan');
for (const width of [1600, 1200, 700, 390]) {
await page.setViewportSize({ width, height: 1100 });
const dimensions = await page.locator('#rwBoard').evaluate(e => ({ width: e.clientWidth, scroll: e.scrollWidth, canvas: document.getElementById('relationshipMapGraph').clientWidth }));
assert(dimensions.scroll <= dimensions.width + 1 && dimensions.canvas >= 200, 'usable canvas at ' + width);
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 2), 'no horizontal page overflow at ' + width);
assert(await page.evaluate(() => document.documentElement.scrollHeight <= innerHeight + 2), 'no page scrolling at ' + width);
if (width <= 800) {
await page.locator('#rwCharacters').click();
assert.equal(await page.locator('.rw-left [data-rw-character]').count(), 75, 'mobile drawer keeps the complete cast available');
await page.locator('#rwSearch').fill('elan');
await page.locator('[data-rw-character="1"]').click();
assert(await page.locator('.rw-navigation').isHidden(), 'selection returns touch users to the map');
await page.locator('#rwCharacters').click(); await page.locator('#rwSearch').fill(''); await page.locator('#rwCharacters').click();
}
}
await page.setViewportSize({width:1600,height:1000});
for (const theme of ['modern-light','modern-dark','warm-light','warm-dark']) {
await page.evaluate(theme => { document.documentElement.dataset.appTheme = theme; document.documentElement.dataset.theme = theme.endsWith('dark') ? 'dark':'light'; }, theme);
await page.waitForTimeout(100);
const themeState = await page.evaluate(() => {
const w = window.PlotDirectorRelationshipWorkspace, style = getComputedStyle(document.documentElement);
const swatch = document.createElement('span'); swatch.style.color = style.getPropertyValue('--pd-text'); document.body.append(swatch); const expected = getComputedStyle(swatch).color; swatch.remove();
return { node:w.cy.$id('c-1').style('color'), expected, portrait:w.cy.$id('c-1').data('portrait'), canvas:getComputedStyle(document.getElementById('relationshipMapGraph')).backgroundColor };
});
assert(themeState.portrait.startsWith('data:image/svg+xml'), theme+' initials fallback on graph nodes');
assert.equal(themeState.node.replace(/\s/g,''), themeState.expected.replace(/\s/g,''), theme+' graph text follows active theme tokens');
assert(themeState.canvas, theme+' themed canvas');
await page.screenshot({path:`/srv/repos/relationships-${theme}.png`});
}
assert(await page.locator('#rwApp').evaluate(e=>e.getBoundingClientRect().width>=innerWidth-12), 'workspace uses essentially the entire application width');
const beforeMax = await page.locator('#relationshipMapGraph').boundingBox();
await page.locator('#rwMaximise').click();
assert.equal(await page.locator('#rwMaximise').getAttribute('aria-pressed'), 'true');
const afterMax = await page.locator('#relationshipMapGraph').boundingBox(); assert(afterMax.height>beforeMax.height, 'maximise grows the application canvas');
await page.keyboard.press('Escape');
assert.equal(await page.locator('#rwMaximise').getAttribute('aria-pressed'), 'false');
await page.locator('#rwClearFocus').click();
assert.equal(await page.locator('#rwFocusName').innerText(), 'Full cast');
await page.locator('#rwPan').click(); assert(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.autoungrabify()));
await page.locator('#rwSelect').click(); assert(!(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.autoungrabify())));
assert.equal(await page.locator('.list-section').count(), 0, 'no relationship list below workspace');
// Existing application menu discovery in installed mode, plus keyboard fallback.
const pwa = await browser.newContext({ viewport: { width: 1600, height: 1100 } });
await pwa.addInitScript(() => Object.defineProperty(navigator, 'standalone', { value: true }));
const app = await pwa.newPage(); app.on('pageerror', e => errors.push(e.message));
await app.goto(base + '/fixture?page=relationships');
await app.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace);
await app.locator('[data-rw-character="1"]').evaluate(e => e.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX:100,clientY:200 })));
await app.locator('.pd-context-popup').waitFor();
assert.match(await app.locator('.pd-context-popup').innerText(), /Focus|relationship|Edit character/);
await app.keyboard.press('Escape');
await app.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('r-1').emit('cxttap'));
await app.locator('.pd-context-popup').waitFor();
assert.match(await app.locator('.pd-context-popup').innerText(), /Edit at timeline point/, 'line actions use application menu');
await app.keyboard.press('Escape');
assert(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('r-1').hasClass('relationship-category-friendship')), 'existing line category retained');
await app.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-18').emit('cxttap'));
await app.locator('.pd-context-popup').waitFor();
assert.match(await app.locator('.pd-context-popup').innerText(), /Edit character|Add relationship/, 'map context actions remain available after focusing');
await app.keyboard.press('Escape');
assert.deepEqual(errors, []);
console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout and PWA menu');
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });