← Files JUJIES ArbeitsblätterARCHIVED FILE

tests/check-browser-controls.mjs

10.7 KB · Nov 11, 2026 · 13:26 UTC

↓ Download file

import {mkdtemp,mkdir,readdir,readFile,writeFile,rm,copyFile} from 'node:fs/promises';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {createRequire} from 'node:module';
import {fileURLToPath,pathToFileURL} from 'node:url';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createBrowserStart} from '../skills/arbeitsblatt-html/scripts/create-browser-start.mjs';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const skill=path.join(root,'skills/arbeitsblatt-html');
const output=process.env.AB_TEST_OUTPUT?path.resolve(process.env.AB_TEST_OUTPUT):null;
await mkdir('work',{recursive:true});
const scratch=await mkdtemp(path.resolve('work/browser-controls-'));
if(output)await mkdir(output,{recursive:true});
const require=createRequire(import.meta.url);
const {chromium}=require(process.env.AB_PLAYWRIGHT_MODULE||'playwright');
const browser=await chromium.launch();
const sha=b=>createHash('sha256').update(b).digest('hex');
async function pixels(pdf,dir){await mkdir(dir);execFileSync('pdftoppm',['-png','-r','72',pdf,path.join(dir,'page')],{stdio:'pipe'});return Promise.all((await readdir(dir)).sort().map(async f=>sha(await readFile(path.join(dir,f)))));}
const results=[];
try {
 for(const id of (await readdir(path.join(skill,'assets/vorlagen'),{withFileTypes:true})).filter(e=>e.isDirectory()).map(e=>e.name).sort()) {
  const source=path.join(skill,'assets/vorlagen',id);
  const manifest=JSON.parse(await readFile(path.join(source,'manifest.json'),'utf8'));
  const start=path.join(skill,'assets/browserstarts',`${id}-browser.html`);
  const authored=await readFile(path.join(source,manifest.entry),'utf8');
  assert((await readFile(start,'utf8')).includes(`sha256 ${sha(authored)}`),'Packaged example source is stale');
  const page=await browser.newPage({viewport:{width:1100,height:1250}});
  const failures=[];page.on('requestfailed',r=>failures.push(r.url()));
  await page.goto(pathToFileURL(start).href);await page.evaluate(()=>document.fonts.ready);
  assert.deepEqual(failures,[],'Missing packaged resource');
  const height=await page.locator('.ab-browser-controls').evaluate(e=>e.getBoundingClientRect().height);
  assert(height<=44,'Desktop toolbar takes excessive worksheet space');
  assert.equal(await page.locator('#ab-print-help').getAttribute('open'),null,'Help expanded by default');
  await page.evaluate(()=>{window.__calls=0;window.print=()=>window.__calls++;});
  await page.keyboard.press('Tab');assert.equal(await page.evaluate(()=>document.activeElement.id),'ab-browser-print');
  await page.keyboard.press('Enter');assert.equal(await page.evaluate(()=>window.__calls),1);
  assert.equal(await page.locator('.ab-browser-controls').evaluate(e=>e.getBoundingClientRect().height),height,'Print action grows toolbar');
  await page.locator('#ab-print-help summary').click();assert.equal(await page.locator('#ab-print-help').evaluate(e=>e.open),true);
  assert.equal(await page.locator('.ab-browser-controls').evaluate(e=>e.getBoundingClientRect().height),height,'Help pushes worksheet down');
  await page.locator('#ab-print-help summary').click();
  const paper=page.locator('[data-tafelraum-page]').first();
  const normalPaper=await paper.evaluate(e=>({width:e.getBoundingClientRect().width,shadow:getComputedStyle(e).boxShadow,background:getComputedStyle(e).backgroundColor,margin:getComputedStyle(e).marginTop}));
  assert.notEqual(normalPaper.shadow,'none','Missing paper shadow');
  assert.equal(normalPaper.background,'rgb(255, 255, 255)','Paper must remain white');
  assert(parseFloat(normalPaper.margin)>=16,'Pages need a visible gap');
  assert.equal(await page.locator('body').evaluate(e=>getComputedStyle(e).backgroundColor),'rgb(237, 240, 242)','Missing quiet browser background');
  const fieldState=()=>page.locator('[data-tafelraum-page] input,[data-tafelraum-page] textarea,[data-tafelraum-page] select').evaluateAll(fields=>fields.map(f=>({id:f.id,value:f.value,checked:f.checked})));
  const textField=page.locator('[data-tafelraum-page] textarea').first();
  if(await textField.count())await textField.fill('Gemeinsam erarbeitet');
  const state=await fieldState();
  await page.evaluate(()=>{window.__originalFields=Array.from(document.querySelectorAll('[data-tafelraum-page] input,[data-tafelraum-page] textarea,[data-tafelraum-page] select'));});
  await page.locator('#ab-review-toggle').click();
  assert.equal(await page.locator('#ab-review-toggle').getAttribute('aria-pressed'),'true');
  assert(await paper.evaluate(e=>e.getBoundingClientRect().width)>normalPaper.width*1.2,'Review view must actually enlarge the worksheet');
  const tasks=await page.locator('#ab-review-task option').count();assert(tasks>0,'Missing navigation');
  if(tasks>1){
    await page.locator('#ab-review-task').selectOption('1');
    await page.evaluate(()=>window.scrollTo(0,document.documentElement.scrollHeight));
    await page.locator('#ab-review-task').selectOption('0');
    assert(await page.locator('[data-ab-review-target]').first().evaluate(e=>{const r=e.getBoundingClientRect();return r.bottom>0&&r.top<innerHeight;}),'Task navigation did not bring the target into view');
  }
  assert.deepEqual(await fieldState(),state,'View navigation lost answers');
  assert(await page.evaluate(()=>window.__originalFields.every((f,i)=>f===document.querySelectorAll('[data-tafelraum-page] input,[data-tafelraum-page] textarea,[data-tafelraum-page] select')[i])),'Review view cloned worksheet controls');
  assert.equal(await page.locator('.ab-browser-controls').evaluate(e=>e.getBoundingClientRect().height),height,'Review navigation grows toolbar');
  if(output&&['unusual-transport-madeira-reading-to-speaking','hamburg-city-bikes-listening','ottomotor-vier-takte'].includes(id))await page.screenshot({path:path.join(output,`${id}-bildschirm.png`)});
  await page.evaluate(()=>{window.print=()=>{throw new Error('Dialog unavailable');};});
  await page.locator('#ab-browser-print').click();assert.equal(await page.locator('#ab-print-help').evaluate(e=>e.open),true,'Failure should expose useful fallback');
  await page.emulateMedia({media:'print'});assert.equal(await page.locator('.ab-browser-controls').isVisible(),false);
  const derivedPdf=path.join(scratch,`${id}-browser.pdf`);
  const opts={format:'A4',preferCSSPageSize:true,printBackground:true,displayHeaderFooter:false};
  await page.pdf({...opts,path:derivedPdf});
  await page.emulateMedia({media:'screen'});await page.locator('#ab-review-toggle').click();
  assert.deepEqual(await fieldState(),state,'Returning to A4 lost answers');
  assert(Math.abs(await paper.evaluate(e=>e.getBoundingClientRect().width)-normalPaper.width)<1,'A4 size was not restored');
  await page.emulateMedia({media:'print'});
  // Isolate the added controls in the same resolved document. Re-navigation can
  // change PDF photo-edge antialiasing independently of worksheet geometry.
  await page.locator('.ab-browser-controls').evaluate(e=>e.remove());
  const sourcePdf=path.join(scratch,`${id}-source.pdf`);await page.pdf({...opts,path:sourcePdf});
  const a=await pixels(derivedPdf,path.join(scratch,`${id}-a`));const b=await pixels(sourcePdf,path.join(scratch,`${id}-b`));
  if(output&&JSON.stringify(a)!==JSON.stringify(b)){await copyFile(derivedPdf,path.join(output,`${id}-abweichung-browser.pdf`));await copyFile(sourcePdf,path.join(output,`${id}-abweichung-quelle.pdf`));}
  assert.deepEqual(a,b,`Browser controls changed printed worksheet: ${id}`);
  if(output&&id.startsWith('english-drug-harm-'))await copyFile(derivedPdf,path.join(output,`${id}.pdf`));
  results.push({id,toolbarHeight:height,printPages:a.length,printPixelIdentical:true,keyboardPrint:true,helpDoesNotShiftWorksheet:true,exceptionFallback:true,paperAppearance:true,reviewZoom:true,navigationTargets:tasks,answersPreserved:true,sameDomFields:true});
  await page.close();
 }
 const touch=await browser.newPage({viewport:{width:900,height:1100},hasTouch:true,isMobile:true});
 await touch.goto(pathToFileURL(path.join(skill,'assets/browserstarts/hamburg-city-bikes-listening-browser.html')).href);
 assert(await touch.locator('#ab-browser-print').evaluate(e=>e.getBoundingClientRect().height)>=44,'Touch target too small');await touch.close();
 const fixture=path.join(scratch,'review-fixture');await mkdir(fixture);
 await writeFile(path.join(fixture,'manifest.json'),JSON.stringify({format:'tafelraum-interactive-html',schemaVersion:1,id:'review-fixture',title:'Review fixture',entry:'index.html',defaultViewport:{width:794,height:1123},print:{entry:'index.html',page:'A4',orientation:'portrait',mode:'template',layout:'shared-pages'}}));
 await writeFile(path.join(fixture,'index.html'),'<!doctype html><html lang="de"><head><meta charset="utf-8"><title>Besprechen</title><style>[data-tafelraum-page]{width:210mm;min-height:297mm;padding:15mm;box-sizing:border-box}</style></head><body><main><section data-tafelraum-page><section data-ab-task data-ab-task-title="1 · Lesen"><label for="gemeinsam">Antwort</label><textarea id="gemeinsam"></textarea><label><input type="checkbox" id="wahl">Auswahl</label></section></section><section data-tafelraum-page><section data-ab-task data-ab-task-title="2 · Erklären"><h2>Erklären</h2></section></section></main></body></html>');
 const fixtureStart=path.join(scratch,'review-browser.html');await createBrowserStart({sourceDirectory:fixture,output:fixtureStart});
 const review=await browser.newPage({viewport:{width:1600,height:1000}});await review.goto(pathToFileURL(fixtureStart).href);
 assert.deepEqual(await review.locator('#ab-review-task option').allTextContents(),['1 · Lesen','2 · Erklären']);
 await review.locator('#gemeinsam').fill('Gemeinsame Antwort');await review.locator('#wahl').check();
 await review.locator('#ab-review-toggle').click();await review.locator('#ab-review-task').selectOption('1');
 const largeZoom=await review.evaluate(()=>Number(getComputedStyle(document.documentElement).getPropertyValue('--ab-review-zoom')));
 await review.setViewportSize({width:1000,height:900});
 await review.waitForFunction(z=>Number(getComputedStyle(document.documentElement).getPropertyValue('--ab-review-zoom'))<z,largeZoom);
 await review.locator('#ab-review-toggle').click();assert.equal(await review.locator('#gemeinsam').inputValue(),'Gemeinsame Antwort');assert(await review.locator('#wahl').isChecked());
 await review.close();
 const report={ok:true,packages:results.length,desktopToolbarMax:Math.max(...results.map(r=>r.toolbarHeight)),touchTargetAtLeast44:true,explicitTaskNavigation:true,windowResizeZoom:true,textAndSelectionRetained:true,results};
 if(output)await writeFile(path.join(output,'Browserleisten-Pruefung.json'),JSON.stringify(report,null,2)+'\n');
 console.log(JSON.stringify(report,null,2));
}finally {await browser.close();await rm(scratch,{recursive:true,force:true});}

SHA-256: d40c23d78c66085d85ccb62639ff820ef1351b7e68d7fd50e684ac2b086802d5