PlotDirector/PlotLine.Tests/Browser/context-spatial-development.cjs

12 lines
11 KiB
JavaScript

// Development only. All writes target this dedicated synthetic author's owned fixture project.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');const file=process.argv[2];if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated identity required');const identity=JSON.parse(fs.readFileSync(file));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));const f=identity.SpatialFixture;assert(f?.scenes?.length===3);const base='https://dev.plotdirector.com',out='/tmp/pd-spatial-evidence';
(async()=>{const browser=await chromium.launch();let step='login';try{const context=await browser.newContext({viewport:{width:1600,height:1050}}),page=await context.newPage(),errors=[],mutations=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/SpatialContext/Mutate'))mutations.push(r.postDataJSON());});await page.goto(base+'/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);await Promise.all([page.waitForURL('**/Projects'),page.locator('form button[type=submit]').click()]);const scope=`projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}&pinned=true`;await page.goto(base+'/Writing/Context?'+scope);await page.selectOption('[data-context-pane="0"] [data-context-tab]','locations');const pane=i=>page.locator(`[data-context-pane="${i}"]`),shot=name=>page.screenshot({path:`${out}/development-${name}.png`});await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();const token=await pane(0).locator('[name=__RequestVerificationToken]').inputValue();async function state(){const r=await page.request.get(base+`/SpatialContext/State?bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);assert.equal(r.status(),200);return r.json();}async function mapState(){const r=await page.request.get(base+`/Maps/State?projectId=${identity.ProjectID}&id=${f.mapId}`);assert.equal(r.status(),200);return r.json();}async function waitState(test){for(let i=0;i<30;i++){const value=await state();if(test(value))return value;await page.waitForTimeout(100);}throw Error('Saved state did not reach expected value.');}async function undo(i){await pane(i).getByRole('button',{name:'Undo spatial change',exact:true}).click();}async function chooseLocation(location){const dialog=page.locator('dialog[open]').last();await dialog.locator(`[data-picker-id="${location}"] .pd-location-picker-name`).click();await dialog.getByRole('button',{name:'Choose',exact:true}).click();}
step='authoritative sequence';let data=await state();assert.deepEqual(data.scenes.map(s=>s.sceneID),f.scenes);assert.equal(data.scenes[0].chapterID,f.chapters[0]);assert.equal(data.scenes[1].chapterID,f.chapters[1]);assert.equal(data.scope.primaryLocationID,f.locations[1]);const originalMap=await mapState(),originalFeature=JSON.stringify(originalMap.features[0]);await shot('locations');
step='explicit current-scene assignment while inspecting adjacent';await pane(0).locator('[data-scene-position="-1"] button').first().click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor();await pane(0).getByRole('button',{name:'Change current scene location',exact:true}).click();await chooseLocation(f.locations[3]);await waitState(x=>x.scope.primaryLocationID===f.locations[3]);assert.equal(mutations.at(-1).sceneID,f.scenes[1]);assert.equal(mutations.at(-1).locationID,f.locations[3]);await undo(0);await waitState(x=>x.scope.primaryLocationID===f.locations[1]);await pane(0).getByRole('button',{name:'Return to scene location',exact:true}).click();await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();
step='description and existing protected Undo';await pane(0).getByRole('button',{name:'Edit description',exact:true}).click();await pane(0).locator('textarea').fill('Spatial acceptance prose, saved exactly without AI.');await pane(0).getByRole('button',{name:'Save',exact:true}).click();await pane(0).getByText('Spatial acceptance prose, saved exactly without AI.',{exact:true}).waitFor();await undo(0);await waitState(x=>!x.locations.find(l=>l.locationID===f.locations[1]).description);
step='atomic create-and-assign and stale-create rollback';let beforeCreate=await state();let response=await page.request.post(base+'/SpatialContext/Create',{headers:{RequestVerificationToken:token},data:{bookID:identity.BookID,sceneID:f.scenes[1],name:'Stale atomic fixture must not remain',parentID:f.locations[0],expected:'2000-01-01T00:00:00'}});assert.equal(response.status(),409);const directoryResponse=await page.request.get(base+`/LocationWorkspace/Picker?projectId=${identity.ProjectID}`);assert(!(await directoryResponse.json()).locations.some(l=>l.name==='Stale atomic fixture must not remain'));response=await page.request.post(base+'/SpatialContext/Create',{headers:{RequestVerificationToken:token},data:{bookID:identity.BookID,sceneID:f.scenes[1],name:'Atomic spatial acceptance alcove',parentID:f.locations[0],expected:beforeCreate.scope.version}});assert.equal(response.status(),200);const created=await response.json();await waitState(x=>x.scope.primaryLocationID===created.id);response=await page.request.post(base+'/SpatialContext/Undo',{headers:{RequestVerificationToken:token},data:{token:created.assignment.undoToken}});assert.equal(response.status(),200);await waitState(x=>x.scope.primaryLocationID===f.locations[1]);await pane(0).getByRole('button',{name:'Return to scene location',exact:true}).click();await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();
step='map placement and Undo';const liveMap=await context.newPage();await liveMap.goto(base+`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`);await liveMap.waitForFunction(()=>!!window.PlotDirectorPresenceConnection&&!!window.PlotDirectorMapWorkspace);await page.bringToFront();await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','maps');await pane(1).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===1);const mapFrame=page.frames().find(frame=>frame.url().includes('/SpatialContext/Map'));await shot('locations-maps');await pane(1).getByRole('button',{name:'Place location',exact:true}).click();await pane(1).locator('[data-spatial-operation]').filter({hasText:'Place existing location: Bedroom'}).waitFor();await shot('placement');await mapFrame.locator('#mapsCanvas').click({position:{x:150,y:130}});await waitState(x=>x.maps.some(m=>m.locationID===f.locations[1]));await liveMap.waitForFunction(()=>PlotDirectorMapWorkspace.document.features.length===2);let saved=await mapState();assert.equal(saved.features.filter(x=>x.locationID===f.locations[1]).length,1);assert.equal(JSON.stringify(saved.features.find(x=>x.featureID===originalMap.features[0].featureID)),originalFeature);const marker=saved.features.find(x=>x.locationID===f.locations[1]);const main=await context.newPage();await main.goto(base+`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}&featureId=${marker.featureID}`);await main.waitForFunction(id=>PlotDirectorMapWorkspace?.selected.includes(id),marker.featureID);await main.close();await undo(1);await waitState(x=>!x.maps.some(m=>m.locationID===f.locations[1]));assert.equal((await mapState()).features.length,1);await liveMap.waitForFunction(()=>PlotDirectorMapWorkspace.document.features.length===1);await liveMap.close();
step='room association and Undo';const livePlan=await context.newPage();await livePlan.goto(base+`/FloorPlans/Edit/${f.planId}`);await livePlan.waitForSelector('[data-floor-plan-initialized=true]');await page.bringToFront();await page.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await pane(1).locator('[data-spatial-floor-canvas]').waitFor();const room=pane(1).locator(`[data-block][data-location-id="${f.locations[2]}"]`);const block=await room.getAttribute('data-block'),geometry=await room.getAttribute('style');await room.click();await pane(1).getByRole('button',{name:'Associate existing location',exact:true}).click();const picker=page.locator('dialog[open]').last();await picker.locator('input[type=search]').fill('Unmapped valley');await chooseLocation(f.locations[4]);await pane(1).getByRole('button',{name:'Confirm',exact:true}).waitFor();await shot('room-association');await pane(1).getByRole('button',{name:'Confirm',exact:true}).click();await pane(1).locator(`[data-block="${block}"][data-location-id="${f.locations[4]}"]`).waitFor();assert.equal(await pane(1).locator(`[data-block="${block}"]`).getAttribute('style'),geometry);await livePlan.locator(`[data-block="${block}"][data-location-id="${f.locations[4]}"]`).waitFor();data=await state();assert.equal(data.locations.find(l=>l.locationID===f.locations[4])?.parentLocationID??null,null);await undo(1);await pane(1).locator(`[data-block="${block}"][data-location-id="${f.locations[2]}"]`).waitFor();await livePlan.locator(`[data-block="${block}"][data-location-id="${f.locations[2]}"]`).waitFor();await livePlan.close();await shot('locations-floorplans');
step='main workspaces remain available';const checks=[];const verification=await context.newPage();for(const route of [`/Locations?projectId=${identity.ProjectID}`,`/Characters?projectId=${identity.ProjectID}`,`/Names?projectId=${identity.ProjectID}`,`/Relationships?projectId=${identity.ProjectID}`,`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`,`/FloorPlans/Edit/${f.planId}`,`/Assets?projectId=${identity.ProjectID}`]){const response=await verification.goto(base+route);assert.equal(response.status(),200,route);checks.push(route.split('?')[0]);}await verification.close();
step='single SignalR in following window';const follow=await context.newPage();let connections=0;follow.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))connections++;});await follow.goto(base+`/Writing/Context?projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);await follow.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await follow.selectOption('[data-context-pane="0"] [data-context-tab]','maps');await follow.selectOption('[data-context-layout]','columns');await follow.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await follow.waitForTimeout(500);assert.equal(connections,1);await follow.close();assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/development-results.json`,JSON.stringify({passed:true,source:'authenticated Development',fixturesOnly:true,sceneSequence:f.scenes,checks,signalRConnections:connections,errors},null,2));console.log('PASS authenticated Development spatial sequence, targeted description/scene assignment, real protected Undo, map placement/reveal, room association, geometry preservation, main directories, one SignalR connection.');}catch(e){console.error('FAIL',step,e);process.exitCode=1;}finally{await browser.close();}})();