/* 주간 회의록 셀 편집. 글자 서식은 목표와 같은 PJGoalText/자동 저장을 사용한다. */ (function () { "use strict"; function init(opts) { const table = opts.table, pane = opts.pane, admin = opts.admin; const KEY = "pj_meet_col_w", widths = {}, defaults = {}; const cols = Array.from(table.querySelectorAll("colgroup col")); let saver = null, selected = [], anchor = null, rangeDrag = null, moveDrag = null; let busy = false, undo = null, suppressClick = 0; const editableCell = n => { const td = n && n.closest && n.closest("td[data-meet-item]"); return td && table.contains(td) && td.querySelector(".pj-meet-text") ? td : null; }; const editorOf = td => td.querySelector(".pj-meet-text"); const keyOf = td => (td.dataset.meetCols || "").split(",").filter(Boolean).at(-1); const minWidth = key => key === "section" ? 48 : key === "label" ? 96 : 40; cols.forEach(function (col) { const key = col.dataset.meetCol; defaults[key] = Math.max(minWidth(key), Math.round(col.getBoundingClientRect().width / opts.zoom()) || 160); widths[key] = defaults[key]; }); try { const saved = JSON.parse(localStorage.getItem(KEY) || "{}"); Object.keys(widths).forEach(k => { if (Number.isFinite(saved[k]) && saved[k] > 0) widths[k] = Math.max(minWidth(k), saved[k]); }); } catch (_) {} function applyWidths() { cols.forEach(col => { col.style.width = widths[col.dataset.meetCol] + "px"; }); table.style.width = cols.reduce((sum, col) => sum + widths[col.dataset.meetCol], 0) + "px"; table.style.minWidth = table.style.width; } function saveWidths() { try { localStorage.setItem(KEY, JSON.stringify(widths)); } catch (_) {} } function handles() { const keys = Array.from(table.querySelectorAll("colgroup col")).map(col => col.dataset.meetCol), occupied = []; Array.from(table.rows).forEach(function (tr, r) { occupied[r] = occupied[r] || []; let c = 0; Array.from(tr.cells).forEach(function (td) { while (occupied[r][c]) c++; const end = c + td.colSpan - 1; for (let rr = r; rr < r + td.rowSpan; rr++) { occupied[rr] = occupied[rr] || []; for (let cc = c; cc <= end; cc++) occupied[rr][cc] = true; } td.dataset.meetCols = keys.slice(c, end + 1).join(","); const handle = td.querySelector(".pj-meet-colresize") || document.createElement("span"); handle.className = "pj-meet-colresize"; handle.dataset.col = keys[end]; handle.title = "끌어서 너비 조절 · 더블클릭하면 내용에 맞춤"; if (!handle.parentNode) td.appendChild(handle); if (admin && editableCell(td)) ["top", "bottom", "left"].forEach(function (edge) { if (td.querySelector('.pj-goal-move-edge[data-edge="' + edge + '"]')) return; const h = document.createElement("span"); h.className = "pj-goal-move-edge"; h.dataset.edge = edge; h.title = "테두리를 끌어 내용과 서식 이동"; td.appendChild(h); }); c = end + 1; }); }); } handles(); applyWidths(); let widthTouched = false; // 사람이 너비를 바꾸면 늦은 자동 맞춤(글꼴 로딩 뒤)이 덮지 않게 const orderButton = document.getElementById("pj-meet-order"); if (orderButton) new MutationObserver(handles).observe(table, { attributes: true, attributeFilter: ["class"] }); function measure(td) { const probe = document.createElement("div"), copy = td.cloneNode(true); const t = table.cloneNode(false), section = td.parentElement.parentElement.cloneNode(false), row = td.parentElement.cloneNode(false); probe.style.cssText = "position:fixed;visibility:hidden;pointer-events:none;width:max-content;left:0;top:0"; probe.setAttribute("aria-hidden", "true"); t.style.cssText = "width:max-content;table-layout:auto"; copy.querySelectorAll(".pj-meet-colresize,.pj-goal-move-edge,.pj-meet-more,.pj-meet-sec-add").forEach(n => n.remove()); copy.querySelectorAll("input,textarea,select").forEach(function (n) { const text = document.createElement("span"); text.textContent = n.value; n.replaceWith(text); }); [t, section, row, copy].concat(Array.from(copy.querySelectorAll("*"))).forEach(function (n) { n.removeAttribute("id"); n.removeAttribute("contenteditable"); n.removeAttribute("data-placeholder"); const styles = { position: "static", width: "max-content", "min-width": "0", "max-width": "none", height: "auto", overflow: "visible", "white-space": "pre", "overflow-wrap": "normal", "word-break": "normal" }; Object.keys(styles).forEach(k => n.style.setProperty(k, styles[k], "important")); }); copy.style.display = "block"; row.appendChild(copy); section.appendChild(row); t.appendChild(section); probe.appendChild(t); pane.appendChild(probe); try { return Math.ceil(copy.getBoundingClientRect().width / opts.zoom()) + 2; } finally { probe.remove(); } } function fit(key) { widthTouched = true; let width = minWidth(key); table.querySelectorAll("[data-meet-cols]").forEach(function (td) { const keys = td.dataset.meetCols.split(","); if (!keys.includes(key)) return; width = Math.max(width, measure(td) - keys.reduce((s, k) => s + (k === key ? 0 : widths[k]), 0)); }); widths[key] = width; applyWidths(); saveWidths(); } function fitAll() { const cells = Array.from(table.querySelectorAll("[data-meet-cols]")).map(td => ({ keys: td.dataset.meetCols.split(","), width: measure(td) })); Object.keys(widths).forEach(k => { widths[k] = minWidth(k); }); cells.filter(c => c.keys.length === 1).forEach(c => { widths[c.keys[0]] = Math.max(widths[c.keys[0]], c.width); }); cells.filter(c => c.keys.length > 1).forEach(function (c) { const last = c.keys.at(-1), rest = c.keys.slice(0, -1).reduce((s, k) => s + widths[k], 0); widths[last] = Math.max(widths[last], c.width - rest); }); applyWidths(); saveWidths(); } // 회의록을 열 때는 늘 전체 열 너비 자동 맞춤으로 시작한다(2026-10-07 요청 — 예전 저장 너비보다 우선). // 글꼴이 늦게 로드되면 글자 폭이 바뀌므로, 그 사이 사람이 너비를 바꾸지 않았으면 한 번 더 맞춘다. fitAll(); if (document.fonts && document.fonts.status !== "loaded") { document.fonts.ready.then(function () { if (!widthTouched && table.isConnected) fitAll(); }); } function widthItems(td) { const key = keyOf(td); return key ? [ { label: "현재 열 너비 자동 맞춤", icon: opts.icon("fit_width"), onClick: () => fit(key) }, { 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); } }); table.addEventListener("mousedown", function (e) { const h = e.target.closest(".pj-meet-colresize"); if (!h || e.button !== 0) return; e.preventDefault(); e.stopPropagation(); const key = h.dataset.col, x = e.clientX, before = widths[key]; widthTouched = true; function move(ev) { widths[key] = Math.max(minWidth(key), Math.min(600, before + (ev.clientX - x) / opts.zoom())); applyWidths(); } function stop() { document.removeEventListener("mousemove", move); document.removeEventListener("mouseup", stop); window.removeEventListener("blur", stop); saveWidths(); } document.addEventListener("mousemove", move); document.addEventListener("mouseup", stop); window.addEventListener("blur", stop); }); function paintSelection() { table.querySelectorAll(".is-merge-sel,.is-goal-active").forEach(td => td.classList.remove("is-merge-sel", "is-goal-active")); selected.forEach(td => td.classList.add("is-merge-sel")); if (selected.length === 1) selected[0].classList.add("is-goal-active"); } function select(a, b) { if (!a || !b || a.closest("tbody") !== b.closest("tbody")) return; const rows = Array.from(a.closest("tbody").rows); const cells = Array.from(a.closest("tbody").querySelectorAll("td[data-meet-item]")); let start = Math.min(rows.indexOf(a.parentElement), rows.indexOf(b.parentElement)); let end = Math.max(rows.indexOf(a.parentElement) + a.rowSpan - 1, rows.indexOf(b.parentElement) + b.rowSpan - 1); cells.forEach(function (td) { const i = rows.indexOf(td.parentElement); if (i <= end && i + td.rowSpan - 1 >= start) { start = Math.min(start, i); end = Math.max(end, i + td.rowSpan - 1); } }); selected = cells.filter(td => { const i = rows.indexOf(td.parentElement); return i <= end && i + td.rowSpan - 1 >= start; }); paintSelection(); } function clearSelection() { selected = []; paintSelection(); } async function locked(fields, work) { if (busy || !saver) return; busy = true; const attrs = fields.map(e => e.getAttribute("contenteditable")); fields.forEach(e => { e.setAttribute("contenteditable", "false"); e.closest("td").classList.add("is-goal-move-saving"); }); try { await saver.flush(); return await work(); } catch (err) { opts.toast("셀 편집 실패: " + err.message + " — 입력 내용은 화면에 유지됩니다.", "error"); } finally { fields.forEach((e, i) => { e.setAttribute("contenteditable", attrs[i]); e.closest("td").classList.remove("is-goal-move-saving"); }); busy = false; } } function moveCell(a, b) { if (a === b) return; const source = editorOf(a), target = editorOf(b); return locked([source, target], async function () { const sourceBody = source.value, targetBody = target.value; if (!sourceBody) return; if (targetBody && !await opts.confirm("대상 셀의 내용을 덮어쓸까요? 내용과 서식이 함께 이동합니다.", { okText: "덮어쓰기", cancelText: "취소" })) return; const result = await opts.api("POST", "/project/api/goals/meeting-cells/move", { source_item: a.dataset.meetItem, target_item: b.dataset.meetItem, source_body: sourceBody, target_body: targetBody, }); saver.replace(source, ""); saver.replace(target, result.body); clearSelection(); select(b, b); opts.toast("내용과 서식을 이동했습니다."); }); } function clearCells(cells) { const fields = cells.map(editorOf).filter(e => e && e.value); return locked(fields, async function () { undo = fields.map(e => [e, e.value]); fields.forEach(e => { e.value = ""; }); await Promise.all(fields.map(e => saver.save(e))); opts.toast("내용을 지웠습니다 — Ctrl+Z로 되돌리기"); }); } function undoClear() { const previous = (undo || []).filter(([e]) => e.isConnected); undo = null; return locked(previous.map(([e]) => e), async function () { previous.forEach(([e, value]) => { e.value = value; }); await Promise.all(previous.map(([e]) => saver.save(e))); }); } function mergeCells(cells) { const all = Array.from(table.querySelectorAll(".pj-meet-text")); return locked(all, async function () { await opts.api("POST", "/project/api/goals/meeting-cells/merge", { item_from: cells[0].dataset.meetItem, item_to: cells.at(-1).dataset.meetItem }); saver.reload(); }); } function unmergeCells(cells) { return locked(Array.from(table.querySelectorAll(".pj-meet-text")), async function () { for (const td of cells) await opts.api("DELETE", "/project/api/goals/meeting-items/" + td.dataset.meetItem + "/cell-merge"); saver.reload(); }); } function cancelMove() { moveDrag = null; table.querySelectorAll(".is-goal-move-target").forEach(td => td.classList.remove("is-goal-move-target")); document.documentElement.classList.remove("pj-goal-moving"); } if (admin) { table.addEventListener("mousedown", function (e) { if (e.defaultPrevented || e.button !== 0 || busy) return; const td = editableCell(e.target); if (!td) return; if (e.target.closest(".pj-goal-move-edge")) { e.preventDefault(); e.stopPropagation(); rangeDrag = null; moveDrag = { source: td, target: null }; document.documentElement.classList.add("pj-goal-moving"); return; } if (e.shiftKey && anchor && anchor !== td && anchor.closest("tbody") === td.closest("tbody")) { e.preventDefault(); select(anchor, td); if (document.activeElement) document.activeElement.blur(); return; } anchor = td; select(td, td); rangeDrag = { start: td }; }); table.addEventListener("mouseover", function (e) { if (!rangeDrag || moveDrag) return; const td = editableCell(e.target); if (!td || td === rangeDrag.start || td.closest("tbody") !== rangeDrag.start.closest("tbody")) return; document.documentElement.classList.add("pj-goal-selecting"); if (document.activeElement) document.activeElement.blur(); window.getSelection().removeAllRanges(); select(rangeDrag.start, td); }); document.addEventListener("mousemove", function (e) { if (!moveDrag) return; const td = editableCell(document.elementFromPoint(e.clientX, e.clientY)); table.querySelectorAll(".is-goal-move-target").forEach(c => c.classList.remove("is-goal-move-target")); moveDrag.target = td && td !== moveDrag.source ? td : null; if (moveDrag.target) moveDrag.target.classList.add("is-goal-move-target"); }); document.addEventListener("mouseup", function () { rangeDrag = null; document.documentElement.classList.remove("pj-goal-selecting"); if (!moveDrag) return; const { source, target } = moveDrag; cancelMove(); suppressClick = Date.now() + 300; if (target) moveCell(source, target); }); table.addEventListener("click", function (e) { if (busy || (Date.now() < suppressClick && editableCell(e.target))) { e.preventDefault(); e.stopImmediatePropagation(); } }, true); document.addEventListener("keydown", function (e) { if (e.key === "Escape") { cancelMove(); rangeDrag = null; clearSelection(); document.documentElement.classList.remove("pj-goal-selecting"); } const active = document.activeElement; if (busy || (active && (active.isContentEditable || active.matches("textarea,input,select")))) return; if (e.key === "Delete" && selected.length) { e.preventDefault(); clearCells(selected.slice()); } else if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "z" && undo) { e.preventDefault(); undoClear(); } }); window.addEventListener("blur", function () { cancelMove(); rangeDrag = null; document.documentElement.classList.remove("pj-goal-selecting"); }); document.addEventListener("mousedown", function (e) { if (!editableCell(e.target) && !e.target.closest(".pj-ctxmenu,.pj-goal-format")) clearSelection(); }, true); } table.addEventListener("contextmenu", function (e) { if (busy) { e.preventDefault(); e.stopImmediatePropagation(); return; } const td = e.target.closest("td,th"); if (!td || !table.contains(td)) return; if (admin && td.matches("th.pj-meet-c-label")) return; // 기존 줄 메뉴에 너비 항목을 붙인다. const cell = admin && editableCell(td), items = []; if (cell) { if (!selected.includes(cell)) select(cell, cell); const cells = selected.slice(), merged = cells.filter(c => c.rowSpan > 1); if (table.dataset.cellMerges === "true" && cells.length > 1) items.push({ label: "셀 병합 (세로)", icon: opts.icon("cell_merge"), onClick: () => mergeCells(cells) }); if (merged.length) items.push({ label: "병합 해제", icon: opts.icon("call_split"), onClick: () => unmergeCells(merged) }); if (cells.some(c => editorOf(c).value)) items.push({ label: "내용 지우기 (Del)", icon: opts.icon("ink_eraser"), onClick: () => clearCells(cells) }); if (saver) { items.push(null, { label: "위에 줄 추가", icon: opts.icon("add_row_above"), onClick: () => saver.addRow(cell.closest("tbody").dataset.section, cell.dataset.meetItem, "above") }, { label: "아래에 줄 추가", icon: opts.icon("add_row_below"), onClick: () => { const rows = Array.from(cell.closest("tbody").rows), bottom = rows[rows.indexOf(cell.parentElement) + cell.rowSpan - 1]; saver.addRow(cell.closest("tbody").dataset.section, bottom.dataset.item, "below"); } }); } } if (items.length) items.push(null); items.push(...widthItems(td)); if (items.length) { e.preventDefault(); opts.menu(e.clientX, e.clientY, items); } }); return { bindSaver: s => { saver = s; }, widthItems: widthItems }; } window.PJMeetingCells = { init: init }; })();