ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/shtukbase-ui-html/lib/overflow.ts

lib/overflow.ts

154 líneas, 9.0 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // The overflow test: every state of every component is drawn with long Russian text in a narrow cell, in a real browser
  2. // (headless Chrome), and every text that leaves its box, and every element that leaves the cell, is a failure. A box that
  3. // clips on purpose is allowed: one line ending in an ellipsis, or a line clamp. Pure parts here (the page, the result);
  4. // `runChrome` is the one IO shell. Used by this package's test and by shtukbase-ui-react's, on its rendered states.
  5. import { spawnSync } from 'node:child_process';
  6. import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
  7. import { tmpdir } from 'node:os';
  8. import { join } from 'node:path';
  9. /** Long Russian text: a phrase with long words for longer labels, two long words for short ones. */
  10. export const RU_SHORT = 'Переустановить зависимости';
  11. export const RU_LONG = 'Синхронизировать достопримечательности проекта и переустановить все зависимости пакета «Коллекции»';
  12. const LETTERS = /[A-Za-z].*[A-Za-z].*[A-Za-z]/;
  13. /**
  14. * The markup with every text of three Latin letters or more replaced by long Russian text (initials, keys, numbers and
  15. * separators stay: they are short by nature). Text inside <svg>, <style>, <option> and <script> stays.
  16. */
  17. export function longText(markup: string): string {
  18. let skip = 0;
  19. return markup.replace(/(<\/?([a-z][a-z0-9-]*)\b[^>]*>)|([^<]+)/gi, (all, tag: string, name: string, text: string) => {
  20. if (tag) {
  21. const n = name.toLowerCase();
  22. if (['svg', 'style', 'option', 'script'].includes(n) && !tag.endsWith('/>')) skip += tag.startsWith('</') ? -1 : 1;
  23. return all;
  24. }
  25. if (skip > 0 || !LETTERS.test(text)) return all;
  26. const lead = /^\s*/.exec(text)![0];
  27. const trail = /\s*$/.exec(text)![0];
  28. return lead + (text.trim().length <= 14 ? RU_SHORT : RU_LONG) + trail;
  29. });
  30. }
  31. /**
  32. * The levels the test measures: all of them. The canvas has its own rule: what stands on its stage
  33. * (layout-canvas-stage) may sit outside the view, since the canvas pans; but a label on it may not leave its own card, and
  34. * the canvas controls, the panels and every other text are measured as anywhere else.
  35. */
  36. export const MEASURED_LEVELS = ['primitive', 'composite', 'block', 'shell', 'page'];
  37. /** Cell widths by level: narrow enough to make long text matter, wide enough for the component to make sense. */
  38. export const WIDTHS: Record<string, number> = { primitive: 200, composite: 320, block: 640, shell: 960, page: 960 };
  39. export type Cell = { id: string; state: string; level: string; markup: string; width?: number };
  40. export type Failure = { id: string; state: string; what: string };
  41. /** The test page: the style's tokens and the library CSS, then one cell per state, then the measuring script. */
  42. export function overflowPage(cells: Cell[], css: string, theme: 'light' | 'dark' = 'light'): string {
  43. const body = cells
  44. .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>`)
  45. .join('\n');
  46. return `<!doctype html><html lang="ru"${theme === 'dark' ? ' class="dark"' : ''}><head><meta charset="utf-8"><style>${css}
  47. body{margin:0;padding:16px;font-family:var(--font-sans);background:var(--background);color:var(--foreground)}
  48. .ov-cell{margin:0 0 24px;display:flex;flex-direction:column;align-items:flex-start;gap:8px}
  49. *{animation:none!important;transition:none!important}</style></head><body>
  50. ${body}
  51. <script>${MEASURE}</script></body></html>`;
  52. }
  53. // 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
  54. // 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.
  55. const MEASURE = `(() => {
  56. const fails = [];
  57. const scrolls = (v) => v === 'auto' || v === 'scroll';
  58. const clipsOnPurpose = (s, outX, outY) => (s.overflowX !== 'visible' || s.overflowY !== 'visible') &&
  59. ((outX && !outY && s.textOverflow === 'ellipsis') || (outY && !outX && scrolls(s.overflowY)) || (s.webkitLineClamp && s.webkitLineClamp !== 'none') ||
  60. (s.maskImage && s.maskImage !== 'none') || (s.webkitMaskImage && s.webkitMaskImage !== 'none'));
  61. const name = (e) => e.tagName.toLowerCase() + (e.className && typeof e.className === 'string' ? '.' + e.className.trim().split(/\\s+/)[0] : '');
  62. for (const cell of document.querySelectorAll('.ov-cell')) {
  63. const cr = cell.getBoundingClientRect();
  64. const tag = (what) => fails.push({ id: cell.dataset.id, state: cell.dataset.state, what });
  65. const walk = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);
  66. for (let n; (n = walk.nextNode()); ) {
  67. if (!n.textContent.trim()) continue;
  68. const el = n.parentElement;
  69. if (el.closest('svg,option,select,style,script,template,textarea')) continue;
  70. const cs = getComputedStyle(el);
  71. if (cs.display === 'none' || cs.visibility === 'hidden') continue;
  72. if (el.checkVisibility && !el.checkVisibility({ contentVisibilityAuto: true, visibilityProperty: true })) continue; // a closed <details>
  73. const range = document.createRange(); range.selectNodeContents(n);
  74. let reported = false;
  75. for (const tr of range.getClientRects()) {
  76. if (reported || !tr.width) continue;
  77. for (let a = el; a && a !== cell.parentElement; a = a.parentElement) {
  78. if (a.dataset && a.dataset.slot === 'layout-canvas-stage') break; // the canvas rule: the stage pans
  79. if (a.dataset && a.dataset.slot === 'scroll-area-viewport') break; // a scroll area scrolls both ways on purpose
  80. const s = getComputedStyle(a);
  81. if (s.display === 'inline' || s.display === 'contents') continue;
  82. const ar = a.getBoundingClientRect();
  83. const outX = tr.left < ar.left - 1 || tr.right > ar.right + 1;
  84. const outY = tr.top < ar.top - 2 || tr.bottom > ar.bottom + 2;
  85. if (!outX && !outY) continue;
  86. if (clipsOnPurpose(s, outX, outY)) break;
  87. tag('text "' + n.textContent.trim().slice(0, 24) + '…" leaves ' + name(a) + (outX ? ' sideways' : ' vertically') +
  88. ' (' + Math.round(tr.right - ar.right) + 'px)');
  89. reported = true; break;
  90. }
  91. }
  92. }
  93. for (const e of cell.querySelectorAll('*')) {
  94. if (e.closest('svg') && e.tagName.toLowerCase() !== 'svg') continue;
  95. if (e.closest('[data-slot="layout-canvas-stage"]')) continue; // the canvas rule: content may sit outside the view
  96. if (getComputedStyle(e).opacity === '0') continue; // an invisible native control (Radix puts one next to a switch)
  97. const r = e.getBoundingClientRect();
  98. if (!r.width || (r.right <= cr.right + 1 && r.left >= cr.left - 1)) continue;
  99. let clipped = false;
  100. for (let a = e.parentElement; a && a !== cell; a = a.parentElement) {
  101. const s = getComputedStyle(a);
  102. if (s.overflowX !== 'visible') { clipped = true; break; }
  103. }
  104. if (!clipped) { tag(name(e) + ' is ' + Math.round(r.width) + 'px wide and leaves the ' + Math.round(cr.width) + 'px cell'); break; }
  105. }
  106. }
  107. const pre = document.createElement('pre'); pre.id = 'ov-result'; pre.textContent = JSON.stringify(fails);
  108. document.body.appendChild(pre);
  109. })();`;
  110. /** The failures written by the page into <pre id="ov-result">, read back from the dumped DOM. */
  111. export function parseResult(dom: string): Failure[] | null {
  112. const m = /<pre id="ov-result">([\s\S]*?)<\/pre>/.exec(dom);
  113. if (!m) return null;
  114. return JSON.parse(m[1].replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&'));
  115. }
  116. /** A headless Chrome or Chromium on this machine: $CHROME, the macOS app, or one on the PATH. */
  117. export function findChrome(): string | null {
  118. const env = process.env.CHROME;
  119. if (env && existsSync(env)) return env;
  120. const mac = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
  121. if (existsSync(mac)) return mac;
  122. for (const n of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']) {
  123. const w = spawnSync('which', [n], { encoding: 'utf8' });
  124. if (w.status === 0 && w.stdout.trim()) return w.stdout.trim();
  125. }
  126. return null;
  127. }
  128. /** Loads the page in headless Chrome and returns the failures it found (throws when the page did not report). */
  129. export function runChrome(chrome: string, page: string): Failure[] {
  130. const dir = mkdtempSync(join(tmpdir(), 'sui-overflow-'));
  131. try {
  132. const file = join(dir, 'page.html');
  133. writeFileSync(file, page);
  134. const out = spawnSync(chrome, ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
  135. `--user-data-dir=${join(dir, 'profile')}`, '--window-size=1200,800', '--virtual-time-budget=4000', '--dump-dom', `file://${file}`],
  136. { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 60_000 });
  137. const result = parseResult(out.stdout ?? '');
  138. if (!result) throw new Error(`the overflow page did not report: ${(out.stderr ?? '').slice(0, 400)}`);
  139. return result;
  140. } finally {
  141. rmSync(dir, { recursive: true, force: true });
  142. }
  143. }