包文件→ .shtukbase/packages/shtukbase-ui-html/lib/overflow.ts
lib/overflow.ts
154 行, 9.0 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The overflow test: every state of every component is drawn with long Russian text in a narrow cell, in a real browser
- // (headless Chrome), and every text that leaves its box, and every element that leaves the cell, is a failure. A box that
- // clips on purpose is allowed: one line ending in an ellipsis, or a line clamp. Pure parts here (the page, the result);
- // `runChrome` is the one IO shell. Used by this package's test and by shtukbase-ui-react's, on its rendered states.
- import { spawnSync } from 'node:child_process';
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { join } from 'node:path';
- /** Long Russian text: a phrase with long words for longer labels, two long words for short ones. */
- export const RU_SHORT = 'Переустановить зависимости';
- export const RU_LONG = 'Синхронизировать достопримечательности проекта и переустановить все зависимости пакета «Коллекции»';
- const LETTERS = /[A-Za-z].*[A-Za-z].*[A-Za-z]/;
- /**
- * The markup with every text of three Latin letters or more replaced by long Russian text (initials, keys, numbers and
- * separators stay: they are short by nature). Text inside <svg>, <style>, <option> and <script> stays.
- */
- export function longText(markup: string): string {
- let skip = 0;
- return markup.replace(/(<\/?([a-z][a-z0-9-]*)\b[^>]*>)|([^<]+)/gi, (all, tag: string, name: string, text: string) => {
- if (tag) {
- const n = name.toLowerCase();
- if (['svg', 'style', 'option', 'script'].includes(n) && !tag.endsWith('/>')) skip += tag.startsWith('</') ? -1 : 1;
- return all;
- }
- if (skip > 0 || !LETTERS.test(text)) return all;
- const lead = /^\s*/.exec(text)![0];
- const trail = /\s*$/.exec(text)![0];
- return lead + (text.trim().length <= 14 ? RU_SHORT : RU_LONG) + trail;
- });
- }
- /**
- * The levels the test measures: all of them. The canvas has its own rule: what stands on its stage
- * (layout-canvas-stage) may sit outside the view, since the canvas pans; but a label on it may not leave its own card, and
- * the canvas controls, the panels and every other text are measured as anywhere else.
- */
- export const MEASURED_LEVELS = ['primitive', 'composite', 'block', 'shell', 'page'];
- /** Cell widths by level: narrow enough to make long text matter, wide enough for the component to make sense. */
- export const WIDTHS: Record<string, number> = { primitive: 200, composite: 320, block: 640, shell: 960, page: 960 };
- export type Cell = { id: string; state: string; level: string; markup: string; width?: number };
- export type Failure = { id: string; state: string; what: string };
- /** The test page: the style's tokens and the library CSS, then one cell per state, then the measuring script. */
- export function overflowPage(cells: Cell[], css: string, theme: 'light' | 'dark' = 'light'): string {
- const body = cells
- .map((c) => `<div class="ov-cell" data-id="${c.id}" data-state="${c.state}" style="width:${c.width ?? WIDTHS[c.level] ?? 320}px">${longText(c.markup)}</div>`)
- .join('\n');
- return `<!doctype html><html lang="ru"${theme === 'dark' ? ' class="dark"' : ''}><head><meta charset="utf-8"><style>${css}
- body{margin:0;padding:16px;font-family:var(--font-sans);background:var(--background);color:var(--foreground)}
- .ov-cell{margin:0 0 24px;display:flex;flex-direction:column;align-items:flex-start;gap:8px}
- *{animation:none!important;transition:none!important}</style></head><body>
- ${body}
- <script>${MEASURE}</script></body></html>`;
- }
- // Runs in the page. Text: each line box of a text must lie inside every block box around it up to the cell, unless that
- // box clips on purpose (an ellipsis, a line clamp, a mask; a box that scrolls vertically; a scroll area). Elements: none may leave the cell, unless a box between them and the cell clips it.
- const MEASURE = `(() => {
- const fails = [];
- const scrolls = (v) => v === 'auto' || v === 'scroll';
- const clipsOnPurpose = (s, outX, outY) => (s.overflowX !== 'visible' || s.overflowY !== 'visible') &&
- ((outX && !outY && s.textOverflow === 'ellipsis') || (outY && !outX && scrolls(s.overflowY)) || (s.webkitLineClamp && s.webkitLineClamp !== 'none') ||
- (s.maskImage && s.maskImage !== 'none') || (s.webkitMaskImage && s.webkitMaskImage !== 'none'));
- const name = (e) => e.tagName.toLowerCase() + (e.className && typeof e.className === 'string' ? '.' + e.className.trim().split(/\\s+/)[0] : '');
- for (const cell of document.querySelectorAll('.ov-cell')) {
- const cr = cell.getBoundingClientRect();
- const tag = (what) => fails.push({ id: cell.dataset.id, state: cell.dataset.state, what });
- const walk = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);
- for (let n; (n = walk.nextNode()); ) {
- if (!n.textContent.trim()) continue;
- const el = n.parentElement;
- if (el.closest('svg,option,select,style,script,template,textarea')) continue;
- const cs = getComputedStyle(el);
- if (cs.display === 'none' || cs.visibility === 'hidden') continue;
- if (el.checkVisibility && !el.checkVisibility({ contentVisibilityAuto: true, visibilityProperty: true })) continue; // a closed <details>
- const range = document.createRange(); range.selectNodeContents(n);
- let reported = false;
- for (const tr of range.getClientRects()) {
- if (reported || !tr.width) continue;
- for (let a = el; a && a !== cell.parentElement; a = a.parentElement) {
- if (a.dataset && a.dataset.slot === 'layout-canvas-stage') break; // the canvas rule: the stage pans
- if (a.dataset && a.dataset.slot === 'scroll-area-viewport') break; // a scroll area scrolls both ways on purpose
- const s = getComputedStyle(a);
- if (s.display === 'inline' || s.display === 'contents') continue;
- const ar = a.getBoundingClientRect();
- const outX = tr.left < ar.left - 1 || tr.right > ar.right + 1;
- const outY = tr.top < ar.top - 2 || tr.bottom > ar.bottom + 2;
- if (!outX && !outY) continue;
- if (clipsOnPurpose(s, outX, outY)) break;
- tag('text "' + n.textContent.trim().slice(0, 24) + '…" leaves ' + name(a) + (outX ? ' sideways' : ' vertically') +
- ' (' + Math.round(tr.right - ar.right) + 'px)');
- reported = true; break;
- }
- }
- }
- for (const e of cell.querySelectorAll('*')) {
- if (e.closest('svg') && e.tagName.toLowerCase() !== 'svg') continue;
- if (e.closest('[data-slot="layout-canvas-stage"]')) continue; // the canvas rule: content may sit outside the view
- if (getComputedStyle(e).opacity === '0') continue; // an invisible native control (Radix puts one next to a switch)
- const r = e.getBoundingClientRect();
- if (!r.width || (r.right <= cr.right + 1 && r.left >= cr.left - 1)) continue;
- let clipped = false;
- for (let a = e.parentElement; a && a !== cell; a = a.parentElement) {
- const s = getComputedStyle(a);
- if (s.overflowX !== 'visible') { clipped = true; break; }
- }
- if (!clipped) { tag(name(e) + ' is ' + Math.round(r.width) + 'px wide and leaves the ' + Math.round(cr.width) + 'px cell'); break; }
- }
- }
- const pre = document.createElement('pre'); pre.id = 'ov-result'; pre.textContent = JSON.stringify(fails);
- document.body.appendChild(pre);
- })();`;
- /** The failures written by the page into <pre id="ov-result">, read back from the dumped DOM. */
- export function parseResult(dom: string): Failure[] | null {
- const m = /<pre id="ov-result">([\s\S]*?)<\/pre>/.exec(dom);
- if (!m) return null;
- return JSON.parse(m[1].replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&'));
- }
- /** A headless Chrome or Chromium on this machine: $CHROME, the macOS app, or one on the PATH. */
- export function findChrome(): string | null {
- const env = process.env.CHROME;
- if (env && existsSync(env)) return env;
- const mac = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
- if (existsSync(mac)) return mac;
- for (const n of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']) {
- const w = spawnSync('which', [n], { encoding: 'utf8' });
- if (w.status === 0 && w.stdout.trim()) return w.stdout.trim();
- }
- return null;
- }
- /** Loads the page in headless Chrome and returns the failures it found (throws when the page did not report). */
- export function runChrome(chrome: string, page: string): Failure[] {
- const dir = mkdtempSync(join(tmpdir(), 'sui-overflow-'));
- try {
- const file = join(dir, 'page.html');
- writeFileSync(file, page);
- const out = spawnSync(chrome, ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
- `--user-data-dir=${join(dir, 'profile')}`, '--window-size=1200,800', '--virtual-time-budget=4000', '--dump-dom', `file://${file}`],
- { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 60_000 });
- const result = parseResult(out.stdout ?? '');
- if (!result) throw new Error(`the overflow page did not report: ${(out.stderr ?? '').slice(0, 400)}`);
- return result;
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- }