// 실제 Chromium + 프로젝트 CSS/폰트로 열 자동 너비를 검증한다(운영 서버·DB 미사용). // python tests/js/render_goals.py // NODE_PATH= node tests/js/goals_autofit.browser.test.js // 설치된 Chrome 사용 시 PJ_TEST_BROWSER= 지정. const assert = require("node:assert/strict"); const fs = require("node:fs"); const http = require("node:http"); const path = require("node:path"); const { chromium } = require("playwright"); const ROOT = path.resolve(__dirname, "../.."); const STATIC = path.join(ROOT, "app/static"); const server = http.createServer(function (req, res) { const url = new URL(req.url, "http://localhost"); if (url.pathname === "/project/goals/2026") { const html = fs.readFileSync(path.join(__dirname, ".out/goals_admin.html"), "utf8") .replace("", '
') .replace("", "
"); res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return; } if (url.pathname.startsWith("/project/api/")) { res.setHeader("Content-Type", "application/json"); res.end("{}"); return; } const file = path.resolve(STATIC, "." + decodeURIComponent(url.pathname.slice(7))); if (!url.pathname.startsWith("/static/") || !file.startsWith(STATIC + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { res.statusCode = 404; res.end(); return; } const types = { ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".woff": "font/woff" }; res.setHeader("Content-Type", types[path.extname(file)] || "application/octet-stream"); fs.createReadStream(file).pipe(res); }); (async function () { let browser; try { await new Promise(function (resolve) { server.listen(0, "127.0.0.1", resolve); }); browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined }); const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); const errors = [], writes = []; page.on("pageerror", function (e) { errors.push(e.message); }); page.on("request", function (r) { if (r.method() !== "GET") writes.push(r.url()); }); await page.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026"); await page.evaluate(async function () { await document.fonts.ready; const a = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'); const b = document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]'); a.value = "다담: 100 백만(김지통)\n주부콩: 20백만(김지통)"; b.value = "pj-rich:v1:" + JSON.stringify([{ text: "가장 긴 문단: 글자 크기와 굵기도 반영", size: 32, bold: true }, { text: " 끝" }]); window.autofitDraft = b.value; document.getElementById("pj-goal-pane").scrollTop = 0; }); async function fit(key) { await page.locator('thead .pj-goal-colresize[data-col="' + key + '"]').dblclick(); } async function widths() { return page.evaluate(function () { const td = document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').closest("td"); const head = document.querySelector('thead th[data-col="m1"]'); return { logical: parseFloat(head.style.getPropertyValue("--cw")), cell: td.getBoundingClientRect().width, zoom: document.documentElement.classList.contains("pj-ui-scale") ? 0.75 : 1 }; }); } await fit("m1"); const rich = await widths(); const expected = await page.evaluate(function () { const td = document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').closest("td"); const editor = td.querySelector(".pj-goal-text"), ctx = document.createElement("canvas").getContext("2d"); let textWidth = 0; Array.from(editor.childNodes).forEach(function (node) { const style = getComputedStyle(node.nodeType === 1 ? node : editor); ctx.font = style.fontWeight + " " + style.fontSize + " " + style.fontFamily; textWidth += ctx.measureText(node.textContent).width; }); const cellStyle = getComputedStyle(td), style = getComputedStyle(editor); return textWidth + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(cellStyle.borderRightWidth); }); assert(rich.logical >= expected && rich.logical <= expected + 4, JSON.stringify({ rich, expected })); assert(Math.abs(rich.cell - rich.logical) < 1, "실제 셀 너비와 지정한 너비 일치"); assert(await page.evaluate(function () { return document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').value === window.autofitDraft; })); console.log("PASS rich text, actual font geometry, preserved draft"); await page.evaluate(function () { document.querySelector('.pj-goal-text[data-row="11"][data-month="1"]').value = "짧음"; }); await fit("m1"); const plain = await widths(); assert(plain.logical < rich.logical, "짧은 문단으로 바꾸면 너비 축소"); const lineRects = await page.evaluate(function () { const editor = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'); const range = document.createRange(); range.selectNodeContents(editor); return Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).map(function (r) { return r.top; }); }); assert.equal(new Set(lineRects).size, 2, "명시적 두 문단은 각각 한 줄로 표시"); await page.evaluate(function () { document.documentElement.classList.add("pj-ui-scale"); }); await fit("m1"); const zoomed = await widths(); assert(Math.abs(zoomed.logical - plain.logical) <= 1, JSON.stringify({ plain, zoomed })); assert(Math.abs(zoomed.cell / zoomed.zoom - zoomed.logical) < 1); console.log("PASS explicit paragraphs, shrink to fit, 75% zoom"); await page.evaluate(function () { document.documentElement.classList.remove("pj-ui-scale"); document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]').value = "길이가 아주 긴 목표 문단 ".repeat(20); }); await fit("m1"); const large = await widths(); assert(large.logical > 600); // 새로고침 때 기존 beforeunload 보호가 수정한 초안을 저장하는 것은 별도 동작이다. assert.deepEqual(writes, [], "자동 맞춤 자체는 쓰기 요청 없음"); await page.reload(); assert.equal((await widths()).logical, large.logical); assert.equal(await page.locator(".pj-goal-autofit-measure").count(), 0); assert.deepEqual(errors, []); console.log("PASS long paragraph beyond 600px, persisted width, no writes/errors"); const mergedPage = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); await mergedPage.addInitScript(function () { document.addEventListener("DOMContentLoaded", function () { const editor = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'); const td = editor.closest("td"); td.colSpan = 2; td.dataset.span = "2"; td.nextElementSibling.remove(); editor.textContent = "병합한 셀에서도 다른 열은 그대로 유지하고 가장 긴 문단에 맞춰 줍니다"; }); }); await mergedPage.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026"); const before = await mergedPage.locator('thead th[data-col="m1"]').evaluate(function (th) { return th.style.getPropertyValue("--cw"); }); await mergedPage.locator('tbody.pj-goal-area [data-row-id="10"] .pj-goal-colresize[data-col="m2"]').dblclick(); const merged = await mergedPage.evaluate(function () { const a = document.querySelector('thead th[data-col="m1"]'), b = document.querySelector('thead th[data-col="m2"]'); const editor = document.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'); const range = document.createRange(); range.selectNodeContents(editor); return { first: a.style.getPropertyValue("--cw"), last: parseFloat(b.style.getPropertyValue("--cw")), actual: editor.closest("td").getBoundingClientRect().width, lines: Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).length }; }); assert.equal(merged.first, before); assert.equal(merged.lines, 1, JSON.stringify(merged)); assert(Math.abs(merged.actual - parseFloat(before) - merged.last) < 1, JSON.stringify(merged)); console.log("PASS merged cell mapping, one unwrapped paragraph, other column unchanged"); await mergedPage.close(); console.log("ALL PASS"); } finally { if (browser) await browser.close(); await new Promise(function (resolve) { server.close(resolve); }); } })().catch(function (e) { console.error(e); process.exitCode = 1; });