Files

140 lines
9.8 KiB
JavaScript

const { chromium } = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const root = path.resolve(__dirname, '..');
const origin = process.env.GITEA_URL || 'https://git.narl.io';
const live = process.env.LIVE === '1';
const out = path.join(root, 'artifacts', live ? 'live' : 'preview');
const cases = [
['repository-desktop', '/nvrl/dotfiles', 1600, 1050],
['code-desktop', '/nvrl/dotfiles/src/branch/main/hypr/lua/palette.lua', 1440, 1000],
['login-desktop', '/user/login', 1440, 1000],
['login-mobile', '/user/login', 320, 900],
['issues-mobile', '/nvrl/dotfiles/issues', 390, 844],
['repository-mobile', '/nvrl/dotfiles', 320, 900],
['explore-desktop', '/explore/repos', 1440, 1000],
['explore-tablet', '/explore/repos', 768, 1024],
['explore-mobile', '/explore/repos', 320, 900],
['profile-desktop', '/nvrl', 1440, 1000],
['profile-mobile', '/nvrl', 390, 900],
['history-desktop', '/nvrl/dotfiles/commits/branch/main', 1440, 1000],
['short-desktop', '/nvrl/dotfiles', 1440, 500],
];
// Check rendered colors, including translucent ancestors, rather than only tokens.
async function contrast(page, selector) {
return page.locator(selector).evaluateAll(elements => {
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const rgba = color => { ctx.clearRect(0,0,1,1); ctx.fillStyle=color; ctx.fillRect(0,0,1,1); return [...ctx.getImageData(0,0,1,1).data].map((v,i)=>i===3?v/255:v); };
const blend = (front,back) => front.slice(0,3).map((v,i)=>v*front[3]+back[i]*(1-front[3]));
const luminance = rgb => rgb.map(v=>{v/=255;return v<=.04045?v/12.92:((v+.055)/1.055)**2.4;}).reduce((s,v,i)=>s+v*[.2126,.7152,.0722][i],0);
return elements.filter(el=>el.getBoundingClientRect().width).map(el=>{
const stack=[];for(let node=el;node;node=node.parentElement)stack.unshift(rgba(getComputedStyle(node).backgroundColor));
let bg=[255,255,255];for(const layer of stack)bg=blend(layer,bg);
const fg=blend(rgba(getComputedStyle(el).color),bg);const a=luminance(fg),b=luminance(bg);
return {text:el.textContent.trim().slice(0,48),ratio:(Math.max(a,b)+.05)/(Math.min(a,b)+.05)};
});
});
}
(async()=>{
await fs.mkdir(out,{recursive:true});
const browser=await chromium.launch({headless:true,...(process.env.CHROMIUM_PATH?{executablePath:process.env.CHROMIUM_PATH}:{})});
const report=[];
try {
if(live) {
const fresh=await browser.newContext();const p=await fresh.newPage();await p.goto(origin+'/');
assert.equal(await p.evaluate(()=>document.documentElement.dataset.theme),'yorha-dark','server default remains dark');
await fresh.close();
}
for(const scheme of ['dark','light']) {
const theme='yorha-'+scheme;
const themeOut=path.join(out,theme);await fs.mkdir(themeOut,{recursive:true});
const context=await browser.newContext({reducedMotion:'reduce'});
if(live)await context.addCookies([{name:'gitea_theme',value:theme,url:origin,httpOnly:true,secure:origin.startsWith('https:')}]);
const page=await context.newPage();const errors=[];
page.on('pageerror',e=>errors.push(e.message));
page.on('requestfailed',r=>{if(r.failure()?.errorText!=='net::ERR_ABORTED')errors.push(`${r.url()}: ${r.failure()?.errorText}`);});
page.on('response',r=>{if(r.status()>=400&&new URL(r.url()).pathname.startsWith('/assets/'))errors.push(`${r.status()} ${r.url()}`);});
if(!live)await page.route('**/assets/**',async route=>{
let rel=new URL(route.request().url()).pathname.replace(/^\/assets\//,'');
if(rel==='css/theme-yorha-dark.css')rel=`css/theme-${theme}.css`;
const local=path.resolve(root,rel);
if(!local.startsWith(root+path.sep)||!/^(css|fonts)\//.test(rel))return route.continue();
if(!(await fs.stat(local).catch(()=>null))?.isFile())return route.continue();
await route.fulfill({path:local,contentType:local.endsWith('.css')?'text/css':'font/woff2'});
});
await page.route('**/__yorha-components?*',async route=>route.fulfill({
body:(await fs.readFile(path.join(root,'preview/components.html'),'utf8')).replaceAll('../css/','/assets/css/'),contentType:'text/html'
}));
async function goto(route) {
const response=await page.goto(new URL(route,origin).href,{waitUntil:'networkidle'});assert.equal(response.status(),200,route);
if(!live)await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
await page.evaluate(()=>getComputedStyle(document.body).fontFamily);await page.evaluate(()=>document.fonts.ready);
}
const api=await page.request.get(origin+'/api/v1/repos/nvrl/dotfiles/commits?limit=1');
assert.equal(api.status(),200);const sha=(await api.json())[0].sha;
const themeCases=[...cases,['diff-desktop','/nvrl/dotfiles/commit/'+sha,1440,1000],['components','/__yorha-components?theme='+scheme,1440,1000]];
for(const [name,route,width,height] of themeCases) {
await page.setViewportSize({width,height});await goto(route);
const metrics=await page.evaluate(()=>({theme:document.documentElement.dataset.theme,width:innerWidth,overflow:document.documentElement.scrollWidth>innerWidth,rail:getComputedStyle(document.querySelector('#navbar')).position==='fixed',background:getComputedStyle(document.body).backgroundColor,fonts:[...document.fonts].filter(f=>f.status==='loaded').map(f=>f.family)}));
assert.equal(metrics.overflow,false,`${theme}/${name}: page overflow`);
assert.equal(metrics.theme,theme,`${theme}/${name}: theme`);
assert.equal(metrics.rail,width>=1280&&height>=600,`${theme}/${name}: rail breakpoint`);
assert.equal(metrics.background,scheme==='dark'?'rgb(15, 17, 14)':'rgb(205, 200, 176)',`${theme}/${name}: palette`);
assert.ok(metrics.fonts.includes('YoRHa Noto Sans'),`${theme}/${name}: local font`);
if(name==='code-desktop')assert.ok(metrics.fonts.includes('YoRHa JetBrains Mono'));
if(live)assert.ok((await page.locator('#footer-theme-selector .default-text').innerText()).includes('YoRHa '+(scheme==='dark'?'Dark':'Light')),theme+': native display name');
if(name==='login-desktop') {
const values=await contrast(page,'.signin-passkey,.ui.primary.button');
for(const v of values)assert.ok(v.ratio>=4.5,`${theme}/${name}: ${v.text} contrast ${v.ratio.toFixed(2)}`);
}
if(name==='issues-mobile') {
for(const v of await contrast(page,'.small-menu-items .active.item')) {
assert.ok(v.ratio>=4.5,`${theme}/issue selection: contrast ${v.ratio.toFixed(2)}`);
}
}
if(name==='components') {
const checkbox=await page.locator('#compact').evaluate(el=>({
fill:getComputedStyle(el).backgroundColor,
mark:getComputedStyle(el,'::before').backgroundColor,
}));
assert.notEqual(checkbox.fill,checkbox.mark,theme+': checkbox tick is visible');
const values=await contrast(page,'.ui.primary.button,.ui.green.button,.ui.red.button,.ui.message > .header,.ui.message > p,.ui.modal > .header,.ui.vertical.menu .active.item,.ui.green.label,.ui.red.label');
for(const v of values)assert.ok(v.ratio>=4.5,`${theme}/${name}: ${v.text} contrast ${v.ratio.toFixed(2)}`);
for(const selector of ['.ui.primary.button','.ui.red.button']) {
await page.locator(selector).first().hover();
for(const v of await contrast(page,selector))assert.ok(v.ratio>=4.5,`${theme}: hover ${v.text} contrast ${v.ratio.toFixed(2)}`);
}
metrics.contrast=values;
}
await page.screenshot({path:path.join(themeOut,name+'.png'),animations:'disabled',fullPage:name==='components'});
report.push({name,scheme,...metrics});
}
await page.setViewportSize({width:390,height:844});await goto('/nvrl/dotfiles');
const explore=page.locator('#navbar .navbar-left > a[href="/explore/repos"]');
assert.equal(await explore.isVisible(),false);await page.getByRole('button',{name:'Navigation Menu',exact:true}).click();assert.equal(await explore.isVisible(),true);
await page.getByRole('button',{name:'Navigation Menu',exact:true}).click();assert.equal(await explore.isVisible(),false);
await page.setViewportSize({width:1440,height:1000});await goto('/nvrl/dotfiles');
const branch=page.locator('.branch-selector-dropdown');await branch.click();assert.equal(await branch.locator(':scope > .menu').isVisible(),true);await page.keyboard.press('Escape');
await page.locator('#navbar-logo').focus();await page.keyboard.press('Tab');
assert.ok(await page.locator('#navbar a[href="/explore/repos"]').evaluate(el=>el.matches(':focus-visible')));
await page.screenshot({path:path.join(themeOut,'keyboard-focus.png')});
if(live) {
await page.locator('#footer-theme-selector').click();
const choice=page.locator(`#footer-theme-selector [data-value="yorha-${scheme==='dark'?'light':'dark'}"]`);
await choice.waitFor();await choice.click();
await page.waitForFunction(t=>document.documentElement.dataset.theme===t,scheme==='dark'?'yorha-light':'yorha-dark');
await page.reload({waitUntil:'networkidle'});
assert.equal(await page.evaluate(()=>document.documentElement.dataset.theme),scheme==='dark'?'yorha-light':'yorha-dark','native theme selection persists');
}
assert.deepEqual(errors,[],theme+': browser or asset errors');await context.close();
console.log(`${theme}: ${themeCases.length} layouts, contrast, menus and focus passed`);
}
await fs.writeFile(path.join(out,'report.json'),JSON.stringify({live,cases:report},null,2)+'\n');
console.log(`Screenshots: ${out}`);
} finally { await browser.close(); }
})().catch(e=>{console.error(e);process.exitCode=1;});