54 lines
12 KiB
JavaScript

const {chromium}=require('playwright'),assert=require('node:assert/strict');
const base=process.env.PD_MAPS_STORY_TEST_URL||'http://127.0.0.1:5247';
(async()=>{const browser=await chromium.launch();try{
for(const pwa of [false,true]){
const context=await browser.newContext({viewport:{width:1800,height:1100}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage(),errors=[];page.setDefaultTimeout(12000);page.on('pageerror',e=>errors.push(e.message));let reads=0,geographyWrites=0,annotation=null;
let fixture=await(await context.request.get(base+'/map-story-fixture')).json();
await page.route('**/Maps/Story?**',route=>{reads++;return route.fulfill({json:fixture});});
await page.route('**/Maps/Save',route=>{geographyWrites++;return route.fulfill({status:500,json:{message:'Story must never save geography'}});});
await page.route('**/Maps/Journey?**',route=>{annotation=route.request().postDataJSON();const leg=fixture.legs.find(l=>l.characterID===annotation.characterID&&l.fromSceneID===annotation.fromSceneID&&l.toSceneID===annotation.toSceneID);leg.note=annotation;return route.fulfill({json:{ok:true}});});
await page.goto(base+'/fixture?page=maps&story=true');await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
const geography=await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document));
async function menuFor(locator){const menus=locator.locator('xpath=ancestor::details[@data-compact]');for(const menu of await menus.all())if(await menu.getAttribute('data-compact')==='true'&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();}
async function clickSource(id){if(pwa){const proxy=page.locator(`[data-pwa-context-controls] [data-command-identity="handler:${id}"]`);if(await proxy.count()){await menuFor(proxy);await proxy.click();return;}}const source=page.locator('#'+id),menu=source.locator('xpath=ancestor::details[1]');if(await menu.count()&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();await source.click();}
async function choose(id,value){if(pwa){const label=await page.locator('#'+id).getAttribute('aria-label');const host=page.locator('[data-pwa-context-controls]'),field=host.getByRole('combobox',{name:label,exact:true,includeHidden:true}).or(host.getByRole('listbox',{name:label,exact:true,includeHidden:true}));await menuFor(field);await field.selectOption(String(value));}else await page.locator('#'+id).selectOption(String(value));}
await page.locator('button[data-mode=story]').evaluate(el=>el.click());await page.waitForFunction(()=>!!window.PlotDirectorStoryOverlay?.data);
const canvas=page.locator('#mapsCanvas'),bounds=await canvas.boundingBox();assert.equal(await page.locator('#mapsStoryLayer >g').count(),2,'overview is restrained density, not one marker per scene');
await page.evaluate(()=>{window.__baseSVG=document.getElementById('mapsCanvas');window.__basePiece=document.querySelector('#mapsScene [data-feature-id]');});
await choose('mapStoryLens','scene');await choose('mapStoryScene',90);assert.match(await page.locator('#mapsDetailContent').innerText(),/Harbour morning/);await clickSource('mapStoryNext');assert.match(await page.locator('#mapsDetailContent').innerText(),/Hill arrival/);await clickSource('mapStoryPrevious');assert.match(await page.locator('#mapsDetailContent').innerText(),/Harbour morning/);
assert.equal(await page.locator('a[href="/Scenes/Edit/90"]').count(),1,'map to canonical scene editor');
await choose('mapStoryScene',20);assert.match(await page.locator('#mapsDetailContent').innerText(),/No Location assigned/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),0,'unknown scene has no fake map position');assert.equal(await page.locator('.maps-feature.is-selected').count(),0,'previous scene highlight is cleared for unknown geography');
await choose('mapStoryScene',80);assert.match(await page.locator('#mapsDetailContent').innerText(),/Unmapped/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),0,'matching feature names do not create associations');
await choose('mapStoryScene',30);assert.equal(await page.locator('a[href*="id=2&mode=story"]').count(),1,'child map navigation');assert.equal(await page.locator('a[href*="/FloorPlans/Edit/101?storySceneId=30"]').count(),1,'Floor Plan occupancy context');
await choose('mapStoryLens','character');await choose('mapStoryCharacter1',1);await choose('mapStoryCharacter2',2);
const journeyText=await page.locator('#mapsDetailContent').innerText();assert.match(journeyText,/Ari/);assert.match(journeyText,/Bea/);assert.match(journeyText,/1\. Harbour/);assert.match(journeyText,/3\. Harbour/);assert.match(journeyText,/Unknown/);assert(await page.locator('.maps-story-leg').count()>=2);
await page.locator('.maps-story-leg').first().focus();await page.keyboard.press('Enter');assert.match(await page.locator('#mapsDetailContent').innerText(),/journey leg/);assert.match(await page.locator('#mapsDetailContent').innerText(),/126 kilometres/);assert.match(await page.locator('#mapsDetailContent').innerText(),/Possible travel timing to review/);
await page.locator('#mapsDetailContent details').filter({has:page.locator('summary:text-is("Author-selected travel context")')}).locator('summary').click();await page.locator('#mapStoryJourneyForm [name=travelMethod]').fill('Boat');await page.locator('#mapStoryJourneyForm [name=typicalMinutes]').fill('180');await page.locator('#mapStoryJourneyForm button[type=submit]').click();await page.waitForFunction(()=>window.PlotDirectorStoryOverlay.data.legs.some(l=>l.note?.travelMethod==='Boat'));assert.equal(annotation.travelMethod,'Boat');
await choose('mapStoryLens','chapter');await choose('mapStoryChapter',11);assert.match(await page.locator('#mapsDetailContent').innerText(),/3 scenes/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),2);
await choose('mapStoryLens','plot');await choose('mapStoryPlot1',5);assert.match(await page.locator('#mapsDetailContent').innerText(),/67%/);assert.equal(await page.locator('#mapsStoryLayer >g').count(),1);assert(await page.locator('#mapsScene .map-story-muted').count()>=1,'unrelated geography fades rather than disappears');
await choose('mapStoryLens','time');await choose('mapStoryCharacter1',0);await choose('mapStoryCharacter2',0);await choose('mapStoryTime','2026-01-01T09:30:00');assert.match(await page.locator('#mapsDetailContent').innerText(),/Last known: Hill town/);assert.match(await page.locator('#mapsDetailContent').innerText(),/Unknown person/);assert.match(await page.locator('#mapsDetailContent').innerText(),/position between scenes is not established/);
await choose('mapStoryTime','2026-01-01T10:30:00');assert.match(await page.locator('#mapsDetailContent').innerText(),/latest confirmed appearance has no known Location/);
await choose('mapStoryLens','overview');await clickSource('mapStoryGaps');assert.match(await page.locator('#mapsDetailContent').innerText(),/Unmapped town/);assert.match(await page.locator('#mapsDetailContent').innerText(),/No Location assigned/);
await clickSource('mapStoryObservations');assert.match(await page.locator('#mapsDetailContent').innerText(),/Possible travel timing to review/);
assert.deepEqual(await canvas.boundingBox(),bounds,'lens changes and selections do not shift the canvas');
assert(await page.evaluate(()=>window.__baseSVG===document.getElementById('mapsCanvas')&&window.__basePiece===document.querySelector('#mapsScene [data-feature-id]')),'base canvas and keyed geography nodes are retained');
assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);assert.equal(await page.evaluate(()=>window.PlotDirectorMapWorkspace.dirty),false);await canvas.focus();await page.keyboard.press('Control+s');await page.keyboard.press('Delete');assert.equal(geographyWrites,0);assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);assert.equal(reads,2,'one source projection plus one explicit annotation refresh, no per-stop requests');
await clickSource('mapStoryLayer');assert(await page.locator('#mapsStoryLayer').isHidden());await clickSource('mapStoryLayer');
if(pwa)assert(await page.locator('#mapsStoryToolbar').isHidden());
await page.screenshot({path:`${process.env.PD_MAPS_SCREENSHOT_DIR||'/tmp'}/maps2-${pwa?'pwa':'web'}.png`});
await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('create'));assert(await page.locator('#mapsLibrary').isVisible());assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);
fixture=JSON.parse(JSON.stringify(fixture));const prototype=fixture.scenes[0],pa=fixture.scenes[0].position,pb=fixture.scenes[1].position;
fixture.characters=Array.from({length:30},(_,i)=>({characterID:i+1,name:'Person '+(i+1),importance:i%10}));
fixture.scenes=Array.from({length:500},(_,i)=>({...prototype,sceneID:1000+i,narrativeOrder:i+1,sceneTitle:'Scene '+i,sceneNumber:i+1,position:i%2?pa:pb,primaryLocationID:(i%2?pa:pb).locationID,startDateTime:new Date(Date.UTC(2026,0,1,0,i)).toISOString().slice(0,19),characterIDs:[],plotLineIDs:[]}));
fixture.stops=fixture.scenes.flatMap((s,i)=>Array.from({length:10},(_,j)=>({characterID:(i+j)%30+1,sceneID:s.sceneID,sequence:i+1,position:s.position,observedAt:s.startDateTime,timePrecision:'Timestamp',evidence:'Fixture presence'})));
const previous=new Map();fixture.legs=[];for(const stop of fixture.stops){const p=previous.get(stop.characterID);if(p)fixture.legs.push({characterID:stop.characterID,fromSceneID:p.sceneID,toSceneID:stop.sceneID,from:p.position,to:stop.position,evidenceLevel:0,timingObservation:false});previous.set(stop.characterID,stop);}
await page.evaluate(()=>window.PlotDirectorMapWorkspace.setMode('story'));await page.evaluate(()=>window.PlotDirectorStoryOverlay.refresh());await page.waitForFunction(()=>window.PlotDirectorStoryOverlay.data.scenes.length===500);await choose('mapStoryLens','scene');await choose('mapStoryScene',1499);assert.match(await page.locator('#mapsDetailContent').innerText(),/Scene 499/);
const elapsed=await page.evaluate(()=>{const start=performance.now();for(let i=0;i<50;i++)window.PlotDirectorStoryOverlay.chooseScene(1000+i);return performance.now()-start;});assert(elapsed<5000,'scene navigation remains practical with 500 scenes/5,000 appearances');
const scrubMs=await page.evaluate(async()=>{const input=document.getElementById('mapStoryScrubber'),start=performance.now();for(let i=0;i<100;i++){input.value=String(i*5);input.dispatchEvent(new Event('input',{bubbles:true}));if(i%10===9)await new Promise(requestAnimationFrame);}input.dispatchEvent(new Event('change',{bubbles:true}));return performance.now()-start;});assert(scrubMs<5000);assert.equal(await page.evaluate(()=>window.PlotDirectorStoryOverlay.state.sceneID),1495,'rapid scrubber input settles at the canonical requested scene');
await choose('mapStoryLens','character');await choose('mapStoryCharacter1',1);await choose('mapStoryCharacter2',2);assert(await page.locator('.maps-story-leg').count()<=4,'repeated movements aggregate their lines while preserving individual stops/leg Details');
assert.equal(geographyWrites,0);assert.equal(await page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document)),geography);console.log(`Maps Story ${pwa?'PWA':'web'} scale: 500 scenes, 5,000 appearances; 50 scene changes in ${elapsed.toFixed(0)}ms.`);
assert.deepEqual(errors,[]);console.log(`PASS Maps Story ${pwa?'PWA':'web'}: six lenses, manuscript navigation, repeated visits/comparison, travel context, evidence, hierarchy/Floor Plan links, honest gaps, stable keyed canvas and unchanged geography/revision`);await context.close();
}
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});