Files
juzi/h5/test/report-touch-layout.mjs
T

132 lines
9.3 KiB
JavaScript

// Real mobile pointer dispatch on the actual report. Auth/analysis writes blocked.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
const { chromium } = await import(pathToFileURL(execSync('npm root -g', { encoding: 'utf8' }).trim() + '/playwright/index.mjs').href);
const base = process.env.H5_BASE_URL || 'http://127.0.0.1:8080/';
const root = fileURLToPath(new URL('../../', import.meta.url));
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'design/ui-20261012/delivery-optimization-20261012.json')));
for (const asset of manifest.assets) {
for (const [file, expected] of [[asset.source, asset.source_sha256], [asset.file, asset.sha256]]) {
assert.equal(crypto.createHash('sha256').update(fs.readFileSync(path.join(root, file))).digest('hex'), expected);
}
assert(asset.bytes < asset.source_bytes * .9 && asset.psnr_db >= 40);
}
const browser = await chromium.launch({ headless: true });
try {
const page = await browser.newPage({ viewport: { width: 375, height: 726 }, isMobile: true, hasTouch: true });
page.setDefaultTimeout(60000); // Public-site cold font/fixture downloads may exceed 30s.
const errors = [], writes = [];
page.on('pageerror', e => errors.push(e.message));
await page.route('**/*', route => {
const req = route.request();
if (req.method() !== 'GET') { writes.push(req.url()); return route.abort(); }
if (req.url().endsWith('/api/auth/session')) return route.fulfill({ json: { ok: true, user: { id: 'report-touch-fixture', kind: 'browser' } } });
return route.continue();
});
await page.goto(base + '?mock=1&screen=report', { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => document.querySelector('#stat-score b').textContent !== '--' && [...document.querySelectorAll('.ditem-img')].every(i => !i.hidden && i.naturalWidth));
await page.evaluate(async () => { await Promise.all([document.fonts.load('500 40px MiSans'), document.fonts.load('400 12px MiSans')]); });
for (const width of [320, 375, 390, 414, 480]) {
await page.setViewportSize({ width, height: 844 });
await page.waitForTimeout(400);
for (const score of ['0', '75', '100', '--']) {
await page.locator('#stat-score b').evaluate((el, value) => { el.textContent = value; }, score);
const layout = await page.evaluate(() => {
const rect = selector => {
const r = document.querySelector(selector).getBoundingClientRect();
return { x: r.x, y: r.y, width: r.width, height: r.height, bottom: r.bottom };
};
return { dial: rect('.score-dial'), score: rect('#stat-score b'), title: rect('.sum-score > .stat-label'),
ageTitle: rect('.sum-age > .stat-label'), age: rect('.age-dial'),
careAlign: getComputedStyle(document.querySelector('.card-care .card-heading')).textAlign };
});
assert(Math.abs(layout.score.x + layout.score.width / 2 - layout.dial.x - layout.dial.width / 2) < 1, 'score horizontally centered: ' + width + '/' + score);
assert(Math.abs(layout.score.y + layout.score.height / 2 - layout.dial.y - layout.dial.height / 2) < 1, 'score vertically centered');
assert(layout.title.bottom < layout.dial.y && layout.ageTitle.bottom < layout.age.y, 'labels outside above their values');
assert(Math.abs(layout.title.y - layout.ageTitle.y) < 1, 'labels share top alignment');
assert.equal(layout.careAlign, 'left');
}
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
}
await page.locator('#stat-score b').evaluate(el => { el.textContent = '75'; });
await page.setViewportSize({ width: 375, height: 726 });
const cdp = await page.context().newCDPSession(page), cards = page.locator('.card-detail');
const offset = card => card.locator('.detail-panels').evaluate(el => new DOMMatrix(getComputedStyle(el).transform).m41);
const selected = card => card.locator('.dtab.active').getAttribute('data-tab');
const touch = (type, x, y, timestamp) => cdp.send('Input.dispatchTouchEvent', {
type, ...(timestamp ? { timestamp } : {}), touchPoints: /touchEnd|touchCancel/.test(type) ? [] : [{ x, y, id: 1 }]
});
async function drag(card, dx, { dy = 0, cancel = false, pause = 0, flick = false, verify = false } = {}) {
const frame = card.locator('.dpanel.active .viz-frame');
await frame.scrollIntoViewIfNeeded(); await page.waitForTimeout(400);
const box = await frame.boundingBox(), x = box.x + box.width / 2, y = Math.min(500, box.y + box.height / 2);
const before = await offset(card), previous = await selected(card), now = flick ? Date.now() / 1000 : null;
await touch('touchStart', x, y, now);
await touch('touchMove', x + dx / 2, y + dy / 2, now && now + .02);
await touch('touchMove', x + dx, y + dy, now && now + .04);
if (verify) {
assert(Math.abs(await offset(card) - before - dx) < 3, 'report follows finger before release');
assert.equal(await selected(card), previous, 'selection commits only on release');
assert.equal(await card.locator('.detail-panels.dragging').count(), 1);
if (process.env.H5_ARTIFACT_DIR) {
fs.mkdirSync(process.env.H5_ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.H5_ARTIFACT_DIR, 'report-drag-' + await card.locator('.dtab').first().textContent() + '.png') });
}
}
if (pause) await page.waitForTimeout(pause);
await touch(cancel ? 'touchCancel' : 'touchEnd', 0, 0, now && now + .05);
await page.waitForTimeout(400);
assert.equal(await card.locator('.detail-panels.dragging').count(), 0);
assert.equal(await page.locator('#p-zoom.show').count(), 0, 'drag never opens zoom');
}
async function aligned(card) {
const state = await card.evaluate(el => {
const viewport = el.querySelector('.detail-viewport'), active = el.querySelector('.dpanel.active');
return { viewport: viewport.getBoundingClientRect().height, panel: active.offsetHeight,
delta: active.getBoundingClientRect().left - viewport.getBoundingClientRect().left,
selected: el.querySelectorAll('.dtab[aria-selected="true"][tabindex="0"]').length,
accessible: [...el.querySelectorAll('.dpanel')].filter(p => !p.inert && p.getAttribute('aria-hidden') === 'false').length };
});
assert(Math.abs(state.viewport - state.panel) < 2 && Math.abs(state.delta) < 2, 'selected panel fits/aligned: ' + JSON.stringify(state));
assert.equal(state.selected, 1); assert.equal(state.accessible, 1);
}
for (let i = 0; i < 3; i++) {
const card = cards.nth(i);
await drag(card, -100, { verify: true }); assert.equal(await selected(card), '1'); await aligned(card);
await drag(card, 25, { pause: 160 }); assert.equal(await selected(card), '1', 'short slow drag snaps back');
await drag(card, 100, { cancel: true }); assert.equal(await selected(card), '1', 'cancellation restores selection');
await drag(card, 2, { dy: -90 }); assert.equal(await selected(card), '1', 'vertical scrolling preserves tab');
await drag(card, 40, { flick: true }); assert.equal(await selected(card), '0', 'short fast flick goes back');
await drag(card, 100); assert.equal(await selected(card), '0', 'first edge cannot overshoot');
await card.locator('.dtab').last().click(); await page.waitForTimeout(400); await aligned(card);
await drag(card, -100); assert.equal(await selected(card), String(i === 1 ? 2 : 1), 'last edge cannot overshoot');
await card.locator('.dtab').last().focus(); await page.keyboard.press('Home'); await page.waitForTimeout(400); await aligned(card);
}
await drag(cards.nth(1), -100); await drag(cards.nth(1), -100); assert.equal(await selected(cards.nth(1)), '2');
assert.equal(await selected(cards.nth(0)), '0'); assert.equal(await selected(cards.nth(2)), '0', 'groups are independent');
const image = cards.nth(0).locator('.dpanel.active .ditem-img');
await image.click(); await page.waitForSelector('#p-zoom.show');
assert.equal(await page.locator('#zoom-img').getAttribute('src'), await image.getAttribute('src'));
await page.click('#p-zoom'); await page.waitForTimeout(400);
for (const width of [320, 390, 480]) {
await page.setViewportSize({ width, height: 844 }); await page.waitForTimeout(400);
for (const card of await cards.all()) await aligned(card);
}
for (const asset of manifest.assets) {
const response = await page.request.get(new URL(asset.file.replace(/^h5\//, ''), base).href);
assert.equal(response.status(), 200); assert(response.headers()['content-type'].startsWith('image/jpeg'));
assert.equal((await response.body()).length, asset.bytes);
}
if (process.env.H5_ARTIFACT_DIR) {
await page.setViewportSize({ width: 375, height: 726 });
await page.locator('#s-report').evaluate(el => { el.scrollTop = 0; });
await page.screenshot({ path: path.join(process.env.H5_ARTIFACT_DIR, 'report-summary.png') });
}
assert.deepEqual(errors, []); assert.deepEqual(writes, []);
console.log('PASS: score centered/labels above/care left in five widths; real finger-following three report groups, flick/snap/cancel/vertical/edges/keyboard/zoom/resize/height/ARIA; smaller JPEG hashes/dimensions/MIME; no JS errors/backend writes');
} finally { await browser.close(); }