import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import process from "node:process"; import { chromium, type Page } from "@playwright/test"; /** * 화면을 사람 눈으로 보기 위한 촬영기. 디자인을 검토할 때 쓴다. * *

손으로 찍으면 두 가지를 반드시 놓친다. 첫째, 뷰포트다. 브라우저 세션이 리셋되면 창은 * 기본 크기(약 877px)로 돌아가는데 그 폭은 이 사이트의 900px 분기 아래라 헤더가 접힌 좁은 * 화면이 나온다 — 방문자 대부분이 보지 않는 배치를 보면서 검토하게 된다. 둘째, 전체 페이지를 * 한 장으로 찍으면 세로로 긴 문서가 통째로 축소되어 17px 글자가 7~8px 로 뭉갠다. 덩어리는 * 보이지만 정작 타이포는 못 본다. * *

그래서 폭을 고정 목록으로 돌고, 화면 높이만큼씩 잘라 찍는다. 잊을 자리를 없앤다. * *

눈으로 본 인상은 어디가 이상한지까지만 알려 준다. 얼마나 잘못됐는지는 값이 말해야 하므로 * 매 폭마다 측정도 함께 남긴다 — 실제로 고친 결함(목록 항목 간격 0px, 한 줄 53자)은 전부 * 이 측정에서 나왔다. */ /** 이 사이트의 반응형 분기는 1179 / 1050 / 900 / 767 이다. 그 위·사이·아래를 하나씩 본다. */ const WIDTHS = [1440, 900, 390] as const; const VIEWPORT_HEIGHT = 900; /** 한 폭당 이만큼까지만 자른다. 문서가 길어도 검토는 앞쪽에서 대부분 끝난다. */ const MAX_SLICES = 6; const OUTPUT_DIRECTORY = "artifacts/design-review"; type Measurement = { readonly width: number; readonly layoutWidth: number; readonly scrollbarWidth: number; readonly horizontalOverflow: boolean; readonly overflowingElements: readonly string[]; readonly text: readonly TextMeasurement[]; readonly lists: readonly ListMeasurement[]; }; type TextMeasurement = { readonly selector: string; readonly fontSize: string; readonly lineHeight: string; readonly widthPx: number; /** 한글 기준 한 줄 글자 수. 25~40 이 편한 범위이고 그보다 길면 줄을 놓치기 쉽다. */ readonly charactersPerLine: number; }; type ListMeasurement = { readonly section: string; readonly items: number; readonly marker: string; /** 항목 사이 실제 간격. 0 이면서 마커도 없으면 여러 줄 항목이 한 덩어리로 보인다. */ readonly gapPx: number | null; readonly separatedByPadding: boolean; }; function slugOf(url: string): string { const { pathname } = new URL(url); const cleaned = pathname.replace(/^\/+|\/+$/gu, "").replace(/[^a-zA-Z0-9-]+/gu, "-"); return cleaned || "home"; } async function measure(page: Page, width: number): Promise { return page.evaluate((viewportWidth: number) => { const root = document.documentElement; const layoutWidth = root.clientWidth; const text = ["main p", "main li", "h1"].flatMap((selector) => { const element = document.querySelector(selector); if (!element) return []; const style = getComputedStyle(element); const box = element.getBoundingClientRect(); const fontSize = Number.parseFloat(style.fontSize); return [ { selector, fontSize: style.fontSize, lineHeight: style.lineHeight, widthPx: Math.round(box.width), charactersPerLine: fontSize > 0 ? Math.round(box.width / fontSize) : 0, }, ]; }); const lists = [...document.querySelectorAll("main ul, main ol")].map((list) => { const items = [...list.children]; const first = items[0]; const second = items[1]; const itemStyle = first ? getComputedStyle(first) : null; const gapPx = first && second ? Math.round( second.getBoundingClientRect().top - first.getBoundingClientRect().bottom, ) : null; return { section: list.closest("section")?.querySelector("h2")?.textContent?.trim().slice(0, 16) ?? String(list.className).slice(0, 24) ?? "(이름 없음)", items: items.length, marker: getComputedStyle(list).listStyleType, gapPx, /* 여백이 항목 안(padding)에 있으면 박스 사이는 0으로 나온다 — 그것도 구분이다. */ separatedByPadding: itemStyle ? Number.parseFloat(itemStyle.paddingTop) > 0 || Number.parseFloat(itemStyle.borderBottomWidth) > 0 : false, }; }); return { width: viewportWidth, layoutWidth, scrollbarWidth: window.innerWidth - layoutWidth, horizontalOverflow: root.scrollWidth > layoutWidth, overflowingElements: [...document.querySelectorAll("body *")] .filter((element) => { const box = element.getBoundingClientRect(); return box.width > 0 && box.right > layoutWidth + 1; }) .slice(0, 5) .map((element) => `${element.tagName}.${String(element.className).slice(0, 24)}`), text, lists, }; }, width); } async function capture(page: Page, url: string, width: number): Promise { await page.setViewportSize({ width, height: VIEWPORT_HEIGHT }); /* `networkidle` 은 오지 않는다 — 이 앱은 유휴 상태에서도 요청을 계속 보낸다. 기다려야 하는 것은 네트워크가 조용해지는 순간이 아니라 본문이 그려진 순간이므로 제목이 나올 때까지 기다린다. */ await page.goto(url, { waitUntil: "domcontentloaded" }); await page.waitForSelector("main h1", { timeout: 15_000 }); const slug = slugOf(url); const pageHeight = await page.evaluate(() => document.documentElement.scrollHeight); const slices = Math.min(Math.ceil(pageHeight / VIEWPORT_HEIGHT), MAX_SLICES); for (let index = 0; index < slices; index += 1) { await page.evaluate((top: number) => window.scrollTo(0, top), index * VIEWPORT_HEIGHT); // 스크롤에 붙은 전환이 끝나기를 기다린다. 반쯤 그려진 화면을 남기면 검토가 그것을 지적한다. await page.waitForTimeout(250); await page.screenshot({ path: path.join(OUTPUT_DIRECTORY, `${slug}-${width}-${index + 1}.png`), scale: "css", }); } await page.evaluate(() => window.scrollTo(0, 0)); return measure(page, width); } async function main(): Promise { const urls = process.argv.slice(2); if (urls.length === 0) { process.stderr.write( "사용법: node scripts/capture-public-screens.ts [URL...]\n" + `폭 ${WIDTHS.join(" / ")} 로 각각 찍고 ${OUTPUT_DIRECTORY}/ 에 남긴다.\n`, ); process.exitCode = 1; return; } await mkdir(OUTPUT_DIRECTORY, { recursive: true }); const browser = await chromium.launch(); const report: Record = {}; try { const page = await browser.newPage(); for (const url of urls) { const measurements: Measurement[] = []; for (const width of WIDTHS) { const measurement = await capture(page, url, width); measurements.push(measurement); const body = measurement.text.find((entry) => entry.selector === "main p"); const worstList = measurement.lists.find( (list) => list.gapPx === 0 && list.marker === "none" && !list.separatedByPadding, ); process.stdout.write( `${url} ${width}px → 레이아웃 ${measurement.layoutWidth}px` + (body ? `, 본문 ${body.charactersPerLine}자/줄` : "") + (measurement.horizontalOverflow ? ", 가로 넘침 있음" : "") + (worstList ? `, 구분 없는 목록: ${worstList.section}` : "") + "\n", ); } report[url] = measurements; } } finally { await browser.close(); } const reportPath = path.join(OUTPUT_DIRECTORY, "measurements.json"); await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8"); process.stdout.write(`\n측정값: ${reportPath}\n스크린샷: ${OUTPUT_DIRECTORY}/\n`); } await main();