feat(project): auto-fit goal column widths

This commit is contained in:
2026-10-03 06:55:00 +09:00
parent e726f986db
commit b32f2ac3a3
12 changed files with 307 additions and 17 deletions
+12
View File
@@ -25,3 +25,15 @@ node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom
```
실제 브라우저 레이아웃·입력기·터치 기기는 아니다(그건 헤드리스 크롬으로 따로 확인).
목표 열 자동 맞춤은 실제 Chromium에서도 검증한다. 로컬 테스트 HTML·프로젝트 CSS/폰트를 사용하며 운영 서버·DB에 연결하지 않는다.
부분 서식과 셀 여백, 명시적 줄바꿈, 75% 배율, 600px를 넘는 긴 문단, 저장된 너비 복원을 확인한다.
```powershell
python tests/js/render_goals.py
# playwright 설치 또는 NODE_PATH로 기존 설치 지정
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
node tests/js/goals_autofit.browser.test.js
```
`PJ_TEST_BROWSER`를 생략하면 Playwright에 설치된 기본 Chromium을 사용한다.
+145
View File
@@ -0,0 +1,145 @@
// 실제 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 html = fs.readFileSync(path.join(__dirname, ".out/goals_admin.html"), "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();
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; });
+86 -1
View File
@@ -115,6 +115,36 @@ function unload(env) {
return e;
}
// jsdom에는 글꼴·레이아웃 엔진이 없다. 숨은 복사본의 실제 DOM/서식을 확인하면서
// 결정적인 글 너비를 제공한다. 실제 CSS·폰트 측정은 별도 브라우저 검증으로 확인한다.
function mockAutoFitLayout(env) {
const realRect = env.w.HTMLElement.prototype.getBoundingClientRect;
const measured = [];
env.w.HTMLElement.prototype.getBoundingClientRect = function () {
if (!this.classList.contains("pj-goal-autofit-measure")) return realRect.call(this);
measured.push(this);
const content = this.querySelector(".pj-goal-text, .pj-goal-text-ro, .pj-goal-num, .pj-goal-area-text, .pj-goal-row-text") || this;
let line = 0, longest = 0;
function walk(node, size, bold) {
if (node.nodeType === 3) {
node.nodeValue.split("\n").forEach(function (text, i) {
if (i) { longest = Math.max(longest, line); line = 0; }
line += text.length * size * (bold ? 1.2 : 1);
});
} else if (node.nodeType === 1) {
if (node.tagName === "BR") { longest = Math.max(longest, line); line = 0; return; }
const nextSize = parseFloat(node.style.fontSize) || size;
const nextBold = node.style.fontWeight ? Number(node.style.fontWeight) >= 600 : bold;
Array.from(node.childNodes).forEach(function (child) { walk(child, nextSize, nextBold); });
}
}
walk(content, 10, false);
const zoom = env.d.documentElement.classList.contains("pj-ui-scale") ? 0.75 : 1;
return { width: (Math.max(longest, line) + 13) * zoom };
};
return measured;
}
// ── 가짜 서버 — 목표 표(글 칸 상태를 기억해 화면 GET 에 반영) ───────────────
function goalsServer(env, st) {
st = Object.assign({ cells: {}, areaAdded: false, cellHook: null, metricHook: null, getHook: null }, st || {});
@@ -580,8 +610,63 @@ function meetServer(env, st) {
env.d.getElementById("pj-goal-area-add").click(); await settle(); await wait(20); await settle();
const fresh = env.d.querySelector('tbody.pj-goal-area .pj-goal-colresize[data-col="m1"]');
check("[너비] 표 새로 그린 뒤에도 손잡이", !!fresh && fresh !== lower);
mockAutoFitLayout(env);
fresh.dispatchEvent(new env.w.MouseEvent("dblclick", { bubbles: true }));
check("[너비] 새 행의 더블클릭 기본값 복원", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "85px");
check("[너비] 표를 다시 그린 뒤에도 더블클릭 내용 맞춤", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "95px");
});
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
goalsServer(env); await boot(env);
const table = env.d.getElementById("pj-goal-table"), measured = mockAutoFitLayout(env);
const first = table.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
const second = table.querySelector('.pj-goal-text[data-row="11"][data-month="1"]');
first.value = "짧은 문단\n다담: 100 백만(김지통)\n주부콩: 20백만(김지통)";
second.value = "pj-rich:v1:" + JSON.stringify([{ text: "가장 긴 문단", size: 32, bold: true }, { text: " 끝" }]);
const draft = second.value, calls = env.calls.length;
function fit(key, body) {
const handle = table.querySelector((body ? "tbody " : "thead ") + '.pj-goal-colresize[data-col="' + key + '"]');
handle.dispatchEvent(new env.w.MouseEvent("dblclick", { bubbles: true, cancelable: true }));
}
function width(key) { return parseFloat(table.querySelector('thead th[data-col="' + key + '"]').style.getPropertyValue("--cw")); }
fit("m1", true);
const wanted = Math.ceil(7 * 32 * 1.2 + 2 * 10 + 13) + 2;
check("[자동 너비] 모든 행 중 가장 긴 문단·큰 글씨·굵기 반영", width("m1") === wanted, [width("m1"), wanted]);
check("[자동 너비] 원본 초안·부분 서식 보존·저장 요청 없음", second.value === draft && env.calls.length === calls);
check("[자동 너비] 복사본만 줄바꿈 해제·메뉴/손잡이 제외·측정 뒤 제거", measured.every(function (cell) {
const editor = cell.querySelector(".pj-goal-text");
return !cell.querySelector(".pj-goal-colresize, .pj-goal-menu-btn") && (!editor || editor.style.whiteSpace === "pre");
}) && !table.querySelector(".pj-goal-autofit-measure"));
second.value = "짧음";
fit("m1");
const paragraphWidth = Math.max.apply(null, first.textContent.split("\n").map(function (line) { return line.length; })) * 10 + 15;
check("[자동 너비] 명시적 줄바꿈 유지·문단 너비로 축소도 가능", width("m1") === paragraphWidth, [width("m1"), paragraphWidth]);
env.d.documentElement.classList.add("pj-ui-scale"); fit("m1");
check("[자동 너비] 75% 화면 배율에서도 같은 논리 너비", width("m1") === paragraphWidth);
env.d.documentElement.classList.remove("pj-ui-scale");
first.value = "긴".repeat(100); fit("m1");
const saved = env.w.localStorage.getItem("pj_goal_col_w");
check("[자동 너비] 600px를 넘는 문단도 잘리지 않고 기억", width("m1") === 1015 && JSON.parse(saved).m1 === 1015);
const restored = makeEnv(PAGE.goals_ro, GOALS_URL, { storage: { pj_goal_col_w: saved } });
goalsServer(restored); await boot(restored);
check("[자동 너비] 다시 열면 큰 자동 너비도 복원", restored.d.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "1015px");
const numeric = table.querySelector('input.pj-goal-num[data-month="2"]');
numeric.value = "12345678901234567890"; fit("m2");
check("[자동 너비] 숫자 입력칸의 현재 초안도 측정", width("m2") === 215);
table.querySelector(".pj-goal-area-text").textContent = "아주 긴 영역 이름"; fit("c1", true);
check("[자동 너비] rowspan 이름 열·메뉴 아이콘 제외", table.style.getPropertyValue("--goal-c1-w") === "115px");
const row = first.closest("tr"), merged = first.closest("td");
merged.colSpan = 2; merged.dataset.goalCols = "m1,m2";
merged.querySelector(".pj-goal-colresize").dataset.col = "m2";
row.querySelector('td[data-month="2"]').remove();
first.value = "병합".repeat(80);
const beforeM1 = width("m1"); fit("m2", true);
check("[자동 너비] 병합 셀은 나머지 열 유지·오른쪽 끝 열만 맞춤", width("m1") === beforeM1 && width("m2") === 1615 - beforeM1, [width("m1"), width("m2")]);
const qth = table.querySelector('thead th[data-col="q1"]'), folded = qth.classList.contains("is-folded");
fit("q1");
check("[자동 너비] 분기 열 더블클릭은 접기 상태를 바꾸지 않음", qth.classList.contains("is-folded") === folded);
mockAutoFitLayout(restored);
restored.d.querySelector('tbody .pj-goal-colresize[data-col="m1"]').dispatchEvent(new restored.w.MouseEvent("dblclick", { bubbles: true }));
check("[자동 너비] 보기 전용도 내용 맞춤 가능·쓰기 요청 없음", restored.d.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "95px" && !restored.calls.some(function (c) { return c.method !== "GET"; }));
});
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════