#!/usr/bin/env node /** * 终端面板(runner/tui.mjs)自测:纯函数 + 假终端渲染,不需要浏览器、不联网。 * * 为什么需要它:面板的正确性全在「列宽」上——中文占 2 列、ANSI 转义不占列、 * 截断后要补 reset。这三处一旦算错,边框就会歪或者把中文劈成半个, * 而这类问题是肉眼看日志发现不了的(日志文件里根本没有面板)。 * * 用法: * node dev/tests/tui-test.mjs # 断言全部通过则退出码 0 * npm run test:tui */ import { textWidth, stripAnsi, formatDuration, progressBar, visualRows, createTui } from '../../runner/tui.mjs'; let failed = 0; function ok(cond, name, extra) { if (cond) { console.log(' ✔ ' + name); } else { failed++; console.log(' ✘ ' + name + (extra ? ' → ' + extra : '')); } } function eq(actual, expect, name) { ok(actual === expect, name, '期望 ' + JSON.stringify(expect) + ',实际 ' + JSON.stringify(actual)); } // --------------------------------------------------------------------------- // 1. 列宽:中文 2 列、emoji 2 列、组合/控制字符 0 列 // --------------------------------------------------------------------------- console.log('列宽计算'); eq(textWidth('abc'), 3, 'ASCII 每字符 1 列'); eq(textWidth('课程'), 4, '中文每字 2 列'); eq(textWidth('课'), 2, '单字中文'); eq(textWidth('(三)'), 6, '全角标点 2 列'); eq(textWidth('a课b'), 4, '中英混排'); eq(textWidth(''), 0, '空串 0 列'); eq(textWidth('\x1b[32m课\x1b[0m'), 2, 'ANSI 序列不占列'); eq(textWidth(stripAnsi('\x1b[1m\x1b[31mabc\x1b[0m')), 3, 'stripAnsi 后再量'); eq(textWidth('😀'), 2, 'emoji 2 列'); eq(textWidth('█░'), 2, '进度条字符 1 列(非全角)'); // --------------------------------------------------------------------------- // 2. 时长 / 进度条 // --------------------------------------------------------------------------- console.log('时长与进度条'); eq(formatDuration(0), '00:00', '0 秒'); eq(formatDuration(72), '01:12', '72 秒'); eq(formatDuration(3600), '1:00:00', '整小时'); eq(formatDuration(3661), '1:01:01', '超一小时'); eq(formatDuration(-5), '00:00', '负数按 0'); eq(progressBar(0, 4), '░░░░', '0% 全空'); eq(progressBar(1, 4), '████', '100% 全满'); eq(progressBar(0.5, 4), '██░░', '50% 一半'); eq(progressBar(2, 4), '████', '大于 1 截到 1'); eq(progressBar(0.5, 4).length, 4, '进度条宽度准确'); // --------------------------------------------------------------------------- // 3. 帧渲染:假 stdout 捕获一帧,逐行量宽度 // --------------------------------------------------------------------------- console.log('帧渲染'); function makeFrame(opts) { const chunks = []; const out = { columns: opts.columns || 80, rows: opts.rows || 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {}, }; const tui = createTui({ enabled: true, out, stdin: null, color: opts.color !== false, logFile: './run-logs/headless.log', title: '面板测试', }); if (opts.setup) opts.setup(tui, out); // 强制重画一帧(createTui 建的时候已经画过一帧,这里要最后一帧) tui.render(); const frame = chunks[chunks.length - 1] || ''; // 一帧内用 \r\n 分隔;最后一行后面紧跟 \x1b[0J const lines = frame.split('\r\n').map((l) => l.replace(/\x1b\[0J$/, '').replace(/\x1b\[K/g, '')); tui.finish(); return { lines, chunks, frame, out, tui }; } const plain = makeFrame({ columns: 80, color: false }); ok(plain.lines.length >= 12, '帧有足够行数(' + plain.lines.length + ' 行)'); for (const line of plain.lines) { const w = textWidth(stripAnsi(line)); ok(w <= 80, '行宽不超过 80 列', w + ' 列:' + JSON.stringify(stripAnsi(line))); } // 边框的三行必须等宽,否则右边框会锯齿 const boxLines = plain.lines.filter((l) => /^[╭├╰│]/.test(stripAnsi(l))); const widths = [...new Set(boxLines.map((l) => textWidth(stripAnsi(l))))]; eq(widths.length, 1, '所有框线行等宽(实际宽度集合:' + widths.join(',') + ')'); ok(widths[0] === 80, '框线正好占满终端宽度', String(widths[0])); // --------------------------------------------------------------------------- // 4. 彩色帧:ANSI 序列混在中文里也不能顶歪边框 // --------------------------------------------------------------------------- console.log('彩色帧'); const colored = makeFrame({ columns: 84, color: true, setup(tui) { tui.snap({ course: '2025年安全生产月专题培训课程(第三期)', lesson: '第三章 事故应急处置与自救互救', summary: { text: '已学 62%' }, countdown: 42, completed: 3, doneCount: 17, retryCount: 1, retryWait: 12, lessons: 8, video: { t: 812, d: 1320, paused: false, err: 0, src: 1 }, }); tui.set({ phase: '刷课中', tone: 'ok', injected: 4 }); }, }); ok(colored.frame.includes('\x1b['), '彩色帧里确实有 ANSI 序列'); for (const line of colored.lines) { const w = textWidth(stripAnsi(line)); ok(w <= 84, '彩色帧行宽不超过 84 列', w + ' 列'); } const coloredBox = colored.lines.filter((l) => /^[╭├╰│]/.test(stripAnsi(l))); const cw = [...new Set(coloredBox.map((l) => textWidth(stripAnsi(l))))]; eq(cw.length, 1, '彩色帧里框线仍等宽(' + cw.join(',') + ')'); ok(cw[0] === 84, '彩色帧框线占满宽度', String(cw[0])); // 状态行不该出现「多余的省略号」(上一版把带色的状态行误判成超宽) const statusLine = colored.lines.find((l) => stripAnsi(l).includes('状态')); ok(statusLine && !stripAnsi(statusLine).includes('刷课中…'), '状态行没有被误截断'); // --------------------------------------------------------------------------- // 5. 窗口尺寸自适应:宽度跟随终端(不再封顶 120 列)+ 矮终端降级 // --------------------------------------------------------------------------- console.log('窗口尺寸自适应'); { // 宽终端(240 列):框线也得撑满 240,不能停在 120 const wide = makeFrame({ columns: 240, rows: 30, color: false }); const wideBox = wide.lines.filter((l) => /^[╭├╰│]/.test(stripAnsi(l))); const ww = [...new Set(wideBox.map((l) => textWidth(stripAnsi(l))))]; eq(ww.length, 1, '240 列终端:框线仍等宽(' + ww.join(',') + ')'); eq(ww[0], 240, '240 列终端:框线跟随终端宽度(不再封顶 120)'); // 每种高度下,帧的行数都不能超过窗口,否则会把回滚区里的历史顶掉 for (const rows of [40, 30, 24, 20, 16, 14, 12, 10, 8]) { const f = makeFrame({ columns: 100, rows, color: false }); ok(f.lines.length <= rows, rows + ' 行窗口:帧高 ' + f.lines.length + ' 不超过窗口'); } // 24 行:正常模式(有课时 / 日志行) const full = makeFrame({ columns: 100, rows: 24, color: false }); ok(stripAnsi(full.lines.join('\n')).includes('课时'), '24 行窗口:显示课时行'); ok(stripAnsi(full.lines.join('\n')).includes('已注入'), '24 行窗口:显示日志行'); ok(stripAnsi(full.lines.join('\n')).includes('q 退出'), '24 行窗口:显示 q 提示'); // 12 行:紧凑模式,先丢课时/日志,保住视频进度与 q 提示 const tight = makeFrame({ columns: 100, rows: 12, color: false }); const tightText = stripAnsi(tight.lines.join('\n')); ok(!tightText.includes('课时'), '12 行窗口:省掉课时行'); ok(tightText.includes('视频'), '12 行窗口:保留视频进度行'); ok(tightText.includes('进度'), '12 行窗口:保留完成数行'); ok(tightText.includes('q 退出'), '12 行窗口:仍显示 q 提示'); ok(tightText.includes('最近日志'), '12 行窗口:保留日志区(只是变矮)'); // 8 行:极端矮,连 q 提示都省掉,也绝不能有半截框 const tiny = makeFrame({ columns: 100, rows: 8, color: false }); ok(tiny.lines.length <= 8, '8 行窗口:帧高不超过 8(实际 ' + tiny.lines.length + ')'); ok(!tiny.lines[0].includes('\n'), '8 行窗口:标题行完整'); } // --------------------------------------------------------------------------- // 6. 尺寸变化时重画不错位:上帧 24 行 → 窗口缩到 12 行 // --------------------------------------------------------------------------- console.log('尺寸变化重绘'); { const chunks = []; const ESC = String.fromCharCode(27); const CRLF = String.fromCharCode(13, 10); const ANSI_ALL = new RegExp(ESC + '\\\[[0-9;]*[A-Za-z]', 'g'); const foldMarker = ESC + '[H'; const out = { columns: 100, rows: 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {}, }; const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' }); tui.render(); // 窗口缩小到 60×12:上帧每行 100 列,在 60 列下要折成 2 行, // 整块折完远超新窗口高度 —— 光标退不到块首,只能整屏重置 out.rows = 12; out.columns = 60; chunks.length = 0; tui.redraw(); const after = chunks.join(''); ok(after.includes(foldMarker), '旧帧折行后比窗口还高时走整屏重置(ESC[H)'); const lines = after.split(CRLF).map((l) => l.replace(ANSI_ALL, '')); const box = lines.filter((l) => /^[╭├╰│]/.test(l)); const bw = [...new Set(box.map((l) => textWidth(l)))]; eq(bw.length, 1, '缩窗后框线仍等宽(' + bw.join(',') + ')'); eq(bw[0], 60, '缩窗后框线跟新宽度 60'); ok(box.length <= 12, '缩窗后帧高不超过 12(实际 ' + box.length + ')'); tui.finish(); } // --------------------------------------------------------------------------- // 6b. 尺寸小幅变窄:折行后仍装得下窗口 → 精确回退,不整屏重置(保住可视历史) // --------------------------------------------------------------------------- console.log('小幅变窄'); { const chunks = []; const ESC = String.fromCharCode(27); const out = { columns: 120, rows: 48, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} }; const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' }); tui.render(); // 120 列的行在 110 列下折成 2 行,整块约 42 行但仍装得进 48 行的窗口 out.columns = 110; chunks.length = 0; tui.redraw(); const frame = chunks.join(''); ok(!frame.includes(ESC + '[2J'), '装得下时不整屏重置(不白白丢掉上方历史日志)'); ok(/\x1b\[\d+A\x1b\[0J/.test(frame), '改用精确回退(向上退到旧帧首行)'); tui.finish(); } // --------------------------------------------------------------------------- // 7. 没有 resize 事件的平台(Windows 传统控制台):靠定时刷新自己发现尺寸变化 // --------------------------------------------------------------------------- console.log('无 resize 事件的尺寸变化'); { const chunks = []; const CRLF = String.fromCharCode(13, 10); const ESC = String.fromCharCode(27); // 注意:on/removeListener 是空实现,模拟「平台根本不发 resize 事件」 const out = { columns: 100, rows: 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {}, }; const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' }); tui.render(); ok(chunks.length > 0, '首帧已画'); const boxWidths = (text) => [...new Set(text.split(CRLF).map(stripAnsi).filter((l) => /^[╭├╰│]/.test(l)).map(textWidth))]; const boxHeight = (text) => text.split(CRLF).map(stripAnsi).filter((l) => /^[╭├╰│]/.test(l)).length; const clears = (text) => text.split(ESC + '[0J').length - 1; // 最大化:100×24 → 180×40,全程不触发任何事件 out.columns = 180; out.rows = 40; chunks.length = 0; tui.render(); eq(boxWidths(chunks.join('')).join(','), '180', '最大化后框线跟到 180 列(不靠 resize 事件)'); // 缩回去:同样没有事件,必须自己发现并清旧帧 out.columns = 80; out.rows = 20; chunks.length = 0; tui.render(); const shrunk = chunks.join(''); ok(shrunk.includes(ESC + '[2J'), '缩窗时整屏重置(旧帧折行后比窗口还高)'); eq(boxWidths(shrunk).join(','), '80', '缩窗后框线跟到 80 列'); ok(boxHeight(shrunk) <= 20, '缩窗后帧高不超 20 行'); // 尺寸没变时不该多清屏(每帧都清屏会闪) chunks.length = 0; tui.render(); eq(clears(chunks.join('')), 1, '尺寸未变时不多做清屏(只留帧尾那一次)'); tui.finish(); } // --------------------------------------------------------------------------- // 7b. 最大化后还原:终端会把宽行折成多行,回退行数必须按折行后的可视行算 // --------------------------------------------------------------------------- console.log('最大化后还原'); { const chunks = []; const ESC = String.fromCharCode(27); const CRLF = String.fromCharCode(13, 10); const out = { columns: 180, rows: 40, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} }; const tui = createTui({ enabled: true, out, stdin: null, color: false, title: '面板测试' }); chunks.length = 0; tui.render(); // 上一帧是 180 列宽的一整块面板(帧内用 CRLF 分隔,首行前面还有回退控制符); // 只看框线行,它们才是真正撑满宽度的内容行 const wideWidths = chunks.join('').split(CRLF) .map((l) => stripAnsi(l)) .filter((l) => /^[╭├╰│]/.test(l)) .map(textWidth); ok(wideWidths.length > 0 && wideWidths.every((w) => w > 80), '上一帧那些框线行都比 80 列宽(还原后必然折行)'); const folded = visualRows(wideWidths, 80); ok(folded > wideWidths.length, '按 80 列重排后行数变多(' + wideWidths.length + ' → ' + folded + ' 行)'); ok(folded > 24, '折行后(' + folded + ' 行)比新窗口 24 行还高,光标退不到块首'); // 还原到 80 列:不发 resize 事件,靠定时刷新发现 out.columns = 80; out.rows = 24; chunks.length = 0; tui.render(); const back = chunks.join(''); ok(back.includes(ESC + '[H') && back.includes(ESC + '[2J'), '还原时整屏重置,旧帧上半截不会残留'); ok(!/\x1b\[\d+A\x1b\[0J/.test(back), '不再用「向上退 N 行」那条路径(退不到块首)'); const box = back.split(CRLF).map(stripAnsi).filter((l) => /^[╭├╰│]/.test(l)); eq([...new Set(box.map(textWidth))].join(','), '80', '重置后框线是 80 列'); ok(box.length <= 24, '重置后帧高不超 24(实际 ' + box.length + ')'); tui.finish(); } // --------------------------------------------------------------------------- // 7c. visualRows 纯函数 // --------------------------------------------------------------------------- console.log('可视行换算'); { eq(visualRows([80, 80, 80], 80), 3, '不折行时等于行数'); eq(visualRows([160, 160], 80), 4, '两行 160 列在 80 列终端下折成 4 行'); eq(visualRows([181], 80), 3, '181 列折成 3 行(向上取整)'); eq(visualRows([], 80), 0, '空数组 0 行'); eq(visualRows([0, 0], 80), 2, '空白行也占一行'); eq(visualRows([40], 0), 1, '宽度非法时按 1 行算,不会崩'); } // --------------------------------------------------------------------------- // 8. 窄终端:不超界、不硬截断(字段按重要性递降) // --------------------------------------------------------------------------- console.log('极端尺寸'); const narrow = makeFrame({ columns: 36, rows: 12, color: true, setup(tui) { tui.snap({ course: '课程', completed: 3, doneCount: 17, lessons: 8, retryCount: 1, countdown: 812, video: { t: 812, d: 1320, paused: false, err: 0, src: 1 } }); }}); for (const line of narrow.lines) { ok(textWidth(stripAnsi(line)) <= 36, '36 列终端:行宽不超界', String(textWidth(stripAnsi(line)))); } ok(narrow.lines.length <= 12, '矮终端帧行数不超过 12', String(narrow.lines.length)); const narrowText = narrow.lines.map((l) => stripAnsi(l)); const progressLine = narrowText.find((l) => l.includes('进度')); ok(progressLine.includes('本次') && progressLine.includes('累计'), '36 列:进度行保住本次/累计两个骨架字段'); ok(!progressLine.includes('倒计时'), '36 列:进度行主动丢掉倒计时字段(而不是截断成省略号)'); const videoLine = narrowText.find((l) => l.includes('视频')); ok(videoLine.includes('%'), '36 列:视频行保住百分比'); // --------------------------------------------------------------------------- // 9. 学习时长与学分:只算视频真在播的时间,学分只算刷完的课 // --------------------------------------------------------------------------- console.log('学习时长与学分'); { const chunks = []; const out = { columns: 100, rows: 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} }; const tui = createTui({ enabled: true, out, stdin: null, color: false }); const snap = (o) => tui.snap({ course: 'A课', lessons: 3, video: { t: 10, d: 100, paused: false, err: 0, src: 1 }, ...o }); // 视频在播:靠真实的 Date.now 差累计,这里直接用间隔验证(把时钟往前拨太脏,改断言区间) snap({ credit: 2.5 }); eq(tui.state.credit, 2.5, '学分:在播时从倒计时文案读到的本门学分'); eq(tui.state.studySeconds, 0, '首帧没有上一帧可比,不计时'); // 暂停期间不累加:间隔再长也不计入 tui.snap({ course: 'A课', video: { t: 10, d: 100, paused: true, err: 0, src: 1 } }); const pausedAt = tui.state.studySeconds; tui.snap({ course: 'A课', video: { t: 10, d: 100, paused: true, err: 0, src: 1 } }); eq(tui.state.studySeconds, pausedAt, '视频暂停时不计学习时长'); // 播放中才有增量(正常应 < 1 秒,断言「大于 0 且不超 30 秒封顶」) snap({ video: { t: 20, d: 100, paused: false, err: 0, src: 1 } }); const t1 = tui.state.studySeconds; snap({ video: { t: 21, d: 100, paused: false, err: 0, src: 1 } }); const t2 = tui.state.studySeconds; ok(t2 >= t1 && t2 - t1 < 30, '两帧之间按真实间隔累计', t1 + ' → ' + t2); // 倒计时消失(学完)后沿用缓存,不会变回 — snap({ credit: undefined }); eq(tui.state.credit, 2.5, '倒计时消失后沿用本门学分缓存'); // 真的完成了才发分;重复上报不重复计数 snap({ completed: 1 }); eq(tui.state.creditEarned, 2.5, '课程完成后计入获得学分'); snap({ completed: 1 }); eq(tui.state.creditEarned, 2.5, '完成数没变不重复加学分'); // 换课:学分清零待读,学完再累加 snap({ course: 'B课', completed: 1, credit: 1.25 }); eq(tui.state.credit, 1.25, '换课后读到新课的学分'); snap({ course: 'B课', completed: 2, credit: null }); eq(tui.state.creditEarned, 3.75, '第二门学完后累加(2.5 + 1.25)'); // 面板上真的画出来了吗 tui.render(); const frame = (chunks[chunks.length - 1] || '').split('\r\n').map(stripAnsi).join('\n'); ok(frame.includes('学时'), '面板有「学时」行'); ok(frame.includes('已学 '), '「学时」行显示学习时长'); ok(frame.includes('学分 3.75'), '「学时」行显示累计学分', frame.match(/学分[^·│]*/)?.[0]); tui.finish(); // 暂停时提示「不计时」,避免用户以为面板死了 const f2 = makeFrame({ columns: 100, rows: 24, color: false, setup(t2ui) { t2ui.snap({ course: 'A课', video: { t: 10, d: 100, paused: true, err: 0, src: 1 } }); } }); ok(f2.lines.map(stripAnsi).some((l) => l.includes('暂停中,不计时')), '暂停时明确提示不计时'); } // --------------------------------------------------------------------------- // 10. 禁用时是空操作(上层可以无条件调用) // --------------------------------------------------------------------------- console.log('禁用即空操作'); { const chunks = []; const out = { columns: 80, rows: 24, isTTY: false, write(s) { chunks.push(s); }, on() {}, removeListener() {} }; let quitCalled = 0; const tui = createTui({ enabled: false, out, stdin: null, onQuit: () => quitCalled++ }); tui.set({ phase: '不该出现' }); tui.snap({ course: '不该出现', video: { t: 1, d: 2 } }); tui.render(); tui.finish(); eq(chunks.length, 0, '禁用时不写任何字节'); eq(tui.state.phase, '启动中', '禁用时 set 不改状态'); eq(tui.logLines.length, 0, '禁用时不缓存日志'); eq(quitCalled, 0, '禁用时不会触发退出回调'); } // --------------------------------------------------------------------------- // 11. 收尾:finish 只生效一次,且恢复光标 / 换行 // --------------------------------------------------------------------------- console.log('收尾'); { const chunks = []; const out = { columns: 80, rows: 24, isTTY: true, write(s) { chunks.push(s); }, on() {}, removeListener() {} }; const tui = createTui({ enabled: true, out, stdin: null, color: false }); chunks.length = 0; tui.finish(); const after = chunks.join(''); ok(after.includes('\x1b[?25h'), 'finish 恢复了光标(?25h)'); ok(after.startsWith('\n'), 'finish 先换行,收尾日志不会盖在面板上'); chunks.length = 0; tui.finish(); eq(chunks.length, 0, '重复 finish 不重复输出'); } console.log(''); if (failed) { console.log('TUI 自测:' + failed + ' 项失败'); process.exit(1); } console.log('TUI 自测:全部通过');