fix(project): grow cells and repair Enter

This commit is contained in:
2026-10-03 17:04:02 +09:00
parent 090e508bf3
commit d3c1ca12e9
10 changed files with 219 additions and 23 deletions
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003j" />
<link rel="stylesheet" href="/static/project.css?v=20261003k" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -306,7 +306,7 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261003c" defer></script>
<script src="/static/project-meeting-cells.js?v=20261003a" defer></script>
<script src="/static/project.js?v=20261003j" defer></script>
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project-meeting-cells.js?v=20261003b" defer></script>
<script src="/static/project.js?v=20261003k" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/project.css?v=20261003k" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -201,6 +201,6 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261003c" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project.js?v=20261003k" defer></script>
{% endblock %}
@@ -611,6 +611,7 @@
</ol>
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자·평가는 바꾸는 즉시 저장됩니다.</p>
<p>목표·주간 회의록 표에서 입력한 글·숫자·이름이 칸보다 길면 열 너비가 자동으로 늘어납니다. 글 셀에서는 <kbd>Enter</kbd>를 한 번 누르면 바로 다음 줄로 이동합니다. 지운 뒤 너비를 줄이려면 열 너비 자동 맞춤을 사용하세요.</p>
<p>이번주 할 일 셀에서는 목표 표의 셀 편집 도구를 함께 사용할 수 있습니다.</p>
<ul>
<li><b>글자 서식</b> — 글자 일부를 선택하고 위쪽 도구에서 색·크기·굵게·기울임·밑줄을 바꿉니다. 초기화 버튼은 선택한 글자의 서식을 지웁니다.</li>
+66 -15
View File
@@ -30,6 +30,7 @@
function walk(node, inherited) {
if (node.nodeType === 3) { add(node.nodeValue, inherited); return; }
if (node.nodeType !== 1) return;
if (node.hasAttribute("data-pj-caret-line")) return;
if (node.tagName === "BR") { add("\n", inherited); return; }
if (/^(SCRIPT|STYLE|IMG|IFRAME)$/.test(node.tagName)) return;
const style = styles(node, inherited);
@@ -64,27 +65,58 @@
editor.replaceChildren();
runs.forEach(function (r) {
if (typeof r.text !== "string") return;
const span = document.createElement("span");
span.textContent = r.text;
if (typeof r.bold === "boolean") span.style.fontWeight = r.bold ? "700" : "400";
if (typeof r.italic === "boolean") span.style.fontStyle = r.italic ? "italic" : "normal";
if (typeof r.underline === "boolean") span.style.textDecoration = r.underline ? "underline" : "none";
if (/^#[\da-f]{6}$/i.test(r.color || "")) span.style.color = r.color;
if (Number.isInteger(r.size) && r.size >= 10 && r.size <= 32) span.style.fontSize = r.size + "px";
editor.appendChild(span.style.cssText ? span : document.createTextNode(r.text));
editor.appendChild(nodeForRun(r));
});
caretLine(editor);
}
function nodeForRun(r) {
const span = document.createElement("span");
r.text.split("\n").forEach(function (line, i) {
if (i) span.appendChild(document.createElement("br"));
if (line) span.appendChild(document.createTextNode(line));
});
if (typeof r.bold === "boolean") span.style.fontWeight = r.bold ? "700" : "400";
if (typeof r.italic === "boolean") span.style.fontStyle = r.italic ? "italic" : "normal";
if (typeof r.underline === "boolean") span.style.textDecoration = r.underline ? "underline" : "none";
if (/^#[\da-f]{6}$/i.test(r.color || "")) span.style.color = r.color;
if (Number.isInteger(r.size) && r.size >= 10 && r.size <= 32) span.style.fontSize = r.size + "px";
if (!span.style.cssText && r.text.includes("\n")) span.style.lineHeight = "inherit";
return span.style.cssText || r.text.includes("\n") ? span : document.createTextNode(r.text);
}
function caretLine(editor) {
// 마지막 개행 뒤의 빈 줄도 화면에 만들되 저장할 글에는 넣지 않는다.
const runs = readRuns(editor), last = runs[runs.length - 1];
let marker = editor.querySelector("[data-pj-caret-line]");
if (last && last.text.endsWith("\n")) {
if (!marker) {
marker = document.createElement("br"); marker.setAttribute("data-pj-caret-line", "");
const holder = document.createElement("span"); holder.appendChild(marker); editor.appendChild(holder);
}
marker.parentElement.style.fontSize = last.size ? last.size + "px" : "";
marker.parentElement.style.lineHeight = last.size ? "normal" : getComputedStyle(editor).lineHeight;
} else if (marker) {
const holder = marker.parentElement; marker.remove();
if (holder !== editor && !holder.childNodes.length) holder.remove();
}
}
function restore(editor, start, end) {
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
const points = [], range = document.createRange();
let node, offset = 0;
while ((node = walker.nextNode())) {
points.push({ node: node, start: offset, end: offset + node.length }); offset += node.length;
const length = node.nodeType === 3 ? node.length : node.tagName === "BR" && !node.hasAttribute("data-pj-caret-line") ? 1 : 0;
if (length) { points.push({ node: node, start: offset, end: offset + length }); offset += length; }
}
function point(n) { return points.find(function (p) { return n <= p.end; }) || points[points.length - 1]; }
const a = point(start), b = point(end);
if (!a || !b) { range.selectNodeContents(editor); range.collapse(false); }
else { range.setStart(a.node, Math.max(0, start - a.start)); range.setEnd(b.node, Math.max(0, end - b.start)); }
else {
function pointAt(p, n) {
return p.node.nodeType === 3 ? [p.node, Math.max(0, n - p.start)] :
[p.node.parentNode, Array.from(p.node.parentNode.childNodes).indexOf(p.node) + (n > p.start ? 1 : 0)];
}
range.setStart(...pointAt(a, start)); range.setEnd(...pointAt(b, end));
}
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
return range;
}
@@ -98,16 +130,34 @@
if (e.isComposing || e.keyCode === 229) return;
if (e.key === "Enter") { e.preventDefault(); insert(editor, "\n"); }
});
editor.addEventListener("beforeinput", function (e) {
if (!e.isComposing && (e.inputType === "insertParagraph" || e.inputType === "insertLineBreak")) {
e.preventDefault(); insert(editor, "\n");
}
});
editor.addEventListener("input", function (e) { if (!e.isComposing) caretLine(editor); });
editor.addEventListener("compositionend", function () { caretLine(editor); });
editor.addEventListener("paste", function (e) {
e.preventDefault(); insert(editor, e.clipboardData.getData("text/plain"));
});
paint(editor, readRuns(editor));
}
function insert(editor, text) {
if (!text) return;
const sel = window.getSelection();
if (!sel.rangeCount || !editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
const range = sel.getRangeAt(0); range.deleteContents();
const node = document.createTextNode(text); range.insertNode(node);
range.setStartAfter(node); range.collapse(true); sel.removeAllRanges(); sel.addRange(range);
const range = sel.getRangeAt(0), pre = document.createRange();
pre.selectNodeContents(editor); pre.setEnd(range.startContainer, range.startOffset);
const offset = readRuns(pre.cloneContents()).reduce((n, r) => n + r.text.length, 0); let pos = 0, style = {};
for (const run of readRuns(editor)) {
pos += run.text.length;
if (pos >= offset) { STYLE_KEYS.forEach(k => { if (run[k] !== undefined) style[k] = run[k]; }); break; }
}
range.deleteContents();
const node = nodeForRun(Object.assign({ text: text }, style)); range.insertNode(node);
const caret = node.nodeType === 3 ? node : node.lastChild;
if (caret.nodeType === 3) range.setStart(caret, caret.length); else range.setStartAfter(caret);
range.collapse(true); sel.removeAllRanges(); sel.addRange(range);
editor.dispatchEvent(new Event("input", { bubbles: true }));
}
function init(table, toolbar) {
@@ -157,7 +207,8 @@
const editor = root.closest(".pj-goal-text[contenteditable='true']");
if (!editor || !table.contains(editor) || !editor.contains(range.endContainer)) { clear(); return; }
const pre = document.createRange(); pre.selectNodeContents(editor); pre.setEnd(range.startContainer, range.startOffset);
saved = { editor: editor, start: pre.toString().length, end: pre.toString().length + range.toString().length };
const start = readRuns(pre.cloneContents()).reduce((n, r) => n + r.text.length, 0);
saved = { editor: editor, start: start, end: start + readRuns(range.cloneContents()).reduce((n, r) => n + r.text.length, 0) };
toolbar.querySelectorAll("button, input, select").forEach(function (el) { el.disabled = false; });
let pos = 0;
const chosen = readRuns(editor).filter(function (run) {
+23
View File
@@ -106,6 +106,29 @@
{ label: "전체 열 너비 자동 맞춤", icon: opts.icon("width"), onClick: fitAll },
] : [];
}
const growingCells = new Set();
let growFrame = 0;
function queueCellGrowth(e) {
const field = e.target.closest("input, textarea, [contenteditable='true']");
const td = field && field.closest("td, th");
if (!admin || !td || !table.contains(td)) return;
growingCells.add(td);
if (growFrame) return;
growFrame = requestAnimationFrame(function () {
growFrame = 0; let changed = false;
growingCells.forEach(function (cell) {
if (!table.contains(cell)) return;
const keys = (cell.dataset.meetCols || "").split(",").filter(Boolean), key = keys.at(-1);
if (!key) return;
const width = measure(cell) - keys.slice(0, -1).reduce((sum, k) => sum + widths[k], 0);
if (width > widths[key]) { widths[key] = width; changed = true; }
});
growingCells.clear();
if (changed) { applyWidths(); saveWidths(); }
});
}
table.addEventListener("input", queueCellGrowth);
table.addEventListener("compositionend", queueCellGrowth);
table.addEventListener("dblclick", function (e) {
const h = e.target.closest(".pj-meet-colresize");
if (h) { e.preventDefault(); e.stopPropagation(); fit(h.dataset.col); }
+24
View File
@@ -8741,6 +8741,30 @@
{ label: "전체 열 너비 자동 맞춤", icon: menuIcon("view_week"), onClick: autoFitAllCols },
];
}
// 입력한 문단이 칸을 넘으면 해당 열만 늘린다. 명시적 개행·선택·초안은 유지한다.
const growingCells = new Set();
let growFrame = 0;
function queueCellGrowth(e) {
const field = e.target.closest("input, textarea, [contenteditable='true']");
const td = field && field.closest("td, th");
if (!isAdmin || !td || !table.contains(td)) return;
growingCells.add(td);
if (growFrame) return;
growFrame = requestAnimationFrame(function () {
growFrame = 0; let changed = false;
growingCells.forEach(function (cell) {
if (!table.contains(cell)) return;
const keys = (cell.dataset.goalCols || "").split(",").filter(Boolean), key = keys[keys.length - 1];
if (!colDefault[key]) return;
const width = naturalCellWidth(cell) - keys.slice(0, -1).reduce((sum, k) => sum + colW[k], 0);
if (width > colW[key]) { colW[key] = width; changed = true; }
});
growingCells.clear();
if (changed) { applyColW(); saveColW(); fitAll(); stickKpi(); }
});
}
table.addEventListener("input", queueCellGrowth);
table.addEventListener("compositionend", queueCellGrowth);
table.addEventListener("contextmenu", function (e) {
const td = e.target.closest("th, td");
if (!td || !table.contains(td)) return;
+3
View File
@@ -798,6 +798,9 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
- **목표와 같은 셀 편집**: 이번주 할 일은 공용 `PJGoalText` 편집기·글자 서식 도구(`_cell_format.html`)를 사용한다.
글자 일부를 선택해 색·크기(10~32px)·굵게·기울임·밑줄·초기화를 적용하며, `pj-rich:v1:` 형식으로 서식을 함께 저장한다.
지난주 글·보기 전용 화면·인쇄도 허용한 서식만 출력하고, 사용자 글은 HTML escape한다. 글 길이 제한은 보이는 글 4,000자다.
목표·회의록 표에서 글·숫자·이름 입력 중 문단이 현재 칸보다 길면 해당 열 너비만 자동으로 늘리고 브라우저에 기억한다.
병합 칸은 나머지 열을 유지하고 오른쪽 끝 열을 늘린다. 입력 중 지워도 너비는 자동으로 줄이지 않으며, 수동 자동 맞춤으로 줄일 수 있다.
글 셀 Enter는 한 번에 개행하며 마지막 개행 뒤의 빈 줄·커서도 즉시 보인다. 빈 줄 표시용 요소는 저장 데이터에 포함하지 않는다.
`project-meeting-cells.js`는 열 경계 드래그·더블클릭/우클릭 현재·전체 열 자동 맞춤, 브라우저별 너비 기억(`pj_meet_col_w`),
같은 구역 글 셀 범위 선택(드래그·Shift+클릭), 내용 지우기(Del)·되돌리기(Ctrl+Z), 테두리 드래그 내용·서식 이동을 제공한다.
이동은 먼저 초안을 저장하고 원본·대상 예상값을 서버에서 비교한다. 값 변경은 409, 두 칸 변경은 한 트랜잭션으로 처리하며
+2
View File
@@ -34,6 +34,8 @@ node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom
항목명 오른쪽의 `자동입력`·`실적 미사용` 표시가 같은 줄에 들어가는지 검증한다.
실제 마우스로 셀 테두리를 끌어 내용·부분 서식을 이동하고, 지연 응답 동안 원본을 유지하는지 확인한다.
회의록에서는 실제 contenteditable 선택·서식 도구·초안 저장 후 이동·이번주/지난주 열 순서·75% 배율의 너비 맞춤도 확인한다.
목표·회의록의 실제 글·숫자·항목명 입력 시 열 자동 확장(75% 배율·세로 병합 포함), 한 번 Enter의 즉시 빈 줄 표시,
연속 개행·모바일 beforeinput 개행·IME Enter 중복 방지도 검증한다.
우클릭 현재/전체 열 자동 맞춤은 접힌 월 열의 측정·너비 저장도 검증한다. jsdom에서는 저장 실패·409 충돌·덮어쓰기 취소·Esc 취소를 추가로 확인한다.
```powershell
+92
View File
@@ -414,6 +414,98 @@ const server = http.createServer(function (req, res) {
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();
+1 -1
View File
@@ -657,7 +657,7 @@ function meetServer(env, st) {
}) && !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;
const paragraphWidth = Math.max.apply(null, first.value.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);