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

169 lines
13 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', '82', '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'), digits: rect('#stat-score b'), unit: rect('#stat-score i'), title: rect('.ring-center .stat-label'),
ageTitle: rect('.sum-age > .stat-label'), age: rect('#stat-age b'),
careAlign: getComputedStyle(document.querySelector('.card-care .card-heading')).textAlign };
});
assert(Math.abs(layout.unit.x - layout.digits.x - layout.digits.width - 2) < 1, 'score unit follows digits in the same row');
assert(Math.abs(layout.unit.x + layout.unit.width - layout.score.x - layout.score.width) < 1, 'score row includes the unit width');
assert(Math.abs(layout.score.x + layout.score.width / 2 - layout.dial.x - layout.dial.width / 2) < 1, 'score and unit jointly horizontally centered: ' + width + '/' + score);
assert(Math.abs(layout.title.y - layout.score.bottom) < 1, 'score title below the number with zero gap');
assert(Math.abs(layout.title.x + layout.title.width / 2 - layout.score.x - layout.score.width / 2) < 1, 'score title and number share the same horizontal center');
assert(Math.abs((layout.score.y + layout.title.bottom) / 2 - layout.dial.y - layout.dial.height / 2) < 1, 'complete score + label stack vertically centered');
assert(layout.score.y > layout.dial.y && layout.title.bottom < layout.dial.bottom, 'both score and label stay inside the circle');
assert(Math.abs(layout.age.y - layout.ageTitle.bottom) < 1, 'age label-to-number gap is zero');
assert(Math.abs((layout.ageTitle.y + layout.age.bottom) / 2 - layout.dial.y - layout.dial.height / 2) < 1, 'complete age stack vertically centered against the score circle');
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, text = false, steps = 2, horizontal = false } = {}) {
const frame = card.locator('.dpanel.active ' + (text ? '.ditem-text' : '.viz-frame'));
await frame.scrollIntoViewIfNeeded(); await page.waitForTimeout(400);
const box = await frame.boundingBox(), x = box.x + box.width / 2, y = box.y + box.height / 2;
const before = await offset(card), previous = await selected(card), now = flick ? Date.now() / 1000 : null;
const scrollBefore = await page.locator('#s-report').evaluate(el => el.scrollTop);
const beforeHeight = await card.locator('.detail-viewport').evaluate(el => el.getBoundingClientRect().height);
await touch('touchStart', x, y, now);
for (let step = 1; step <= steps; step++) {
await touch('touchMove', x + dx * step / steps, y + dy * step / steps, now && now + .04 * step / steps);
if (steps > 2) await page.waitForTimeout(20);
}
const liveOffset = await offset(card), limit = await card.locator('.detail-viewport').evaluate(el => el.clientWidth * (el.querySelectorAll('.dpanel').length - 1));
assert(liveOffset <= 17 && liveOffset >= -limit - 17, 'edge resistance caps overscroll at 16px');
if (horizontal) {
assert(Math.abs(liveOffset - before - dx) < 3, 'diagonal drag remains finger-following before release');
assert.equal(await card.locator('.detail-panels.dragging').count(), 1, 'browser does not cancel diagonal image gesture');
assert(Math.abs(await page.locator('#s-report').evaluate(el => el.scrollTop) - scrollBefore) < 1, 'diagonal image gesture does not scroll the report');
}
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);
assert(Math.abs(await card.locator('.detail-viewport').evaluate(el => el.getBoundingClientRect().height) - beforeHeight) < 1, 'card height stays fixed during horizontal dragging');
await card.locator('.dpanel.active .ditem-text').evaluate(el => {
const growth = document.createElement('span');
growth.dataset.testGrowth = ''; growth.style.cssText = 'display:block;height:80px'; el.append(growth);
});
await page.waitForTimeout(100);
assert(Math.abs(await card.locator('.detail-viewport').evaluate(el => el.getBoundingClientRect().height) - beforeHeight) < 1, 'height stays fixed even when panel content resizes while held');
await card.locator('[data-test-growth]').evaluate(el => el.remove());
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);
if (horizontal) assert(Math.abs(await page.locator('#s-report').evaluate(el => el.scrollTop) - scrollBefore) < 1, 'horizontal release has no vertical momentum');
if (dy <= -80 && Math.abs(dx) < 10) {
assert(await page.locator('#s-report').evaluate(el => el.scrollTop) > scrollBefore + 10, 'vertical gesture actually scrolls the report');
}
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, 65, { dy: -60 }); assert.equal(await selected(card), '0', 'diagonal image gesture prioritizes horizontal switching');
for (const [dx, dy] of [[-60, -75], [-80, -90]]) {
await drag(card, dx, { dy, steps: 6, horizontal: true });
assert.equal(await selected(card), '1', 'vertical-heavy diagonal still uses configured horizontal priority');
await card.locator('.dtab').first().click(); await page.waitForTimeout(400);
}
await card.locator('.dtab').nth(1).click(); await page.waitForTimeout(400);
await drag(card, 100, { text: true }); assert.equal(await selected(card), '1', 'horizontal dragging on analysis text does not switch tabs');
await drag(card, 2, { dy: -90, text: true }); assert.equal(await selected(card), '1', 'reading text keeps vertical scrolling and current 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: whole score stack centered inside circle/gapless age stack vertically centered/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(); }