274 lines
18 KiB
JavaScript
274 lines
18 KiB
JavaScript
// 실제 Chromium + 프로젝트 CSS/폰트로 열 자동 너비를 검증한다(운영 서버·DB 미사용).
|
|
// python tests/js/render_goals.py
|
|
// NODE_PATH=<playwright가 있는 node_modules> node tests/js/goals_autofit.browser.test.js
|
|
// 설치된 Chrome 사용 시 PJ_TEST_BROWSER=<chrome 실행 파일 경로> 지정.
|
|
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("<body>", '<body style="font-family:var(--pj-font)"><div class="erp-app">')
|
|
.replace("</body>", "</div></body>");
|
|
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();
|
|
|
|
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,
|
|
namesAtTop: Array.from(row.querySelectorAll("th")).every(function (th) { return getComputedStyle(th).verticalAlign === "top"; }),
|
|
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.namesAtTop, "구역·항목 이름도 상단 정렬");
|
|
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();
|
|
}
|
|
const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
|
let releaseMove, startedMove;
|
|
const moveGate = new Promise(function (resolve) { releaseMove = resolve; });
|
|
const moveStarted = new Promise(function (resolve) { startedMove = resolve; });
|
|
const moveRequests = [];
|
|
await interactive.route("**/project/api/**", async function (route) {
|
|
const request = route.request();
|
|
if (request.url().endsWith("/goals/cells/move")) {
|
|
const payload = request.postDataJSON(); moveRequests.push(payload); startedMove();
|
|
await moveGate;
|
|
await route.fulfill({ json: { ok: true, body: payload.body } });
|
|
} else await 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"]');
|
|
await sourceCell.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" }]);
|
|
});
|
|
await sourceCell.locator(".pj-goal-text").click();
|
|
const edge = await sourceCell.locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox();
|
|
const dest = await targetCell.boundingBox();
|
|
await interactive.mouse.move(edge.x + edge.width / 2, edge.y + edge.height / 2);
|
|
await interactive.mouse.down();
|
|
await interactive.mouse.move(dest.x + dest.width / 2, dest.y + dest.height / 2, { steps: 6 });
|
|
assert(await targetCell.evaluate(function (td) { return td.classList.contains("is-goal-move-target"); }));
|
|
await interactive.mouse.up(); await moveStarted;
|
|
assert.equal(moveRequests.length, 1);
|
|
assert.equal(await sourceCell.locator(".pj-goal-text").textContent(), "드래그 이동");
|
|
assert.equal(await targetCell.locator(".pj-goal-text").textContent(), "");
|
|
releaseMove();
|
|
await interactive.waitForFunction(function () {
|
|
return document.querySelector('tr[data-row-id="10"] .pj-goal-text[data-month="1"]').textContent === "";
|
|
});
|
|
const moved = await targetCell.locator(".pj-goal-text").evaluate(function (editor) { return JSON.parse(editor.value.slice(11))[0]; });
|
|
assert.equal(moved.text, "드래그 이동"); assert.equal(moved.color, "#ff0000"); assert.equal(moved.size, 24);
|
|
assert(moved.bold && moved.italic && moved.underline);
|
|
assert.deepEqual(await targetCell.evaluate(function (td) { return [td.colSpan, td.rowSpan]; }), [1, 1]);
|
|
console.log("PASS actual mouse border drag, delayed atomic response, all text formats, unchanged cell geometry");
|
|
|
|
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();
|
|
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; });
|