Files
materials/408/ds12-tree/verify.mjs

311 lines
15 KiB
JavaScript
Raw Normal View History

feat: 每个资料子页面加回导航页的返回入口;导航页与 Docker/Linux/Nginx/408 站点入库 一、子页面返回入口(本次改动) - 新增 assets/back.js:在页面顶栏的站点标题之后挂「← 资料库」,点一下回根目录 index.html 并直接落在本资料的详情路由(如 #/knowledge/docker);注册表之外的目录 (408/)回首页;没有顶栏的页面(408 的 404)退化为左下角浮动按钮 - 层级由脚本自己的 src 反推(new URL('../', src)),任何目录深度都不必改 back.js; 样式跟随各站点:描边 / 文字用 currentColor、主色用 var(--brand) / var(--accent)、 圆角跟随 var(--btn-radius),深浅色主题都自适应,打印时自动隐藏;页面里已有 index.html#/ 形式的返回链接时(interview/ 占位页)不再重复挂 - 新增 tools/add-back-links.js:按 assets/portal.data.js 反查路由与名称,给每个子页面 注入 <script src="…assets/back.js" data-portal-back=… data-portal-label=…>。 先删旧标签再按规则插回,位置写错也能自动纠正;--check 只检查(缺一个即退出码 1)、 --dry 只预演、写入失败不会中断整轮 - 共注入 454 个页面,3 个有意跳过:根 index.html(它本身就是导航页)、 interview/index.html(已有「← 返回导航」)、408/ds12-tree/og.html(分享预览图页面) - 末尾是内联 <script> 的 7 个 index.html:标签插在内联脚本之前,保持 </script>\s*</body> 的既有形态,各站点自检规则不受影响 - .sre-s23/gen.js 的两处模板同步带上该行,重新生成 SRE 模块页不会丢入口 - README 补「子页面怎么回到导航页」一节,并在新增资料流程里加上这一步 二、此前未入库的内容(一并提交) - 导航页:index.html + assets/portal.css|portal.data.js|portal.js + tools/check-portal.js - knowledge/docker(14 章)、knowledge/linux(17 章)、knowledge/nginx(17 章) - 408/ds12-tree 知识卡片(app.js / styles.css / verify.mjs / favicon / og) - interview 占位页、README.md 校验 - add-back-links --check:454 / 454 已就绪 - check-portal:3 个模块 / 6 份资料全部命中(无死链) - check-pages:docker 15 页、linux 18 页、nginx 18 页、sre-learning-path 399 页 全部 OK - 无头 Chrome 实测点击:docker 章节页 / SRE 模块页 / 场景题库 / 项目题库 / 408 卡片页 都落到对应资料详情,404 的浮动按钮回导航首页;按钮颜色浅色 rgb(23,33,46) 深色 rgb(231,237,246) 自适应,408 站点圆角保持 0px - 受版本管理的 402 个页面每个只 +1 行(gen.js +2 行),没有整文件改写 说明:本机沙箱下 knowledge/sre-learning-path/**、408/、knowledge/scenario、project/、 interview/ 这些文件当时不可写(缺低完整性标记),注入是在一次完全权限授权下完成的。
2026-10-14 22:42:38 +08:00
/* DS-12 · 验收台架
每条断言都对着一句具体的抱怨,不是综合打分。
用法:node verify.mjs [--shots]
*/
import { createRequire } from 'module';
import { fileURLToPath } from 'url';
import path from 'path';
const GP = '/home/wonder/.nvm/versions/node/v22.22.2/lib/node_modules/@playwright/test/node_modules/playwright-core';
const require = createRequire(import.meta.url);
const { chromium } = require(GP);
const dir = path.dirname(fileURLToPath(import.meta.url));
const URL = 'file://' + path.join(dir, 'index.html');
const wantShots = process.argv.includes('--shots');
const results = [];
const check = (name, ok, detail) => {
results.push({ name, ok, detail });
console.log(`${ok ? ' PASS' : ' FAIL'} ${name}${detail ? ' — ' + detail : ''}`);
};
const mean = a => a.reduce((s, x) => s + x, 0) / (a.length || 1);
const browser = await chromium.launch();
/* ══════════ 1 · 控制台与结构 ══════════ */
{
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
const page = await ctx.newPage();
const errs = [];
page.on('console', m => { if (m.type() === 'error') errs.push(m.text()); });
page.on('pageerror', e => errs.push('pageerror: ' + e.message));
await page.goto(URL, { waitUntil: 'load' });
await page.waitForTimeout(700);
check('console/page errors = 0', errs.length === 0, errs.slice(0, 3).join(' | '));
const s = await page.evaluate(() => ({
lang: document.documentElement.lang,
h1: document.querySelectorAll('h1').length,
title: document.title.length,
desc: (document.querySelector('meta[name=description]') || {}).content || '',
og: (document.querySelector('meta[property="og:image"]') || {}).content || '',
icon: !!document.querySelector('link[rel~=icon]'),
sections: document.querySelectorAll('main section').length,
shapes: new Set(Array.from(document.querySelectorAll('main > section')).map(x => x.className)).size
}));
check('lang = zh-Hans', s.lang === 'zh-Hans', s.lang);
check('exactly one <h1>', s.h1 === 1, String(s.h1));
check('title 40–60 chars', s.title >= 40 && s.title <= 60, String(s.title));
check('description present', s.desc.length > 40, String(s.desc.length));
check('og:image is absolute', /^https?:\/\//.test(s.og), s.og);
check('favicon linked', s.icon);
check('≥3 distinct section shapes', s.shapes >= 3, `shapes=${s.shapes} sections=${s.sections}`);
/* ══════════ 2 · 横向溢出 ══════════ */
for (const w of [320, 375, 414, 768, 1440]) {
await page.setViewportSize({ width: w, height: 860 });
await page.waitForTimeout(320);
const ov = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
check(`no horizontal overflow @${w}`, ov <= 0, `overflow=${ov}px`);
}
/* ══════════ 2b · 版式真的落地了 ══════════ */
await page.setViewportSize({ width: 1440, height: 900 });
await page.waitForTimeout(320);
// 抱怨:网格子项里的 <b> 会自成一格、一个字一行
const rules = await page.evaluate(() => Array.from(document.querySelectorAll('.rules li')).map(li => ({
kids: li.children.length,
bold: Array.from(li.querySelectorAll('b')).map(x => Math.round(x.getBoundingClientRect().height))
})));
check('规则列表每行 2 个子项', rules.every(r => r.kids === 2), rules.map(r => r.kids).join(','));
check('规则列表里没有一个字一行', rules.every(r => r.bold.every(h => h <= 26)),
rules.map(r => r.bold.join('/')).join(' '));
// 抱怨:导航高亮到了不在导航里的章节就卡住不动
await page.evaluate(() => { document.documentElement.style.scrollBehavior = 'auto'; });
await page.evaluate(() => {
const e = document.getElementById('think');
window.scrollTo(0, e.getBoundingClientRect().top + window.scrollY + 120);
});
await page.waitForTimeout(360);
const stale = await page.evaluate(() => {
const a = document.querySelector('.nav a[aria-current="true"]');
return a ? a.getAttribute('href') : '(none)';
});
check('导航高亮不会卡在上一章', stale === '(none)', `此刻高亮=${stale}`);
/* ══════════ 3 · 变形:必须真的在重挂 ══════════ */
await page.setViewportSize({ width: 1440, height: 900 });
await page.waitForTimeout(300);
// 进场动画必须真的会收尾:停在 0 的字等于内容丢失
await page.evaluate(() => {
const e = document.getElementById('creed');
window.scrollTo(0, e.getBoundingClientRect().top + window.scrollY - 200);
});
await page.waitForTimeout(1400);
const revealed = await page.evaluate(() =>
Array.from(document.querySelectorAll('.creed__seg')).map(e => getComputedStyle(e).opacity));
check('进场动画会收尾(口诀不是永久隐藏)',
revealed.every(o => parseFloat(o) > 0.99), revealed.join(','));
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForTimeout(200);
const a = await page.evaluate(() => window.__setMorph(0).heroPos);
const b = await page.evaluate(() => window.__setMorph(1).heroPos);
const disp = a.map((p, i) => Math.hypot(p[1] - b[i][1], p[2] - b[i][2]));
check('morph moves every node', disp.every(d => d > 12), `min=${Math.min(...disp).toFixed(1)}`);
check('morph moves nodes a lot', mean(disp) > 60, `mean=${mean(disp).toFixed(1)} units`);
/* ══════════ 4 · 真手势:鼠标拖动进度条 ══════════ */
// 邀请必须在首屏里:拖动条看不见,就没人知道这图能拖
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForTimeout(220);
const firstScreen = await page.evaluate(() => {
const b = document.getElementById('scrubTrack').getBoundingClientRect();
return { top: b.top, bottom: b.bottom, vh: window.innerHeight, y: window.scrollY };
});
check('拖动条在首屏内(邀请看得见)',
firstScreen.y === 0 && firstScreen.bottom > 0 && firstScreen.bottom <= firstScreen.vh,
`scrollY=${firstScreen.y} bottom=${Math.round(firstScreen.bottom)} / vh=${firstScreen.vh}`);
await page.locator('#scrubTrack').scrollIntoViewIfNeeded();
await page.waitForTimeout(150);
const box = await page.locator('#scrubTrack').boundingBox();
const before = await page.evaluate(() => ({ t: window.__probe().heroT, y: window.scrollY }));
await page.mouse.move(box.x + box.width * 0.9, box.y + box.height / 2);
await page.mouse.down();
for (let i = 1; i <= 12; i++) {
await page.mouse.move(box.x + box.width * (0.9 - 0.82 * i / 12), box.y + box.height / 2);
await page.waitForTimeout(16);
}
await page.mouse.up();
const after = await page.evaluate(() => ({ t: window.__probe().heroT, y: window.scrollY }));
const dragRan = Math.abs(after.t - before.t);
check('real drag drives the morph', dragRan > 0.45, `Δt=${dragRan.toFixed(3)} (from ${before.t} to ${after.t})`);
check('drag never cleared its threshold', dragRan > 0.05, `peak Δt=${dragRan.toFixed(3)}`);
check('drag lands where the pointer stopped', Math.abs(after.t - 0.08) < 0.14, `t=${after.t}`);
check('drag does not scroll the page', Math.abs(after.y - before.y) < 4, `ΔscrollY=${(after.y - before.y).toFixed(1)}`);
/* ══════════ 5 · 遍历:两条互相拉扯的断言 ══════════ */
const rPre = await page.evaluate(() => window.__runTrace('pre'));
const rPost = await page.evaluate(() => window.__runTrace('post'));
const rLvl = await page.evaluate(() => window.__runTrace('level'));
check('先根序列 = 先序序列', rPre.same === true && rPre.tree.join('') === rPre.bt.join(''),
`${rPre.tree.join('')} / ${rPre.bt.join('')}`);
check('后根序列 = 中序序列', rPost.same === true,
`${rPost.tree.join('')} / ${rPost.bt.join('')}`);
check('层序序列 ≠ 二叉树层序序列', rLvl.same === false && rLvl.tree.join('') !== rLvl.bt.join(''),
`${rLvl.tree.join('')} / ${rLvl.bt.join('')}`);
check('后根 ≠ 后序(后根不是二叉树后序)',
rPost.tree.join('') !== (rPost.btPost || []).join(''),
`后根=${rPost.tree.join('')} vs 二叉树后序=${(rPost.btPost || []).join('')}`);
// 真点击跑一遍
await page.locator('#traceBar .tg[data-mode="level"]').click();
await page.waitForTimeout(2900);
const v = await page.evaluate(() => document.getElementById('seqVerdict').textContent);
check('real click runs the tracer', /对不上/.test(v), v.slice(0, 40));
/* ══════════ 6 · 计数标注 ══════════ */
const m = await page.evaluate(() => window.__probe().marks);
check('无左孩子圈数 = 6(叶子)', m.left === 6, String(m.left));
check('无右孩子框数 = 5', m.right === 5, String(m.right));
await page.locator('#forestStepper .step[data-step="3"]').click();
await page.waitForTimeout(260);
const chain = await page.evaluate(() => window.__probe().marks.chain);
check('右链 3 个结点 = 树的棵数', chain === 3, String(chain));
/* ══════════ 7 · 判卷:空状态 + 正确 + 错误 ══════════ */
await page.locator('#quiz').scrollIntoViewIfNeeded();
await page.locator('#gradeBtn').click();
await page.waitForTimeout(120);
const empty = await page.evaluate(() => {
const r = document.getElementById('quizResult');
return { shown: !r.hidden, empty: r.classList.contains('is-empty'), txt: r.textContent };
});
check('空状态:没选答案会说明', empty.shown && empty.empty, empty.txt.slice(0, 30));
for (const [q, idx] of [['1', 2], ['2', 2], ['3', 2]]) {
await page.locator(`.q[data-q="${q}"] .opt`).nth(idx - 1).click();
}
await page.locator('#gradeBtn').click();
await page.waitForTimeout(160);
const graded = await page.evaluate(() => ({
st: window.__quizState(),
txt: document.getElementById('quizResult').textContent,
expl: Array.from(document.querySelectorAll('.q__expl')).map(e => e.classList.contains('is-shown'))
}));
check('三题全选正确 → 3 / 3', graded.st.every(x => x.picked === x.answer) && /3 \/ 3/.test(graded.txt),
graded.txt.slice(0, 26));
check('每题都给出解析', graded.expl.every(Boolean));
await page.locator('#resetBtn').click();
await page.locator('.q[data-q="1"] .opt').nth(0).click();
await page.locator('#gradeBtn').click();
await page.waitForTimeout(140);
const wrong = await page.evaluate(() => ({
marked: !!document.querySelector('.opt.is-wrong'),
correct: !!document.querySelector('.opt.is-correct'),
txt: document.getElementById('quizResult').textContent
}));
check('选错会标出正确项与你的选项', wrong.marked && wrong.correct, wrong.txt.slice(0, 22));
if (wantShots) {
await page.evaluate(() => window.__setMorph(1));
await page.screenshot({ path: path.join(dir, 'shot-desktop.png'), fullPage: false });
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForTimeout(200);
await page.screenshot({ path: path.join(dir, 'shot-full.png'), fullPage: true });
}
await ctx.close();
}
/* ══════════ 8 · 关掉 JS:内容必须本来就在页面上 ══════════ */
{
const ctx = await browser.newContext({
viewport: { width: 1440, height: 900 },
javaScriptEnabled: false
});
const page = await ctx.newPage();
await page.goto(URL, { waitUntil: 'load' });
await page.waitForTimeout(400);
const nojs = await page.evaluate(() => {
const creed = Array.from(document.querySelectorAll('.creed__seg'));
const hidden = creed.filter(e => parseFloat(getComputedStyle(e).opacity) < 0.99).length;
return {
creedVisible: hidden === 0,
creedText: creed.map(e => e.textContent.trim().slice(0, 6)).join(' / '),
expl: Array.from(document.querySelectorAll('.q__expl')).map(e => getComputedStyle(e).display !== 'none'),
h1: document.querySelector('h1').textContent.replace(/\s/g, '').slice(0, 10),
rows: document.querySelectorAll('.rules li, .pit__item, .idx__row').length
};
});
check('关掉 JS,口诀仍然看得见', nojs.creedVisible, nojs.creedText);
check('关掉 JS,正文仍然完整', nojs.rows >= 14 && nojs.h1.includes('一棵树'), `${nojs.rows} 行 · h1=${nojs.h1}`);
check('关掉 JS,三题解析退化成答案册', nojs.expl.filter(Boolean).length === 3, nojs.expl.join(','));
await ctx.close();
}
/* ══════════ 9 · reduced-motion:不能有东西卡在看不见 ══════════ */
{
const ctx = await browser.newContext({
viewport: { width: 1440, height: 900 },
reducedMotion: 'reduce'
});
const page = await ctx.newPage();
const errs = [];
page.on('pageerror', e => errs.push(e.message));
await page.goto(URL, { waitUntil: 'load' });
await page.waitForTimeout(600);
const r = await page.evaluate(() => {
const probe = window.__probe();
const hidden = [];
document.querySelectorAll('.sec, .creed, .hero__title, .seq__v, .q').forEach(e => {
const cs = getComputedStyle(e);
const b = e.getBoundingClientRect();
if (parseFloat(cs.opacity) < 0.99 || b.height < 2) hidden.push(e.className + ':' + cs.opacity);
});
return { reduced: probe.reduced, hidden, heroT: probe.heroT, seq: probe.seq1, verdict: probe.verdict };
});
check('reduced-motion 生效', r.reduced === true);
check('reduced-motion 下没有东西卡在隐藏态', r.hidden.length === 0, r.hidden.slice(0, 3).join(' | '));
check('reduced-motion 下静态呈现转换结果', r.heroT === 1, `heroT=${r.heroT}`);
check('reduced-motion 下序列仍然可读', r.seq.length > 5, r.seq);
check('reduced-motion 无运行时错误', errs.length === 0, errs.slice(0, 2).join('|'));
if (wantShots) {
await page.screenshot({ path: path.join(dir, 'shot-reduced.png'), fullPage: true });
}
await ctx.close();
}
/* ══════════ 10 · 移动端静帧 ══════════ */
{
const ctx = await browser.newContext({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
hasTouch: true,
isMobile: true,
reducedMotion: 'reduce'
});
const page = await ctx.newPage();
await page.goto(URL, { waitUntil: 'load' });
await page.waitForTimeout(600);
const ov = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
check('no horizontal overflow @390 (touch)', ov <= 0, `overflow=${ov}px`);
const small = await page.evaluate(() => {
const bad = [];
document.querySelectorAll('button, a.btn, .opt, .step, .tg, .acc summary').forEach(e => {
const b = e.getBoundingClientRect();
if (b.height > 0 && b.height < 44) bad.push((e.className || e.tagName) + ':' + Math.round(b.height));
});
return bad;
});
check('触摸目标 ≥ 44px', small.length === 0, small.slice(0, 4).join(' | '));
if (wantShots) {
await page.screenshot({ path: path.join(dir, 'shot-mobile.png'), fullPage: true });
}
await ctx.close();
}
await browser.close();
const fails = results.filter(r => !r.ok);
console.log(`\n════════ VERDICT: ${fails.length ? 'FAIL' : 'PASS'} ════════ ${results.length - fails.length}/${results.length} checks`);
if (fails.length) {
console.log('failing: ' + fails.map(f => f.name).join(' · '));
process.exit(1);
}