// Focused interaction/race checks; live persistence is tested separately in Development.
const {chromium}=require('playwright');
const fs=require('node:fs');
const path=require('node:path');
const assert=require('node:assert/strict');
(async()=>{
const browser=await chromium.launch({headless:true});
try {
const page=await browser.newPage({viewport:{width:1200,height:760}}); let reject=false; const writes=[];
await page.route('http://metrics.test/**',route=>{
if(route.request().method()==='POST'){
const body=route.request().postDataJSON(); writes.push(body);
return route.fulfill({status:reject?400:200,json:reject?{message:'Save rejected'}:{success:true,value:body.value}});
}
return route.fulfill({contentType:'text/html',body:'
'});
});
await page.goto('http://metrics.test');
const errors=[];
page.on('pageerror', error=>errors.push(error.message));
await page.addScriptTag({path:path.join(path.dirname(require.resolve('chart.js')), 'chart.umd.js')});
await page.addStyleTag({content:'*{box-sizing:border-box}'+['context-workspace','context-metrics'].map(file=>
fs.readFileSync(`PlotLine/wwwroot/css/${file}.css`,'utf8')).join('\n')});
for(const file of ['metric-curves','context-metrics'])await page.addScriptTag({content:fs.readFileSync(`PlotLine/wwwroot/js/${file}.js`,'utf8')});
await page.evaluate(()=>{
const root=document.querySelector('main');
root.dataset.contextWorkspace='';
root.className='context-workspace';
root.style.height='720px';
const metric='';
const pane=hidden=>``;
root.innerHTML=`${pane(false)}
${pane(true)}
`;
window.metrics=[...root.querySelectorAll('[data-context-metrics]')];
window.mountMetric=i=>PlotDirectorContextLifecycles.metrics.mount(metrics[i],{paneId:i,windowId:'fixture'});
window.chart=()=>Chart.getChart(metrics[0].querySelector('canvas'));
mountMetric(0);
});
const divider=page.locator('.context-metrics-divider').first();
assert.equal(await divider.getAttribute('aria-valuenow'),'75');
await page.waitForFunction(()=>chart().height>400);
const firstHeight=await page.locator('canvas').first().evaluate(el=>el.clientHeight);
await page.evaluate(()=>{document.querySelector('[data-layout]').dataset.layout='columns';metrics[1].closest('section.context-pane').hidden=false;mountMetric(1);});
assert.equal(await divider.isVisible(),false);
await page.evaluate(()=>document.querySelector('[data-layout]').dataset.layout='rows');
assert.equal(await divider.isVisible(),true);
await page.waitForFunction(height=>chart().height{PlotDirectorContextLifecycles.metrics.dispose(metrics[0]);mountMetric(0);});
assert.equal(await divider.getAttribute('aria-valuenow'),split);
await divider.dblclick();
assert.equal(await divider.getAttribute('aria-valuenow'),'75');
assert.deepEqual(await page.evaluate(()=>chart().data.datasets[0].data.map(p=>p.y)),[0,null]);
assert.deepEqual(await page.evaluate(()=>[chart().scales.y.min,chart().scales.y.max]),[1,10]);
await page.waitForFunction(()=>chart().width===chart().canvas.parentElement.clientWidth);
const hit=await page.evaluate(()=>{
const chartInstance=chart(), box=chartInstance.canvas.getBoundingClientRect();
const {left,top,width,height}=chartInstance.legend.legendHitBoxes[0];
return {x:box.x+left+width/2,y:box.y+top+height/2};
});
await page.mouse.click(hit.x,hit.y);
await page.waitForFunction(()=>!chart().isDatasetVisible(0));
await page.evaluate(()=>{PlotDirectorContextLifecycles.metrics.dispose(metrics[0]);mountMetric(0);});
assert.equal(await page.evaluate(()=>chart().isDatasetVisible(0)),false);
await page.mouse.click(hit.x,hit.y);
await page.waitForFunction(()=>chart().isDatasetVisible(0));
const input=page.locator('[type=range]').first();
await input.focus(); await page.keyboard.press('ArrowRight');
await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved');
assert.equal(writes[0].value,1); assert.equal(writes[0].sceneID,2);
reject=true;
await input.focus();await page.keyboard.press('ArrowRight');
await page.waitForFunction(()=>document.querySelector('[data-metrics-error]').textContent==='Save rejected');
assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(metrics[0])),false);
await page.locator('[data-metrics-cancel]').first().click();
assert.equal(await input.inputValue(),'1');
assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(metrics[0])),true);
// A pointer commit on the minimum must record zero even if the range value did not change.
reject=false;
await input.evaluate(el=>{el.value='0';el.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true}));document.dispatchEvent(new PointerEvent('pointerup'));});
await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved');
assert.equal(writes.at(-1).value,0);
await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.dispose(metrics[0]));
assert.equal(await page.evaluate(()=>chart()),undefined);
assert.deepEqual(errors,[]);
console.log('PASS Context Metrics layouts, divider and legend persistence, fixed axis, zero/unset, keyboard and pointer commits, failed save recovery and disposal');
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});