// 실제 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 fixture = url.searchParams.has("readonly") ? "goals_ro.html" : "goals_admin.html"; const html = fs.readFileSync(path.join(__dirname, ".out", fixture), "utf8") .replace("", '
') .replace("", "
"); res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return; } if (url.pathname === "/project/goals/2026/meetings/9") { const fixture = url.searchParams.has("merged") ? "meeting_merged.html" : url.searchParams.has("readonly") ? "meeting_layout_ro.html" : "meeting_layout_admin.html"; const html = fs.readFileSync(path.join(__dirname, ".out", fixture), "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 }); // 열 너비는 애니메이션하고, 숫자는 최종 위치에서만 표시한다(관리자·보기 전용·75% 배율). for (const readonly of [false, true]) { const folding = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); await folding.addInitScript(() => document.addEventListener("DOMContentLoaded", () => { const row = document.querySelector('tr[data-row-id="10"]'); const cell = row.querySelector('td[data-month="1"]'); cell.colSpan = 2; cell.dataset.span = "2"; cell.classList.add("is-merged"); cell.querySelector("div").textContent = "병합한 목표\n두 번째 줄\n세 번째 줄"; row.querySelector('td[data-month="2"]').remove(); })); await folding.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026" + (readonly ? "?readonly" : "")); await folding.evaluate(() => localStorage.setItem("pj_goal_col_w", JSON.stringify({ m1: 150, m2: 110, m3: 175 }))); await folding.reload(); await folding.evaluate(async () => { await document.fonts.ready; }); for (const zoom of [1, 0.75]) { const result = await folding.evaluate(async zoom => { document.documentElement.style.zoom = zoom; const table = document.getElementById("pj-goal-table"); const q = table.querySelector('thead th[data-col="q1"]'); const cells = Array.from(table.querySelectorAll('.pj-goal-kpi .pj-goal-m[data-h="1"]')); const merged = table.querySelector('tr[data-row-id="10"] td[data-month="1"]'); const mergedHeight = merged.parentElement.getBoundingClientRect().height; const mergedWidth = merged.getBoundingClientRect().width; function snapshot() { return cells.map(c => { const box = c.getBoundingClientRect(); const number = c.querySelector(".pj-goal-num"); const range = document.createRange(); range.selectNodeContents(c); const content = number ? number.getBoundingClientRect() : range.getBoundingClientRect(); return [box.x, box.width, content.x, content.width]; }); } const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); async function frames() { const out = []; let heightStable = true; const started = performance.now(); while (performance.now() - started < 420) { await new Promise(requestAnimationFrame); out.push(cells.map(c => ({ width: c.getBoundingClientRect().width, folding: c.classList.contains("is-folding"), hidden: c.querySelector(".pj-goal-num") ? getComputedStyle(c.querySelector(".pj-goal-num")).opacity === "0" : getComputedStyle(c).color === "rgba(0, 0, 0, 0)" }))); if (merged.classList.contains("is-folding")) { heightStable = heightStable && Math.abs(merged.parentElement.getBoundingClientRect().height - mergedHeight) < 1; } } assertHeightStable = assertHeightStable && heightStable; return out; } let assertHeightStable = true; const before = snapshot(); q.click(); const closing = await frames(); await delay(100); const hiddenAfterClose = cells.every(c => getComputedStyle(c).display === "none"); q.click(); const opening = await frames(); await delay(150); const after = snapshot(); // 여러 분기 동시 전환과 빠른 반전: 마지막 클릭 상태만 남는다. const q2 = table.querySelector('thead th[data-col="q2"]'); q.click(); q2.click(); await delay(70); q.click(); await delay(50); q.click(); await delay(400); const rapidHidden = cells.every(c => getComputedStyle(c).display === "none"); const otherHidden = Array.from(table.querySelectorAll('.pj-goal-m[data-h="2"]')).every(c => getComputedStyle(c).display === "none"); const savedFold = JSON.parse(localStorage.getItem("pj_goal_fold_q"))[1]; q.click(); q2.click(); await delay(500); return { before, after, closing, opening, hiddenAfterClose, rapidHidden, otherHidden, savedFold, mergedStable: assertHeightStable && Math.abs(merged.getBoundingClientRect().width - mergedWidth) < 0.1 && merged.colSpan === 2, clean: !table.querySelector(".is-folding"), widths: ["m1", "m2", "m3"].map(key => table.querySelector('thead th[data-col="' + key + '"]').getBoundingClientRect().width / zoom) }; }, zoom); assert(result.hiddenAfterClose && result.rapidHidden && result.otherHidden && result.savedFold && result.clean && result.mergedStable, JSON.stringify({ hiddenAfterClose: result.hiddenAfterClose, rapidHidden: result.rapidHidden, otherHidden: result.otherHidden, savedFold: result.savedFold, clean: result.clean, mergedStable: result.mergedStable })); for (const frames of [result.closing, result.opening]) { assert(frames.some(frame => frame[0].width > 1 && frame[0].width < result.before[0][1] - 1), "quarter width must visibly animate"); frames.forEach(frame => frame.forEach(cell => assert(!cell.folding || cell.hidden, "moving numeric content must stay hidden"))); } result.after.forEach((cell, i) => cell.forEach((value, j) => { assert(Math.abs(value - result.before[i][j]) < 0.1, "quarter numeric position changed during reveal"); })); result.widths.forEach((width, i) => assert(Math.abs(width - [150, 110, 175][i]) < 1)); } await folding.emulateMedia({ reducedMotion: "reduce" }); const reduced = await folding.evaluate(() => { const table = document.getElementById("pj-goal-table"), q = table.querySelector('thead th[data-col="q1"]'); const cells = Array.from(table.querySelectorAll('.pj-goal-m[data-h="1"]')); q.click(); const hidden = cells.every(c => getComputedStyle(c).display === "none"); q.click(); return hidden && cells.every(c => getComputedStyle(c).display !== "none") && !table.querySelector(".is-folding"); }); assert(reduced, "reduced motion uses immediate toggles"); await folding.close(); } console.log("PASS animated quarter widths with stable numeric reveal, saved widths and concurrent/rapid toggles at 100%/75%"); 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(); for (const readonly of [false, true]) { const heightPage = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); await heightPage.addInitScript(function () { document.addEventListener("DOMContentLoaded", function () { const row = document.querySelector('tr[data-row-id="10"]'); row.querySelector('td[data-month="0"] > div').textContent = "첫 번째 줄\n두 번째 줄\n세 번째 줄"; row.querySelector('td[data-month="1"] > div').textContent = "첫 줄\n둘째 줄"; }); }); await heightPage.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026" + (readonly ? "?readonly=1" : "")); await heightPage.evaluate(function () { // 세 줄은 열 폭에 의해 추가로 접히지 않도록 연간 열만 넓힌다. const h = document.querySelector('thead .pj-goal-colresize[data-col="y"]'); h.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); }); async function rowMetrics() { return heightPage.evaluate(function () { const row = document.querySelector('tr[data-row-id="10"]'); const long = row.querySelector('td[data-month="0"] > div'), short = row.querySelector('td[data-month="1"] > div'); const cell = long.closest("td"), style = getComputedStyle(long), cellStyle = getComputedStyle(cell); const range = document.createRange(); range.selectNodeContents(long); return { row: row.getBoundingClientRect().height, editor: long.getBoundingClientRect().height, paddingTop: parseFloat(style.paddingTop), paddingBottom: parseFloat(style.paddingBottom), border: parseFloat(cellStyle.borderTopWidth) + parseFloat(cellStyle.borderBottomWidth), topDifference: short.getBoundingClientRect().top - long.getBoundingClientRect().top, lines: new Set(Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).map(function (r) { return r.top; })).size, namesCentered: Array.from(row.querySelectorAll("th")).every(function (th) { const name = th.querySelector(".pj-goal-area-text, .pj-goal-row-text"); const box = th.getBoundingClientRect(), text = name.getBoundingClientRect(); return getComputedStyle(th).verticalAlign === "middle" && Math.abs((box.top + box.bottom - text.top - text.bottom) / 2) <= 1; }), oneLineRow: document.querySelector('tr[data-row-id="11"]').getBoundingClientRect().height }; }); } const initial = await rowMetrics(); assert.equal(initial.lines, 3, JSON.stringify(initial)); assert.equal(initial.paddingTop, initial.paddingBottom); assert(Math.abs(initial.row - initial.editor - initial.border) <= 1, JSON.stringify(initial)); assert(Math.abs(initial.topDifference) <= 1, "짧은 셀도 긴 셀과 같은 위치에서 상단 정렬"); assert(initial.namesCentered, "구역·항목 이름은 병합된 셀도 세로 가운데 정렬"); assert(initial.oneLineRow <= 36, "한 줄 셀은 불필요한 빈 줄 없이 내용에 맞는 높이: " + initial.oneLineRow); if (!readonly) { await heightPage.evaluate(function () { const row = document.querySelector('tr[data-row-id="10"]'); const long = row.querySelector('td[data-month="0"] > div'), short = row.querySelector('td[data-month="1"] > div'); long.value = "한 줄"; short.value = "한 줄"; long.dispatchEvent(new Event("input", { bubbles: true })); short.dispatchEvent(new Event("input", { bubbles: true })); }); const smaller = await rowMetrics(); assert(smaller.row < initial.row && smaller.row <= 36, JSON.stringify({ initial, smaller })); await heightPage.evaluate(function () { const editor = document.querySelector('tr[data-row-id="10"] td[data-month="1"] > div'); editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "큰 글씨\n두 줄", size: 32, bold: true }]); editor.dispatchEvent(new Event("input", { bubbles: true })); }); const largeText = await heightPage.evaluate(function () { const editor = document.querySelector('tr[data-row-id="10"] td[data-month="1"] > div'); return { row: editor.closest("tr").getBoundingClientRect().height, editor: editor.getBoundingClientRect().height, clipped: editor.scrollHeight > editor.clientHeight, border: parseFloat(getComputedStyle(editor.closest("td")).borderBottomWidth) }; }); assert(largeText.row > smaller.row && !largeText.clipped); assert(Math.abs(largeText.row - largeText.editor - largeText.border) <= 1, JSON.stringify(largeText)); } console.log("PASS content row height, symmetric padding, top alignment" + (readonly ? " (read-only)" : ", shrink and large font")); await heightPage.close(); } for (const readonly of [false, true]) { const meetingPage = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); await meetingPage.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9" + (readonly ? "?readonly=1" : "")); await meetingPage.evaluate(() => document.fonts.ready); async function meetingMetrics() { return meetingPage.evaluate(function () { const row = document.querySelector('tr[data-item="2"]'); const long = row.querySelector(".pj-meet-c-text:not(.is-prev) > *"), short = row.querySelector(".pj-meet-c-text.is-prev > *"); const cell = long.closest("td"), style = getComputedStyle(long), cs = getComputedStyle(cell); const zoom = document.documentElement.classList.contains("pj-ui-scale") ? 0.75 : 1; const labels = Array.from(document.querySelectorAll(".pj-meet-market")).map(function (badge) { const name = badge.previousElementSibling, br = badge.getBoundingClientRect(), nr = name.getBoundingClientRect(); return { text: badge.textContent, rightOfName: br.left >= nr.right, sameLine: br.top < nr.bottom && nr.top < br.bottom, fits: br.right <= badge.closest("th").getBoundingClientRect().right }; }); return { row: row.getBoundingClientRect().height / zoom, long: long.getBoundingClientRect().height / zoom, short: short.getBoundingClientRect().height / zoom, line: parseFloat(style.lineHeight), top: parseFloat(style.paddingTop), bottom: parseFloat(style.paddingBottom), border: parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth), topDifference: (short.getBoundingClientRect().top - long.getBoundingClientRect().top) / zoom, oneLine: document.querySelector('tr[data-item="4"]').getBoundingClientRect().height / zoom, noSlot: !document.querySelector(".pj-meet-week-slot"), cellsAtTop: Array.from(row.querySelectorAll("td")).every(c => getComputedStyle(c).verticalAlign === "top"), namesCentered: Array.from(document.querySelectorAll(".pj-meet-sec th")).every(th => { const box = th.getBoundingClientRect(), line = th.querySelector(".pj-meet-label-line"); let text; if (line) text = line.getBoundingClientRect(); else { const node = th.firstChild, start = node.textContent.search(/\S/); const range = document.createRange(); range.setStart(node, start); range.setEnd(node, start + node.textContent.trim().length); text = range.getBoundingClientRect(); } return getComputedStyle(th).verticalAlign === "middle" && Math.abs((box.top + box.bottom - text.top - text.bottom) / 2) / zoom <= 2; }), labels, clipped: long.scrollHeight > long.clientHeight }; }); } function checkMeeting(m, lines) { assert.equal(m.top, m.bottom, JSON.stringify(m)); assert(Math.abs(m.long - (m.line * lines + m.top + m.bottom)) <= 1, JSON.stringify(m)); assert(Math.abs(m.row - m.long - m.border) <= 1, JSON.stringify(m)); assert(Math.abs(m.topDifference) <= 1 && m.cellsAtTop && !m.clipped, JSON.stringify(m)); assert(m.namesCentered, "meeting section and item names must stay vertically centered"); assert(m.oneLine <= m.line + m.top + m.bottom + m.border + 1 && m.noSlot, JSON.stringify(m)); assert.deepEqual(m.labels, [], "shop link badges (자동입력·실적 미사용) were removed 2026-10-06"); } const initial = await meetingMetrics(); checkMeeting(initial, 3); assert(Math.abs(initial.short - initial.line * 2 - initial.top - initial.bottom) <= 1, JSON.stringify(initial)); if (!readonly) { await meetingPage.locator('tr[data-item="2"] .pj-meet-text').fill("한 줄"); await meetingPage.locator('tr[data-item="2"] .is-prev .pj-meet-ro').evaluate(e => { e.textContent = "한 줄"; }); const smaller = await meetingMetrics(); checkMeeting(smaller, 1); assert(smaller.row < initial.row); await meetingPage.locator('tr[data-item="2"] .pj-meet-text').fill("첫 번째 줄\n두 번째 줄\n세 번째 줄"); } await meetingPage.evaluate(function () { document.documentElement.classList.add("pj-ui-scale"); window.dispatchEvent(new Event("resize")); }); checkMeeting(await meetingMetrics(), 3); await meetingPage.locator("#pj-meet-order").click(); checkMeeting(await meetingMetrics(), 3); await meetingPage.locator("#pj-meet-table").screenshot({ path: path.join(__dirname, ".out", readonly ? "meeting-layout-ro.png" : "meeting-layout-admin.png") }); await meetingPage.close(); console.log("PASS meeting row height, equal padding, top alignment, inline automatic/unused labels, shrink and 75% zoom" + (readonly ? " (read-only)" : "")); } const meetingEditing = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); let releaseMeetingMove, meetingMoveStarted; const meetingMoveGate = new Promise(resolve => { releaseMeetingMove = resolve; }); const meetingMoveStart = new Promise(resolve => { meetingMoveStarted = resolve; }); const meetingWrites = [], meetingErrors = []; meetingEditing.on("pageerror", e => meetingErrors.push(e.message)); await meetingEditing.route("**/project/api/**", async function (route) { const req = route.request(); if (req.method() !== "GET") meetingWrites.push({ url: req.url(), body: req.postDataJSON() }); if (req.url().endsWith("/meeting-cells/move")) { meetingMoveStarted(); await meetingMoveGate; await route.fulfill({ json: { ok: true, body: req.postDataJSON().source_body } }); } else await route.fulfill({ json: { ok: true } }); }); await meetingEditing.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9"); const meetingSource = meetingEditing.locator('tr[data-item="2"] .pj-meet-text'); const meetingTarget = meetingEditing.locator('tr[data-item="3"] .pj-meet-text'); await meetingSource.fill("앞 선택 뒤"); await meetingSource.evaluate(function (e) { const r = document.createRange(); r.setStart(e.firstChild, 2); r.setEnd(e.firstChild, 4); window.getSelection().removeAllRanges(); window.getSelection().addRange(r); e.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); }); for (const name of ["굵게", "기울임", "밑줄", "글자 크기 2px 키우기"]) await meetingEditing.getByRole("button", { name: name, exact: true }).click(); await meetingEditing.getByRole("button", { name: "글자 색상", exact: true }).click(); await meetingEditing.getByRole("button", { name: "#DC2626", exact: true }).click(); const meetingRich = await meetingSource.evaluate(e => e.value); const selectedRun = JSON.parse(meetingRich.slice(11))[1]; assert(selectedRun.bold && selectedRun.italic && selectedRun.underline && selectedRun.color === "#dc2626" && selectedRun.size === 16); await meetingSource.click(); const meetingEdge = await meetingSource.locator("..").locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox(); const meetingDest = await meetingTarget.locator("..").boundingBox(); await meetingEditing.mouse.move(meetingEdge.x + meetingEdge.width / 2, meetingEdge.y + meetingEdge.height / 2); await meetingEditing.mouse.down(); await meetingEditing.mouse.move(meetingDest.x + meetingDest.width / 2, meetingDest.y + meetingDest.height / 2, { steps: 5 }); assert(await meetingTarget.locator("..").evaluate(td => td.classList.contains("is-goal-move-target"))); await meetingEditing.mouse.up(); await Promise.race([meetingMoveStart, new Promise((resolve, reject) => setTimeout(() => reject(new Error("meeting move request did not start")), 3000))]); assert.equal(await meetingSource.evaluate(e => e.value), meetingRich); releaseMeetingMove(); await meetingEditing.waitForFunction(() => document.querySelector('tr[data-item="2"] .pj-meet-text').value === ""); assert.equal(await meetingTarget.evaluate(e => e.value), meetingRich); assert(meetingWrites.findIndex(r => r.url.endsWith("/meeting-items/2")) < meetingWrites.findIndex(r => r.url.endsWith("/meeting-cells/move"))); await meetingTarget.evaluate(e => { e.value = "명시적 줄바꿈\n너비 자동 맞춤은 이 문단 전체에 맞춥니다"; e.dispatchEvent(new Event("input", { bubbles: true })); }); await meetingTarget.locator("..").locator(".pj-meet-colresize").dblclick(); const fittedMeeting = await meetingEditing.locator('col[data-meet-col="content"]').evaluate(c => parseFloat(c.style.width)); assert(fittedMeeting > 200); await meetingEditing.locator("#pj-meet-order").click(); await meetingEditing.waitForFunction(() => document.getElementById("pj-meet-table").classList.contains("is-prev-first")); assert.equal(await meetingTarget.locator("..").getAttribute("data-meet-cols"), "content"); await meetingEditing.evaluate(() => { document.documentElement.classList.add("pj-ui-scale"); window.dispatchEvent(new Event("resize")); }); await meetingTarget.locator("..").locator(".pj-meet-colresize").dblclick(); const zoomedMeeting = await meetingEditing.locator('col[data-meet-col="content"]').evaluate(c => parseFloat(c.style.width)); assert(Math.abs(fittedMeeting - zoomedMeeting) <= 1, JSON.stringify({ fittedMeeting, zoomedMeeting })); await meetingTarget.click({ button: "right" }); await meetingEditing.getByRole("menuitem", { name: "전체 열 너비 자동 맞춤" }).click(); assert(await meetingEditing.evaluate(() => Object.keys(JSON.parse(localStorage.getItem("pj_meet_col_w"))).length === 8)); assert.deepEqual(meetingErrors, []); await meetingEditing.locator("#pj-meet-table").screenshot({ path: path.join(__dirname, ".out", "meeting-cell-editing.png") }); await meetingEditing.close(); console.log("PASS actual meeting formatting, border move, draft save ordering, width fitting, review order and 75% zoom"); const mergedMeeting = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); const mergedErrors = []; mergedMeeting.on("pageerror", e => mergedErrors.push(e.message)); await mergedMeeting.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9?merged"); const mergedCell = mergedMeeting.locator('td[data-meet-item="2"]'); assert.equal(await mergedCell.getAttribute("rowspan"), "2"); assert.equal(await mergedMeeting.locator('td[data-meet-item="3"]').count(), 0); for (const order of [false, true]) { if (order) await mergedMeeting.locator("#pj-meet-order").click(); await mergedMeeting.waitForFunction(() => document.querySelector('tr[data-item="3"] td.pj-meet-c-amt').dataset.meetCols === "target"); const geometry = await mergedMeeting.evaluate(() => { const rect = el => el.getBoundingClientRect(); const a = rect(document.querySelector('td[data-meet-item="2"]')); const b = rect(document.querySelector('tr[data-item="3"] td.pj-meet-c-amt')); const t = rect(document.querySelector('tr[data-item="2"] td.pj-meet-c-amt')); return { sameColumn: Math.abs(b.left - t.left) < 1, sameBottom: Math.abs(a.bottom - b.bottom) < 1, disjoint: a.right <= b.left + 1 }; }); assert(geometry.sameColumn && geometry.sameBottom && geometry.disjoint, JSON.stringify(geometry)); await mergedCell.locator(".pj-meet-colresize").dblclick(); } assert.deepEqual(mergedErrors, []); await mergedMeeting.close(); console.log("PASS merged meeting rowspan, independent numeric cells and both column orders"); const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); await interactive.route("**/project/api/**", function (route) { return route.fulfill({ json: { ok: true } }); }); await interactive.addInitScript(function () { localStorage.setItem("pj_goal_col_w", JSON.stringify({ y: 240, m1: 240, m2: 240 })); }); await interactive.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026"); const sourceCell = interactive.locator('tr[data-row-id="10"] td[data-month="1"]'); const targetCell = interactive.locator('tr[data-row-id="11"] td[data-month="2"]'); // 연간 목표 셀 끌어서 이동은 2026-10-07 요청으로 없앴다 — 이동 테두리가 없어야 한다 await sourceCell.locator(".pj-goal-text").click(); assert.equal(await interactive.locator("#pj-goal-table .pj-goal-move-edge").count(), 0); await targetCell.locator(".pj-goal-text").evaluate(function (editor) { editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "드래그 이동", bold: true, italic: true, underline: true, size: 24, color: "#ff0000" }]); }); console.log("PASS goal cells have no drag-move borders"); await targetCell.click({ button: "right" }); await interactive.getByRole("menuitem", { name: "현재 열 너비 자동 맞춤" }).click(); const oneWidth = await interactive.locator('thead th[data-col="m2"]').evaluate(function (th) { return parseFloat(th.style.getPropertyValue("--cw")); }); assert(oneWidth < 240 && oneWidth > 100); await interactive.evaluate(function () { // 접힌 열도 전체 너비 계산에 포함한다. const editor = document.querySelector('.pj-goal-text[data-row="20"][data-month="4"]'); editor.value = "접힌 열도 길이가 아주 긴 문단을 반영합니다"; document.querySelector('thead th[data-col="q2"]').click(); }); await interactive.waitForTimeout(400); await targetCell.click({ button: "right" }); await interactive.getByRole("menuitem", { name: "전체 열 너비 자동 맞춤" }).click(); const all = await interactive.evaluate(function () { const head = document.querySelector('thead th[data-col="m4"]'); return { width: parseFloat(head.style.getPropertyValue("--cw")), folded: head.classList.contains("is-gone"), saved: JSON.parse(localStorage.getItem("pj_goal_col_w")).m4 }; }); assert(all.folded && all.width > 200 && all.saved === all.width, JSON.stringify(all)); console.log("PASS context menu single/all column fitting including collapsed columns"); await interactive.close(); for (const meeting of [false, true]) { const typing = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); const typingErrors = []; typing.on("pageerror", e => typingErrors.push(e.message)); const url = "/project/goals/2026" + (meeting ? "/meetings/9" : ""); await typing.goto("http://127.0.0.1:" + server.address().port + url); const editor = typing.locator(meeting ? 'tr[data-item="2"] .pj-meet-text' : '.pj-goal-text[data-row="10"][data-month="1"]'); const width = () => editor.locator("..").evaluate(td => td.getBoundingClientRect().width); const originalWidth = await width(); const paragraph = "입력한 문단이 길어지면 이 셀의 열 너비가 자동으로 늘어납니다 ".repeat(4); await editor.fill(paragraph); await typing.waitForFunction(([selector, before]) => document.querySelector(selector).parentElement.getBoundingClientRect().width > before + 100, [meeting ? 'tr[data-item="2"] .pj-meet-text' : '.pj-goal-text[data-row="10"][data-month="1"]', originalWidth]); assert((await width()) > 600, "typing may grow past the manual drag limit"); assert.equal(await editor.evaluate(e => e.value), paragraph); const grown = await width(); await editor.fill("첫 줄"); await typing.waitForTimeout(40); assert.equal(await width(), grown, "deleting text does not shrink the user's column"); await editor.press("End"); const before = await editor.evaluate(e => ({ height: e.getBoundingClientRect().height, line: parseFloat(getComputedStyle(e).lineHeight) })); await editor.press("Enter"); const after = await editor.evaluate(e => ({ height: e.getBoundingClientRect().height, value: e.value, caret: window.getSelection().isCollapsed })); assert.equal(after.value, "첫 줄\n"); assert(after.height >= before.height + before.line - 1, JSON.stringify({ before, after })); assert(after.caret); await editor.press("End"); await editor.press("Backspace"); assert.equal(await editor.evaluate(e => e.value), "첫 줄", "one Backspace removes the final newline after End"); await editor.press("Enter"); await typing.keyboard.insertText("둘째 줄"); assert.equal(await editor.evaluate(e => e.value), "첫 줄\n둘째 줄"); await editor.press("Enter"); await editor.press("Enter"); await typing.keyboard.insertText("넷째 줄"); assert.equal(await editor.evaluate(e => e.value), "첫 줄\n둘째 줄\n\n넷째 줄"); await editor.evaluate(e => { const event = new InputEvent("beforeinput", { inputType: "insertParagraph", bubbles: true, cancelable: true }); e.dispatchEvent(event); }); assert.equal(await editor.evaluate(e => e.value), "첫 줄\n둘째 줄\n\n넷째 줄\n"); await typing.keyboard.insertText("모바일 개행"); await editor.evaluate(e => e.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true }))); assert((await editor.evaluate(e => e.value)).endsWith("모바일 개행"), "IME confirmation does not insert an extra newline"); await typing.evaluate(() => document.documentElement.classList.add("pj-ui-scale")); const zoomedWidth = await width(); await editor.fill(paragraph.repeat(2)); await typing.waitForTimeout(60); assert((await width()) > zoomedWidth * 1.5, "live growth uses logical widths at 75% zoom"); assert.equal(await editor.evaluate(e => e.value), paragraph.repeat(2)); await editor.evaluate(e => { e.value = "pj-rich:v1:" + JSON.stringify([{ text: "큰 글씨", size: 32, bold: true }]); }); await editor.press("End"); const bigBefore = await editor.evaluate(e => e.getBoundingClientRect().height); await editor.press("Enter"); const bigAfter = await editor.evaluate(e => ({ height: e.getBoundingClientRect().height, text: window.PJGoalText.readRuns(e).map(r => r.text).join("") })); assert.equal(bigAfter.text, "큰 글씨\n"); assert(bigAfter.height > bigBefore + 20, "large styled Enter shows an unclipped new line at 75% zoom " + JSON.stringify({ bigBefore, bigAfter })); await typing.keyboard.insertText("다음 줄"); assert.equal(await editor.evaluate(e => window.PJGoalText.readRuns(e).map(r => r.text).join("")), "큰 글씨\n다음 줄"); await editor.evaluate(e => { const walker = document.createTreeWalker(e, NodeFilter.SHOW_TEXT); let text; while ((text = walker.nextNode())) { if (text.textContent.includes("다음 줄")) { const r = document.createRange(); r.setStart(text, 0); r.setEnd(text, 2); const s = window.getSelection(); s.removeAllRanges(); s.addRange(r); break; } } e.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); }); await typing.getByRole("button", { name: "기울임", exact: true }).click(); const multilineRuns = await editor.evaluate(e => window.PJGoalText.readRuns(e)); assert.equal(multilineRuns.map(r => r.text).join(""), "큰 글씨\n다음 줄"); assert(multilineRuns.some(r => r.text === "다음" && r.italic), "formatting respects newlines when calculating selection offsets"); assert(!multilineRuns[0].italic, "the first paragraph is not formatted by selecting the second"); const numeric = typing.locator(meeting ? 'tr[data-item="2"] .pj-meet-amount[data-field="target_amount"]' : 'input.pj-goal-num[data-month="2"]').first(); const beforeNumber = await numeric.locator("..").evaluate(td => td.getBoundingClientRect().width); await numeric.fill("123,456,789,012,345,678,901,234,567,890"); await typing.waitForTimeout(60); assert(await numeric.locator("..").evaluate((td, old) => td.getBoundingClientRect().width > old, beforeNumber), "numeric cells grow while editing"); const name = typing.locator(meeting ? 'tr[data-item="2"] .pj-meet-label' : 'tr[data-row-id="10"] .pj-goal-row-text'); await name.click(); const beforeName = await name.locator("..").evaluate(td => td.getBoundingClientRect().width); await name.fill("항목 이름도 입력 길이에 맞게 자동으로 넓어집니다"); await typing.waitForTimeout(60); assert(await name.locator("..").evaluate((td, old) => td.getBoundingClientRect().width > old, beforeName)); assert.deepEqual(typingErrors, []); await typing.close(); console.log("PASS " + (meeting ? "meeting" : "goals") + " live text/numeric/name growth, single Enter blank line, repeated Enter, mobile input and IME"); } const mergedTyping = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); await mergedTyping.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9?merged"); const mergedEditor = mergedTyping.locator('td[data-meet-item="2"] .pj-meet-text'); const otherWidth = await mergedTyping.locator('col[data-meet-col="target"]').evaluate(c => c.style.width); await mergedEditor.fill("세로 병합한 칸의 내용도 길이에 따라 열 너비를 늘립니다 ".repeat(5)); await mergedTyping.waitForTimeout(60); assert((await mergedEditor.locator("..").boundingBox()).width > 600); assert.equal(await mergedEditor.locator("..").getAttribute("rowspan"), "2"); assert.equal(await mergedTyping.locator('col[data-meet-col="target"]').evaluate(c => c.style.width), otherWidth); await mergedTyping.close(); console.log("PASS merged meeting live growth preserves rowspan and independent amount widths"); 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; });