fix(context): keep explicit location creation and placement cancellation accessible

This commit is contained in:
Nick Beckley 2026-11-27 17:06:01 +00:00
parent 587f067da9
commit 802b98921a
2 changed files with 3 additions and 2 deletions

View File

@ -4,6 +4,7 @@ const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('nod
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();

View File

@ -37,8 +37,8 @@
async function edit(attribute,location){const fixed={...location},name=fixed.locationName;await form(`${attribute==='description'?'Edit description':'Rename'}: ${name}`,panel=>{const input=el(attribute==='description'?'textarea':'input');input.value=attribute==='description'?(fixed.description||''):name;input.setAttribute('aria-label',attribute);if(attribute==='description')input.rows=9;panel.append(input);return input;},input=>post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value:input.value,version:fixed.updatedDate}]}));}
async function discrete(attribute,location){const fixed={...location};let value;if(attribute==='type'){guard(true);try{value=await window.PlotDirectorLocationTypes.choose({taxonomy:data.types,selected:String(fixed.locationTypeID??'')});}finally{guard(false);}if(value===null)return;}else{await form(`Classification: ${fixed.locationName}`,panel=>{const input=el('select');for(const v of ['Unclassified','Real','Fictional','Fictionalised'])input.add(new Option(v,v==='Unclassified'?'':v));input.value=fixed.classification||'';panel.append(input);return input;},input=>post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value:input.value,version:fixed.updatedDate}]}));return;}await finish(await post('/LocationWorkspace/Assign',{projectId:position.projectId,attribute,changes:[{id:id(fixed),value,version:fixed.updatedDate}]}),'/LocationWorkspace/Undo');}
async function createLocation(assignScene=false,parent=selection,block=null){const target={...position},scope={...data.scope},plan=resource;await form(assignScene?`Create location for ${scope.label}`:block?'Create and associate location':'Create child location',panel=>{const name=el('input');name.placeholder='Location name';name.setAttribute('aria-label','Location name');let parentId=parent;const parentLabel=el('small',parent?`Parent: ${path(data,parent)}`:'Parent: Root level');panel.append(name,parentLabel,btn('Choose parent',async()=>{const chosen=await picker('Review containing location',parentId,true);if(chosen!==undefined){parentId=chosen;parentLabel.textContent=chosen?`Parent location ${chosen}`:'Parent: Root level';}}));return {name,parent:()=>parentId};},controls=>post('/SpatialContext/Create',{bookID:target.bookId,sceneID:scope.sceneID,name:controls.name.value,parentID:controls.parent(),expected:assignScene?scope.version:block?.version,planID:block?plan:null,blockID:block?String(block.id):null,replace:!!block}));}
async function showTool(tool){bus.select(selection,context.paneId,true);const visible=[...root.querySelectorAll('[data-context-pane]:not([hidden]) [data-context-tab]')].some(s=>s.value===tool);if(visible){root.contextController.openTool(tool,context.paneId,'other');return;}const dialog=el('dialog',null,'pd-location-picker-dialog');dialog.append(el('h2',`Show ${tool==='maps'?'map':'floor plan'}`),el('p','Choose where to open this spatial perspective.'));for(const [label,destination]of [['This pane','current'],['Other pane / create split','other']])dialog.append(btn(label,()=>{dialog.close();if(!root.contextController.openTool(tool,context.paneId,destination))fail(Error('Finish or cancel editing in the destination pane first.'));}));dialog.append(btn('Cancel',()=>dialog.close()));dialog.onclose=()=>dialog.remove();document.body.append(dialog);dialog.showModal();}
function details(){const host=q('[data-spatial-details]');host.replaceChildren();const current=data.scope,location=data.locations.find(l=>id(l)===selection);const actions=el('div',null,'spatial-toolbar');if(current.canEdit)actions.append(btn(`Change current scene location`,chooseAssignment));host.append(actions);if(!location){host.append(el('p','This scene has no assigned location. Inspect adjacent scenes or explicitly choose a location.'));if(current.canEdit){host.append(btn('Create new location for current scene',()=>createLocation(true,null)));for(const adjacent of data.scenes.filter(s=>s.position!==0&&s.locationID))host.append(btn(`Use ${adjacent.position<0?'previous':'next'} scene location`,()=>assign(adjacent.locationID)));}return;}const header=el('h2',location.locationName);header.prepend(icon(data,location));draggable(header,id(location));host.append(header,el('p',`${location.locationTypeName||'Unclassified'} · ${location.classification||'Unclassified'}`));const trail=el('nav',null,'spatial-path');trail.setAttribute('aria-label','Containing locations');for(const a of ancestors(data,id(location)).reverse())trail.append(btn(a.locationName,()=>select(id(a))));host.append(trail);const description=el('div',location.description||'No description recorded.','spatial-description');host.append(description);if(current.canEdit){const tools=el('div',null,'spatial-toolbar');tools.append(btn('Edit description',()=>edit('description',location)),btn('Rename',()=>edit('name',location)),btn('Type',()=>discrete('type',location)),btn('Classification',()=>discrete('classification',location)),btn('Create child',()=>createLocation(false,id(location))));host.append(tools);}const links=el('div',null,'spatial-toolbar');for(const [label,url]of [['Location Details',`/Locations/Details/${id(location)}`],['Edit Location',`/Locations/Edit/${id(location)}`]]){const a=el('a',label);a.href=url;links.append(a);}host.append(links);const children=data.locations.filter(l=>l.parentLocationID===id(location));if(children.length){const section=el('details');section.open=preferences.children!==false;section.append(el('summary',`Contained locations (${location.childCount})`));section.ontoggle=()=>{preferences.children=section.open;save();};for(const child of children)section.append(btn(child.locationName,()=>select(id(child))));if(location.childCount>children.length)section.append(el('small',`Showing ${children.length} immediate locations. Open Locations for the complete directory.`));host.append(section);}if(data.relationships.length){const section=el('details');section.append(el('summary','Recorded relationships'));for(const r of data.relationships)section.append(el('p',`${r.fromName} · ${r.typeName} · ${r.toName}${r.notes?' — '+r.notes:''}`));host.append(section);}const spatial=el('div',null,'spatial-toolbar');for(const tool of ['maps','floorplans']){const found=resolution(data,id(location),tool);spatial.append(btn(`Show ${tool==='maps'?'map':'floor plan'}${found.some(f=>f.depth)?' (containing location)':''}`,()=>showTool(tool)));if(tool==='maps'&&current.canEdit&&!found.some(f=>f.depth===0))spatial.append(btn('Place on map',()=>{bus.pendingPlacement=selection;return showTool('maps');}));}host.append(spatial);}
async function showTool(tool){bus.select(selection,context.paneId,true);const visible=[...root.querySelectorAll('[data-context-pane]:not([hidden]) [data-context-tab]')].some(s=>s.value===tool);if(visible){root.contextController.openTool(tool,context.paneId,'other');return;}let opened=false;const dialog=el('dialog',null,'pd-location-picker-dialog');dialog.append(el('h2',`Show ${tool==='maps'?'map':'floor plan'}`),el('p','Choose where to open this spatial perspective.'));for(const [label,destination]of [['This pane','current'],['Other pane / create split','other']])dialog.append(btn(label,()=>{dialog.close();if(root.contextController.openTool(tool,context.paneId,destination))opened=true;else fail(Error('Finish or cancel editing in the destination pane first.'));}));dialog.append(btn('Cancel',()=>dialog.close()));dialog.onclose=()=>{if(!opened)bus.pendingPlacement=null;dialog.remove();};document.body.append(dialog);dialog.showModal();}
function details(){const host=q('[data-spatial-details]');host.replaceChildren();const current=data.scope,location=data.locations.find(l=>id(l)===selection);const actions=el('div',null,'spatial-toolbar');if(current.canEdit)actions.append(btn(`Change current scene location`,chooseAssignment),btn('New location for current scene',()=>createLocation(true,null)));host.append(actions);if(!location){host.append(el('p','This scene has no assigned location. Inspect adjacent scenes or explicitly choose a location.'));if(current.canEdit){host.append(btn('Create new location for current scene',()=>createLocation(true,null)));for(const adjacent of data.scenes.filter(s=>s.position!==0&&s.locationID))host.append(btn(`Use ${adjacent.position<0?'previous':'next'} scene location`,()=>assign(adjacent.locationID)));}return;}const header=el('h2',location.locationName);header.prepend(icon(data,location));draggable(header,id(location));host.append(header,el('p',`${location.locationTypeName||'Unclassified'} · ${location.classification||'Unclassified'}`));const trail=el('nav',null,'spatial-path');trail.setAttribute('aria-label','Containing locations');for(const a of ancestors(data,id(location)).reverse())trail.append(btn(a.locationName,()=>select(id(a))));host.append(trail);const description=el('div',location.description||'No description recorded.','spatial-description');host.append(description);if(current.canEdit){const tools=el('div',null,'spatial-toolbar');tools.append(btn('Edit description',()=>edit('description',location)),btn('Rename',()=>edit('name',location)),btn('Type',()=>discrete('type',location)),btn('Classification',()=>discrete('classification',location)),btn('Create child',()=>createLocation(false,id(location))));host.append(tools);}const links=el('div',null,'spatial-toolbar');for(const [label,url]of [['Location Details',`/Locations/Details/${id(location)}`],['Edit Location',`/Locations/Edit/${id(location)}`]]){const a=el('a',label);a.href=url;links.append(a);}host.append(links);const children=data.locations.filter(l=>l.parentLocationID===id(location));if(children.length){const section=el('details');section.open=preferences.children!==false;section.append(el('summary',`Contained locations (${location.childCount})`));section.ontoggle=()=>{preferences.children=section.open;save();};for(const child of children)section.append(btn(child.locationName,()=>select(id(child))));if(location.childCount>children.length)section.append(el('small',`Showing ${children.length} immediate locations. Open Locations for the complete directory.`));host.append(section);}if(data.relationships.length){const section=el('details');section.append(el('summary','Recorded relationships'));for(const r of data.relationships)section.append(el('p',`${r.fromName} · ${r.typeName} · ${r.toName}${r.notes?' — '+r.notes:''}`));host.append(section);}const spatial=el('div',null,'spatial-toolbar');for(const tool of ['maps','floorplans']){const found=resolution(data,id(location),tool);spatial.append(btn(`Show ${tool==='maps'?'map':'floor plan'}${found.some(f=>f.depth)?' (containing location)':''}`,()=>showTool(tool)));if(tool==='maps'&&current.canEdit&&!found.some(f=>f.depth===0))spatial.append(btn('Place on map',()=>{bus.pendingPlacement=selection;return showTool('maps');}));}host.append(spatial);}
function catalog(){return kind==='maps'?data.mapCatalog:data.planCatalog;}
function relevant(){const found=resolution(data,selection,kind);if(found.length)return found.sort((a,b)=>data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===b.resourceID)).length-data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===a.resourceID)).length||a.name.localeCompare(b.name));return data.scenes.flatMap(s=>resolution(data,s.locationID,kind));}
function draw(){if(!data||disposed)return;error.textContent='';scenes();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=Number(preferences.resource);const next=resource&&available.has(resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};const selectedLinks=resolution(data,selection,kind).filter(x=>x.resourceID===next);q('[data-spatial-resolution]').textContent=selectedLinks.length?(selectedLinks[0].depth?`Represented through containing location: ${path(data,selectedLinks[0].represented)}. This is not an exact position for the inspected location.`:'Directly associated with the inspected location.'):'No authoritative representation of the inspected location on this resource.';if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();const advanced=q('[data-spatial-advanced]');advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}`:`/FloorPlans/Edit/${resource}`;advanced.hidden=!resource;}