Files
pipelines/web/test/composer-fit-browser.mjs
T

131 lines
7.8 KiB
JavaScript

// Scratch-only ui-smoke extension: real chat view/input handlers, no backend,
// workflows, services or devices. --before serves HEAD's CSS for comparison.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { resolve, extname } from 'node:path';
import { launchChrome } from './browser.mjs';
const root = resolve(import.meta.dirname, '..');
const out = resolve(process.argv[2] || '.ui-composer-fit');
const before = process.argv.includes('--before');
await mkdir(out, { recursive: true });
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${['design/tokens/tokens','base','shell','lists','run-detail','chat','dialogs'].map(n => `<link rel="stylesheet" href="/${n}.css">`).join('')}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
const id='scratch';
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Composer fit review',backend:'codex'}],
chatOverrides:{},chatDrafts:{},chatThreads:new Map([[id,{loaded:true,draft:'',messages:[{id:'m',role:'user',parts:[{type:'text',text:'Please review the composer alignment.'}]}],attachments:[],notices:[],running:false}]])};
const rt={state,repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.setRunning=(running)=>{state.chatThreads.get(id).running=running;document.querySelector('#chatInput').dispatchEvent(new Event('input',{bubbles:true}));};
window.setAttachment=()=>{state.chatThreads.get(id).attachments=[{id:'a',name:'draft-layout-reference-with-a-long-file-name.txt',size:1024,mime:'text/plain'}];paint();};
paint();window.fixtureState=state;
</script>`;
const server = createServer(async (req, res) => {
try {
if (req.url === '/') { res.setHeader('content-type','text/html'); res.end(html); return; }
const path = resolve(root, `.${new URL(req.url,'http://scratch').pathname}`);
if (!path.startsWith(root + '/')) throw new Error('outside root');
res.setHeader('content-type',extname(path)==='.css'?'text/css':'text/javascript');
res.end(before && path===resolve(root,'chat.css') ? execFileSync('git',['show','HEAD:web/chat.css'],{cwd:root}) : await readFile(path));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
let browser;
const measurements=[];
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatInput');
const measure=()=>page.evaluate(`(() => {
const rect=s=>{const e=document.querySelector(s);if(!e)return null;const r=e.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right};};
const input=document.querySelector('#chatInput'),s=getComputedStyle(input);
return {input:rect('#chatInput'),attach:rect('#chatAttach'),send:rect('#chatSend'),stop:rect('#chatStop'),
header:rect('.chat-bar'),composer:rect('#chatComposer'),scroll:input.scrollHeight,client:input.clientHeight,
line:parseFloat(s.lineHeight),padding:parseFloat(s.paddingTop)+parseFloat(s.paddingBottom),
overflow:s.overflowY,documentWidth:document.documentElement.scrollWidth,viewport:innerWidth};
})()`);
const capture=async(name)=>{
await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');
const m=await measure(); measurements.push({name,...m});
await page.screenshot(resolve(out,name+'.png'));
if (!before) {
assert.ok(m.documentWidth<=m.viewport,`${name}: document overflow`);
for(const b of [m.attach,m.send,m.stop].filter(Boolean)) {
assert.ok(b.width>=44 && b.height>=44,`${name}: touch target`);
const controlCenter=b.y+b.height/2;
const inputCenter=m.input.y+m.input.height/2;
assert.ok(Math.abs(controlCenter-inputCenter)<=1,`${name}: vertical center alignment`);
}
assert.equal(m.send.width,m.attach.width);
assert.ok(m.input.right+8<=m.send.x,`${name}: input/action overlap`);
assert.ok(m.composer.bottom<= (name.includes('keyboard') && m.viewport<600?500:900),`${name}: visible composer`);
}
return m;
};
for(const width of [390,420,1100]) {
await page.resize(width,900);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatInput');
const empty=await capture(`empty-${width}`);
if(!before) assert.equal(empty.input.height,empty.send.height,'empty placeholder must fit one aligned line');
await page.fill('#chatInput','Review this draft');
await capture(`single-${width}`);
await page.fill('#chatInput','First draft line\nSecond draft line\nThird draft line');
const idle=await capture(`multiline-${width}`);
await page.evaluate('setRunning(true)');
const running=await capture(`running-${width}`);
if(!before) {
assert.deepEqual(running.input,idle.input,'running must not rewrap or move draft');
assert.equal(running.stop.width,running.send.width);
assert.deepEqual(running.header,idle.header,'header unchanged');
assert.ok(running.scroll<=running.client,'three full lines fit');
}
await page.evaluate('setRunning(false)');
const settled=await measure();
if(!before) {
assert.deepEqual(settled.input,idle.input,'settling must not move draft');
assert.equal(settled.stop,null);
assert.equal(await page.evaluate('document.activeElement.id'),'chatInput');
}
await page.evaluate('setRunning(true)');
await page.fill('#chatInput','Line one\nLine two\nLine three\nLine four\nLine five\nLine six');
const six=await capture(`six-lines-${width}`);
if(!before) assert.equal(six.input.height,6*six.line+six.padding+2,'six complete lines fit');
await page.fill('#chatInput',Array(10).fill('Long draft line').join('\n'));
const long=await capture(`long-draft-${width}`);
if(!before) { assert.equal(long.overflow,'auto');assert.equal(long.input.height,six.input.height); }
await page.fill('#chatInput','First draft line\nSecond draft line');
{
// Deterministic existing keyboard CSS geometry, not a real OS keyboard.
await page.evaluate(`document.documentElement.classList.add('keyboard-open');document.documentElement.style.setProperty('--keyboard-visible-height','500px');document.documentElement.style.setProperty('--keyboard-viewport-top','0px')`);
await capture(`keyboard-${width}`);
await page.evaluate(`document.documentElement.classList.remove('keyboard-open')`);
}
await page.evaluate('setAttachment()');
await capture(`attachment-${width}`);
}
if(!before) {
await page.emulateTouch(true);
for(const width of [390,420]) {
await page.resize(width,900);await page.goto(`http://127.0.0.1:${server.address().port}/`);await page.waitForSelector('#chatInput');
assert.equal(await page.evaluate("matchMedia('(any-pointer: coarse)').matches"),true);
const touch=await capture(`touch-empty-${width}`);
assert.equal(touch.send.width,48);assert.equal(touch.input.height,48);
await page.evaluate('setRunning(true)');
const running=await capture(`touch-running-${width}`);
assert.equal(running.stop.width,48);assert.deepEqual(running.input,touch.input);
}
}
await writeFile(resolve(out,'geometry.json'),JSON.stringify(measurements,null,2));
console.log(`${measurements.length} scratch captures and geometry: ${out}`);
} finally {
if(browser) await browser.close();
await new Promise(r=>server.close(r));
}