cover_validate.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #!/usr/bin/env node
  2. /**
  3. * cover_validate.js — Cover page overlap detection via Playwright rendering
  4. *
  5. * Detects text-vs-decorative-line overlap on cover HTML pages by:
  6. * 1. Rendering the HTML in Playwright
  7. * 2. Waiting for fonts to load
  8. * 3. Measuring bounding boxes of text elements and decorative line elements
  9. * 4. Checking for Y-axis overlap (minimum spacing = 1U = 5% of page width ≈ 30pt)
  10. *
  11. * Usage:
  12. * node cover_validate.js cover.html
  13. * node cover_validate.js cover.html --width 210mm --height 297mm
  14. * node cover_validate.js cover.html --min-gap 30 # custom min gap in px (default: auto = 5% of width)
  15. *
  16. * Exit codes:
  17. * 0 = no overlap issues found
  18. * 1 = overlap detected (prints details to stderr)
  19. * 2 = script error (missing file, browser launch failure, etc.)
  20. *
  21. * This script is ONLY for cover pages. Do NOT use it on:
  22. * - Multi-page documents (use html2pdf-next.js pre-render checks)
  23. * - Posters (use html2poster.js which handles overflow automatically)
  24. */
  25. 'use strict';
  26. const fs = require('fs');
  27. const path = require('path');
  28. // ── Playwright import ──
  29. let playwright;
  30. try {
  31. playwright = require('playwright');
  32. } catch {
  33. try {
  34. playwright = require('playwright-core');
  35. } catch {
  36. console.error('✗ Neither playwright nor playwright-core is installed.');
  37. process.exit(2);
  38. }
  39. }
  40. // ── Chromium resolution (shared logic with html2poster.js) ──
  41. function resolveChromium(chromiumObj) {
  42. let exe;
  43. try { exe = chromiumObj.executablePath(); } catch (_) { exe = null; }
  44. if (exe && fs.existsSync(exe)) return { status: 'ok', executablePath: exe };
  45. const candidates = [
  46. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  47. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  48. '/usr/bin/chromium-browser', '/usr/bin/chromium', '/usr/bin/google-chrome',
  49. ];
  50. if (process.env.PLAYWRIGHT_CHROMIUM_PATH) candidates.unshift(process.env.PLAYWRIGHT_CHROMIUM_PATH);
  51. for (const c of candidates) {
  52. if (fs.existsSync(c)) return { status: 'fallback', executablePath: c };
  53. }
  54. return { status: 'missing', executablePath: exe || '' };
  55. }
  56. // ── CLI parsing ──
  57. function parseArgs(argv) {
  58. const tokens = argv.slice(2);
  59. let input = null, width = '210mm', height = '297mm', minGap = null;
  60. for (let i = 0; i < tokens.length; i++) {
  61. const t = tokens[i];
  62. if (t === '--width') width = tokens[++i];
  63. else if (t === '--height') height = tokens[++i];
  64. else if (t === '--min-gap') minGap = parseFloat(tokens[++i]);
  65. else if (t === '--help' || t === '-h') {
  66. console.log(`Usage: node cover_validate.js <cover.html> [options]
  67. Options:
  68. --width <val> Page width (default: 210mm)
  69. --height <val> Page height (default: 297mm)
  70. --min-gap <px> Minimum gap between text and decorative lines (default: 5% of width)
  71. --help Show this help`);
  72. process.exit(0);
  73. } else if (!t.startsWith('-') && !input) {
  74. input = t;
  75. }
  76. }
  77. return { input, width, height, minGap };
  78. }
  79. // ── Convert CSS dimension string to px for viewport ──
  80. function dimToPx(dim) {
  81. if (!dim) return null;
  82. const s = String(dim).trim();
  83. const num = parseFloat(s);
  84. if (s.endsWith('mm')) return Math.round(num * 3.7795); // 1mm ≈ 3.7795px at 96dpi
  85. if (s.endsWith('cm')) return Math.round(num * 37.795);
  86. if (s.endsWith('in')) return Math.round(num * 96);
  87. if (s.endsWith('px') || !isNaN(num)) return Math.round(num);
  88. return null;
  89. }
  90. // ── Decorative line detection heuristics ──
  91. // A decorative line is an element that:
  92. // - Is very thin in one dimension (height ≤ 5px or width ≤ 5px)
  93. // - OR is an <hr> element
  94. // - OR has a large aspect ratio (> 10:1 or < 1:10)
  95. // - AND is not inside a text element
  96. const DECORATIVE_LINE_DETECTION = `
  97. (function detectOverlaps(minGapPx) {
  98. // Collect all elements
  99. const allElements = document.querySelectorAll('*');
  100. const textElements = [];
  101. const lineElements = [];
  102. // Classify elements
  103. for (const el of allElements) {
  104. const rect = el.getBoundingClientRect();
  105. if (rect.width === 0 || rect.height === 0) continue;
  106. const tag = el.tagName.toLowerCase();
  107. const style = getComputedStyle(el);
  108. // Skip invisible elements
  109. if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') continue;
  110. // Detect decorative lines
  111. const isHR = tag === 'hr';
  112. const isThinH = rect.height <= 5 && rect.width > 20; // thin horizontal line
  113. const isThinV = rect.width <= 5 && rect.height > 20; // thin vertical line
  114. const aspectH = rect.width / rect.height;
  115. const aspectV = rect.height / rect.width;
  116. const isWideRatio = aspectH > 15 && rect.height <= 8; // very wide, very thin
  117. const isTallRatio = aspectV > 15 && rect.width <= 8; // very tall, very thin
  118. // Check if element has only border (no text content, no background image)
  119. const hasOnlyBorder = (
  120. el.textContent.trim() === '' &&
  121. style.backgroundImage === 'none' &&
  122. (style.borderTopWidth !== '0px' || style.borderBottomWidth !== '0px' ||
  123. style.borderLeftWidth !== '0px' || style.borderRightWidth !== '0px')
  124. );
  125. const isBorderLine = hasOnlyBorder && (rect.height <= 8 || rect.width <= 8);
  126. if (isHR || isThinH || isThinV || isWideRatio || isTallRatio || isBorderLine) {
  127. lineElements.push({
  128. tag: tag,
  129. class: el.className || '',
  130. rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
  131. type: isThinH || isWideRatio ? 'horizontal' : (isThinV || isTallRatio ? 'vertical' : (rect.width >= rect.height ? 'horizontal' : 'vertical')),
  132. });
  133. continue;
  134. }
  135. // Detect text elements (has direct text content or is a heading/paragraph)
  136. const textTags = ['h1','h2','h3','h4','h5','h6','p','span','a','li','td','th','label','summary'];
  137. const hasDirectText = Array.from(el.childNodes).some(n => n.nodeType === 3 && n.textContent.trim());
  138. if (textTags.includes(tag) || hasDirectText) {
  139. // Skip if this is inside a decorative element
  140. if (rect.height < 3) continue;
  141. textElements.push({
  142. tag: tag,
  143. class: el.className || '',
  144. text: el.textContent.trim().substring(0, 60),
  145. rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
  146. });
  147. }
  148. }
  149. // De-duplicate: if a parent and child text element both overlap the same line,
  150. // only keep the more specific (smaller) one to avoid duplicate reports.
  151. // Sort text elements by area (smallest first) so we can skip parents.
  152. textElements.sort((a, b) => (a.rect.width * a.rect.height) - (b.rect.width * b.rect.height));
  153. // Check overlaps between text elements and line elements
  154. const overlaps = [];
  155. const reportedPairs = new Set(); // track "lineIndex:textContent" to deduplicate
  156. for (const text of textElements) {
  157. for (const line of lineElements) {
  158. const tr = text.rect;
  159. const lr = line.rect;
  160. if (line.type === 'horizontal') {
  161. // Check vertical overlap/proximity
  162. const textTop = tr.y;
  163. const textBottom = tr.y + tr.height;
  164. const lineTop = lr.y;
  165. const lineBottom = lr.y + lr.height;
  166. // Check horizontal overlap (they must share some X range)
  167. const xOverlap = !(tr.x + tr.width < lr.x || lr.x + lr.width < tr.x);
  168. if (!xOverlap) continue;
  169. // Calculate vertical gap
  170. let vGap;
  171. if (lineTop >= textBottom) {
  172. vGap = lineTop - textBottom; // line is below text
  173. } else if (textTop >= lineBottom) {
  174. vGap = textTop - lineBottom; // line is above text
  175. } else {
  176. vGap = 0; // overlapping
  177. }
  178. if (vGap < minGapPx) {
  179. // De-dup: same line region, only report the smallest (most specific) text element
  180. const lineKey = 'h:' + Math.round(lr.x) + ',' + Math.round(lr.y);
  181. if (!reportedPairs.has(lineKey)) {
  182. reportedPairs.add(lineKey);
  183. overlaps.push({
  184. text: text.text,
  185. textTag: text.tag,
  186. textClass: text.class,
  187. textRect: tr,
  188. lineTag: line.tag,
  189. lineClass: line.class,
  190. lineRect: lr,
  191. lineType: line.type,
  192. gap: Math.round(vGap * 10) / 10,
  193. required: minGapPx,
  194. });
  195. }
  196. }
  197. } else if (line.type === 'vertical') {
  198. // Check horizontal overlap/proximity
  199. const textLeft = tr.x;
  200. const textRight = tr.x + tr.width;
  201. const lineLeft = lr.x;
  202. const lineRight = lr.x + lr.width;
  203. // Check vertical overlap (they must share some Y range)
  204. const yOverlap = !(tr.y + tr.height < lr.y || lr.y + lr.height < tr.y);
  205. if (!yOverlap) continue;
  206. // Calculate horizontal gap
  207. let hGap;
  208. if (lineLeft >= textRight) {
  209. hGap = lineLeft - textRight;
  210. } else if (textLeft >= lineRight) {
  211. hGap = textLeft - lineRight;
  212. } else {
  213. hGap = 0;
  214. }
  215. if (hGap < minGapPx) {
  216. const lineKey = 'v:' + Math.round(lr.x) + ',' + Math.round(lr.y);
  217. if (!reportedPairs.has(lineKey)) {
  218. reportedPairs.add(lineKey);
  219. overlaps.push({
  220. text: text.text,
  221. textTag: text.tag,
  222. textClass: text.class,
  223. textRect: tr,
  224. lineTag: line.tag,
  225. lineClass: line.class,
  226. lineRect: lr,
  227. lineType: line.type,
  228. gap: Math.round(hGap * 10) / 10,
  229. required: minGapPx,
  230. });
  231. }
  232. }
  233. }
  234. }
  235. }
  236. return {
  237. textElements: textElements.length,
  238. lineElements: lineElements.length,
  239. overlaps: overlaps,
  240. };
  241. })
  242. `;
  243. // ── Main ──
  244. async function main() {
  245. const { input, width, height, minGap } = parseArgs(process.argv);
  246. if (!input) {
  247. console.error('✗ No input file specified. Usage: node cover_validate.js cover.html');
  248. process.exit(2);
  249. }
  250. const absIn = path.resolve(input);
  251. if (!fs.existsSync(absIn)) {
  252. console.error(`✗ File not found: ${absIn}`);
  253. process.exit(2);
  254. }
  255. const widthPx = dimToPx(width) || 794; // A4 width in px
  256. const heightPx = dimToPx(height) || 1123; // A4 height in px
  257. const gap = minGap || Math.round(widthPx * 0.05); // 1U = 5% of page width
  258. console.log(`🔍 cover_validate — Cover overlap detection`);
  259. console.log(` Input: ${absIn}`);
  260. console.log(` Page: ${widthPx}×${heightPx}px`);
  261. console.log(` Min gap: ${gap}px (1U)`);
  262. const { chromium } = playwright;
  263. const bInfo = resolveChromium(chromium);
  264. if (bInfo.status === 'missing') {
  265. console.error('✗ No Chromium found. Install via: npx playwright install chromium');
  266. process.exit(2);
  267. }
  268. let browser;
  269. try {
  270. const opts = { headless: true };
  271. if (bInfo.status === 'fallback') opts.executablePath = bInfo.executablePath;
  272. browser = await chromium.launch(opts);
  273. } catch (err) {
  274. console.error(`✗ Browser launch failed: ${err.message}`);
  275. process.exit(2);
  276. }
  277. try {
  278. const page = await browser.newPage({ viewport: { width: widthPx, height: heightPx } });
  279. await page.goto('file://' + absIn, { waitUntil: 'networkidle' });
  280. console.log(` ✓ HTML loaded`);
  281. // Wait for fonts
  282. const fontsLoaded = await page.evaluate(() =>
  283. document.fonts.ready.then(() => document.fonts.size)
  284. ).catch(() => 0);
  285. console.log(` ✓ Fonts: ${fontsLoaded} loaded`);
  286. // Run overlap detection
  287. const result = await page.evaluate(`(${DECORATIVE_LINE_DETECTION})(${gap})`);
  288. console.log(` ✓ Found ${result.textElements} text elements, ${result.lineElements} decorative lines`);
  289. if (result.overlaps.length === 0) {
  290. console.log(`\n ✅ No overlap issues found`);
  291. process.exit(0);
  292. }
  293. // Report overlaps
  294. console.error(`\n ❌ Found ${result.overlaps.length} text-line overlap(s):\n`);
  295. for (const o of result.overlaps) {
  296. const direction = o.lineType === 'vertical' ? 'horizontal' : 'vertical';
  297. console.error(` ERROR: ${direction} gap = ${o.gap}px (required ≥ ${o.required}px)`);
  298. console.error(` Text: <${o.textTag}> "${o.text}" @ y=${Math.round(o.textRect.y)}-${Math.round(o.textRect.y + o.textRect.height)}`);
  299. console.error(` Line: <${o.lineTag}${o.lineClass ? '.' + o.lineClass.split(' ')[0] : ''}> [${o.lineType}] @ y=${Math.round(o.lineRect.y)}-${Math.round(o.lineRect.y + o.lineRect.height)}`);
  300. console.error(` Fix: Move the decorative line at least ${Math.ceil(o.required - o.gap)}px away from the text.`);
  301. console.error('');
  302. }
  303. process.exit(1);
  304. } finally {
  305. await browser.close();
  306. }
  307. }
  308. main().catch(err => {
  309. console.error(`✗ Unexpected error: ${err.message}`);
  310. process.exit(2);
  311. });