feat(project): 보드 가로 스크롤 · 카드 인라인 편집 · 내 업무 사이드 메뉴 · @태그

- 보드: 매이슨리 절대배치 제거 → 아사나식 flex 가로 배치. 세션이 늘어나면
  아래로 접히지 않고 계속 오른쪽으로 이어지고, 보드가 가로로 스크롤된다
  (막대는 attachHScrollIndicator 가 직접 그린다). 긴 세션은 컬럼 안에서 세로 스크롤.
- 카드: 담당자/마감일을 클릭하면 팝업을 열지 않고 그 자리에서 바꾼다.
  값이 없는 칩은 카드 호버 시 흐리게 나타나 바로 지정할 수 있다.
- 내 업무: 화면 오른쪽 상시 패널을 없애고 좌측 사이드바의 접이식 메뉴로 이전
  (기본 접힘, 업무를 고르면 팝업이 열리며 다시 접힘). 레이아웃 3열 → 2열.
- 설명란: 웹주소를 붙여넣으면 자동 링크(target=_blank), 클릭하면 새 탭으로 연다.
  contenteditable 은 브라우저가 링크를 기본으로 열지 않아 클릭을 직접 받는다.
- @태그: 설명란·댓글에서 @ 로 멤버를 고른다. 설명란은 멘션 칩(data-email),
  댓글은 화면이 고른 이메일을 함께 전송. 서버는 설명란의 경우 저장될 HTML 에서
  직접 이메일을 뽑는다(화면이 보낸 목록을 믿지 않는다).
  태그된 사람은 수신함(/project/inbox)에서 그 업무를 리스트로 본다.

DB: 마이그레이션 006(task_mentions) 신규 — 배포 시 적용 필요.
    미적용 환경에서도 화면이 죽지 않게 멘션 조회/기록은 모두 감쌌다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-22 11:04:21 +09:00
parent 79aa16bf49
commit fac8d5a0b1
11 changed files with 1152 additions and 166 deletions
+542 -43
View File
@@ -293,6 +293,7 @@
renderPending();
});
const cmInput = el("pj-cm-input");
attachMentionInput(cmInput);
if (cmInput) cmInput.addEventListener("paste", function (e) {
const items = (e.clipboardData || window.clipboardData || {}).items || [];
let handled = false;
@@ -438,7 +439,7 @@
const filesToSend = pendingFiles.slice();
try {
const res = await api("POST", "/project/api/tasks/" + taskId + "/comments",
{ body: bodyText, has_attachment: filesToSend.length > 0 });
{ body: bodyText, has_attachment: filesToSend.length > 0, mentions: takeMentions(inp) });
const commentId = res.comment.id;
for (let i = 0; i < filesToSend.length; i++) {
const fd = new FormData();
@@ -456,6 +457,7 @@
pendingFiles = [];
renderPending();
inp.value = "";
clearMentions(inp);
const n = await renderChat(taskId);
if (n !== null) { markSeen(taskId, n); syncBadge(taskId, n); }
} catch (e) { alert("등록 실패: " + e.message); }
@@ -468,6 +470,311 @@
return cmtChat;
}
// ════════════════════════════════════════════════════════════
// 멘션(@태그) — 설명란(contenteditable)과 댓글 입력(평문 input) 공용
//
// @를 누르면 등록된 전체 프로젝트 멤버가 뜨고, 고르면
// · 설명란: <span class="pj-mention" data-email="...">@아이디</span> 칩
// · 댓글 : "@아이디 " 평문 + 이메일을 따로 기억(전송 시 함께 보냄)
// 으로 들어간다. 태그된 사람은 수신함(/project/inbox)에서 그 업무를 본다.
// ════════════════════════════════════════════════════════════
let mentionUsersCache = null;
async function mentionUsers() {
if (mentionUsersCache) return mentionUsersCache;
try {
const res = await api("GET", "/project/api/all-users");
mentionUsersCache = res.users || [];
} catch (_) { mentionUsersCache = []; }
return mentionUsersCache;
}
// 메뉴는 화면에 하나만 띄운다(설명란/댓글/채팅이 번갈아 쓴다).
let mentionMenuEl = null;
let mentionMenuState = null;
function closeMentionMenu() {
if (mentionMenuEl) mentionMenuEl.hidden = true;
mentionMenuState = null;
}
function mentionMenuOpen() { return !!mentionMenuState; }
function ensureMentionMenu() {
if (mentionMenuEl) return mentionMenuEl;
mentionMenuEl = document.createElement("div");
mentionMenuEl.className = "pj-mention-menu";
mentionMenuEl.hidden = true;
document.body.appendChild(mentionMenuEl);
// mousedown 은 막는다 — 안 그러면 목록을 누르는 순간 입력칸이 포커스를
// 잃어 커서 위치(=치환할 자리)가 사라진다.
mentionMenuEl.addEventListener("mousedown", function (e) { e.preventDefault(); });
document.addEventListener("mousedown", function (e) {
if (mentionMenuEl && !mentionMenuEl.contains(e.target)) closeMentionMenu();
}, true);
window.addEventListener("resize", closeMentionMenu);
return mentionMenuEl;
}
function renderMentionMenu(users, rect, onPick) {
const menu = ensureMentionMenu();
menu.innerHTML = "";
if (!users.length) {
menu.innerHTML = '<div class="pj-mention-empty">일치하는 멤버 없음</div>';
} else {
users.forEach(function (u, i) {
const b = document.createElement("button");
b.type = "button";
b.className = "pj-mention-opt" + (i === 0 ? " is-active" : "");
b.innerHTML =
(u.avatar
? '<img class="pj-avatar pj-gicon-sm" src="' + escapeHtml(u.avatar) + '" alt="" referrerpolicy="no-referrer">'
: '<span class="material-symbols-outlined pj-gicon pj-gicon-sm">account_circle</span>') +
"<span>" + escapeHtml(u.id || u.name || u.email) + "</span>";
b.addEventListener("click", function () { onPick(u); });
menu.appendChild(b);
});
}
menu.hidden = false;
// 커서/입력칸 바로 아래. 화면 밖으로 나가면 위쪽으로 뒤집는다.
let top = window.scrollY + rect.bottom + 4;
let left = window.scrollX + rect.left;
left = Math.min(left, window.scrollX + document.documentElement.clientWidth - menu.offsetWidth - 8);
if (rect.bottom + menu.offsetHeight + 8 > document.documentElement.clientHeight) {
top = window.scrollY + rect.top - menu.offsetHeight - 4;
}
menu.style.left = Math.max(8, left) + "px";
menu.style.top = Math.max(8, top) + "px";
mentionMenuState = { users: users, index: 0, onPick: onPick };
}
function moveMentionActive(delta) {
if (!mentionMenuState) return;
const opts = mentionMenuEl.querySelectorAll(".pj-mention-opt");
if (!opts.length) return;
opts[mentionMenuState.index].classList.remove("is-active");
mentionMenuState.index = (mentionMenuState.index + delta + opts.length) % opts.length;
const act = opts[mentionMenuState.index];
act.classList.add("is-active");
act.scrollIntoView({ block: "nearest" });
}
function chooseMentionActive() {
if (!mentionMenuState) return false;
const u = mentionMenuState.users[mentionMenuState.index];
if (!u) { closeMentionMenu(); return false; }
mentionMenuState.onPick(u);
return true;
}
function filterMentionUsers(users, query) {
const q = (query || "").toLowerCase();
if (!q) return users.slice(0, 12);
return users.filter(function (u) {
return (u.id || "").toLowerCase().indexOf(q) >= 0 ||
(u.name || "").toLowerCase().indexOf(q) >= 0 ||
(u.email || "").toLowerCase().indexOf(q) >= 0;
}).slice(0, 12);
}
// 메뉴가 떠 있을 때 위/아래/엔터/탭/ESC 를 가로챈다(입력칸 공용).
function mentionKeydown(e) {
if (!mentionMenuOpen()) return false;
if (e.key === "ArrowDown") { e.preventDefault(); moveMentionActive(1); return true; }
if (e.key === "ArrowUp") { e.preventDefault(); moveMentionActive(-1); return true; }
// stopImmediatePropagation 이어야 한다 — 같은 입력칸에 걸린 "Enter=전송"
// 핸들러는 stopPropagation 으로는 안 막힌다(같은 노드의 다른 리스너).
// 그래서 이 멘션 리스너를 항상 먼저 등록한다(attachMentionInput 호출 위치).
if (e.key === "Enter" || e.key === "Tab") {
e.preventDefault(); e.stopImmediatePropagation();
chooseMentionActive();
return true;
}
if (e.key === "Escape") { e.preventDefault(); closeMentionMenu(); return true; }
return false;
}
// ── 평문 input 용 (#pj-comment-input, #pj-cm-input) ──
// 고른 사람을 input 에 기억해두고(_pjMentions), 전송 직전에 "@아이디" 가
// 아직 본문에 남아 있는 사람만 서버로 보낸다.
function attachMentionInput(input) {
if (!input || input.dataset.pjMention) return;
input.dataset.pjMention = "1";
input._pjMentions = {}; // "@아이디" → 이메일
function caretQuery() {
const pos = input.selectionStart == null ? input.value.length : input.selectionStart;
const before = input.value.slice(0, pos);
const m = before.match(/(?:^|\s)@([^\s@]*)$/);
return m === null ? null : { query: m[1], start: pos - m[1].length - 1, end: pos };
}
async function maybeOpen() {
const ctx = caretQuery();
if (!ctx) { closeMentionMenu(); return; }
const users = filterMentionUsers(await mentionUsers(), ctx.query);
renderMentionMenu(users, input.getBoundingClientRect(), function (u) {
const token = "@" + (u.id || u.email.split("@")[0]);
input.value = input.value.slice(0, ctx.start) + token + " " + input.value.slice(ctx.end);
input._pjMentions[token] = u.email;
const caret = ctx.start + token.length + 1;
input.focus();
input.setSelectionRange(caret, caret);
closeMentionMenu();
});
}
input.addEventListener("input", maybeOpen);
input.addEventListener("blur", function () { setTimeout(closeMentionMenu, 120); });
// keydown 은 capture 로 먼저 받는다 — 이 입력칸들은 Enter 에 "전송"이
// 걸려 있어서, 메뉴가 떠 있을 때 Enter 가 전송으로 새 나가면 안 된다.
input.addEventListener("keydown", function (e) { mentionKeydown(e); }, true);
}
// 전송 시 실제로 본문에 남아 있는 태그만 추린다.
function takeMentions(input) {
if (!input || !input._pjMentions) return [];
const text = input.value || "";
const out = [];
Object.keys(input._pjMentions).forEach(function (token) {
if (text.indexOf(token) >= 0) {
const email = input._pjMentions[token];
if (out.indexOf(email) < 0) out.push(email);
}
});
return out;
}
function clearMentions(input) { if (input) input._pjMentions = {}; }
// ── contenteditable 용 (설명란) — 멘션 칩을 끼워 넣는다 ──
function attachMentionEditor(box) {
if (!box || box.dataset.pjMention) return;
box.dataset.pjMention = "1";
function caretContext() {
const sel = window.getSelection();
if (!sel || !sel.rangeCount) return null;
const r = sel.getRangeAt(0);
if (!r.collapsed || !box.contains(r.startContainer)) return null;
const node = r.startContainer;
if (node.nodeType !== 3) return null; // 텍스트 노드 안에서만
const before = node.textContent.slice(0, r.startOffset);
const m = before.match(/(?:^|[\s\u00a0])@([^\s@\u00a0]*)$/);
if (m === null) return null;
return { node: node, query: m[1], start: r.startOffset - m[1].length - 1, end: r.startOffset };
}
async function maybeOpen() {
const ctx = caretContext();
if (!ctx) { closeMentionMenu(); return; }
const sel = window.getSelection();
let rect = sel.rangeCount ? sel.getRangeAt(0).getBoundingClientRect() : null;
if (!rect || (!rect.width && !rect.height)) rect = box.getBoundingClientRect();
const users = filterMentionUsers(await mentionUsers(), ctx.query);
renderMentionMenu(users, rect, function (u) {
const range = document.createRange();
range.setStart(ctx.node, ctx.start);
range.setEnd(ctx.node, ctx.end);
range.deleteContents();
const chip = document.createElement("span");
chip.className = "pj-mention";
chip.setAttribute("data-email", u.email);
chip.setAttribute("contenteditable", "false");
chip.textContent = "@" + (u.id || u.email.split("@")[0]);
const space = document.createTextNode("\u00a0");
range.insertNode(space);
range.insertNode(chip);
// 커서를 칩 뒤 공백 다음으로
const after = document.createRange();
after.setStartAfter(space);
after.collapse(true);
const s2 = window.getSelection();
s2.removeAllRanges();
s2.addRange(after);
box.focus();
closeMentionMenu();
});
}
box.addEventListener("input", maybeOpen);
box.addEventListener("keydown", function (e) { mentionKeydown(e); }, true);
box.addEventListener("blur", function () { setTimeout(closeMentionMenu, 120); });
}
// ════════════════════════════════════════════════════════════
// 설명란 링크 — 주소를 붙여넣으면 <a> 로 바꾸고, 클릭하면 새 탭으로 연다
// ════════════════════════════════════════════════════════════
const PJ_URL_RE = /(https?:\/\/[^\s<>"']+|www\.[^\s<>"']+)/g;
function linkifyToHtml(text) {
const src = String(text == null ? "" : text);
let out = "";
let last = 0;
let m;
PJ_URL_RE.lastIndex = 0;
while ((m = PJ_URL_RE.exec(src)) !== null) {
out += escapeHtml(src.slice(last, m.index));
// 주소 끝에 붙은 문장부호는 링크에서 뺀다(".", ",", ")" 등).
let url = m[0];
let tail = "";
const trailing = url.match(/[).,!?;:'"]+$/);
if (trailing) { tail = trailing[0]; url = url.slice(0, url.length - tail.length); }
const href = /^https?:\/\//i.test(url) ? url : "http://" + url;
out += '<a href="' + escapeHtml(href) + '" target="_blank" rel="noopener noreferrer">' +
escapeHtml(url) + "</a>" + escapeHtml(tail);
last = m.index + m[0].length;
}
out += escapeHtml(src.slice(last));
return out.replace(/\n/g, "<br>");
}
// 에디터 안의 모든 <a> 가 새 탭으로 열리게 맞춘다(서식바 링크 버튼 포함).
function normalizeEditorLinks(box) {
if (!box) return;
box.querySelectorAll("a").forEach(function (a) {
a.setAttribute("target", "_blank");
a.setAttribute("rel", "noopener noreferrer");
});
}
// ════════════════════════════════════════════════════════════
// 가로 스크롤 막대 — 보드(세션이 오른쪽으로 계속 늘어난다)용.
// 세로 막대(attachScrollIndicator)와 같은 이유로 직접 그린다.
// ════════════════════════════════════════════════════════════
function attachHScrollIndicator(scroller, bar) {
if (!scroller || !bar) return null;
const thumb = bar.querySelector(".pj-hbar-thumb");
if (!thumb) return null;
let thumbW = 0;
function update() {
const sw = scroller.scrollWidth, cw = scroller.clientWidth;
if (cw <= 0 || sw <= cw + 1) { bar.hidden = true; return; }
bar.hidden = false;
const trackW = bar.clientWidth;
thumbW = Math.max(32, Math.round(trackW * cw / sw));
const left = Math.round((trackW - thumbW) * scroller.scrollLeft / (sw - cw));
thumb.style.width = thumbW + "px";
thumb.style.transform = "translateX(" + left + "px)";
}
if (bar.dataset.pjHbar) return update;
bar.dataset.pjHbar = "1";
scroller.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", update);
if (window.ResizeObserver) new ResizeObserver(update).observe(scroller);
let dragging = false, startX = 0, startLeft = 0;
thumb.addEventListener("mousedown", function (e) {
e.preventDefault();
dragging = true; startX = e.clientX; startLeft = scroller.scrollLeft;
thumb.classList.add("is-dragging");
});
document.addEventListener("mousemove", function (e) {
if (!dragging) return;
const sw = scroller.scrollWidth, cw = scroller.clientWidth;
const room = bar.clientWidth - thumbW;
if (room <= 0) return;
scroller.scrollLeft = startLeft + (e.clientX - startX) * (sw - cw) / room;
});
document.addEventListener("mouseup", function () {
if (dragging) { dragging = false; thumb.classList.remove("is-dragging"); }
});
bar.addEventListener("mousedown", function (e) {
if (e.target !== bar) return;
e.preventDefault();
const x = e.clientX - bar.getBoundingClientRect().left;
const thumbLeft = thumb.getBoundingClientRect().left - bar.getBoundingClientRect().left;
scroller.scrollLeft += (x < thumbLeft ? -1 : 1) * scroller.clientWidth * 0.9;
});
update();
return update;
}
// ════════════════════════════════════════════════════════════
// 홈 페이지 — 새 프로젝트
// ════════════════════════════════════════════════════════════
@@ -888,6 +1195,7 @@
if (cmt) cmt.wireBadge(newLi.querySelector(".pj-cmt-badge"));
if (existingLi) existingLi.replaceWith(newLi); else group.appendChild(newLi);
updateMyTreeCounts(groupEl);
refreshMyTasksBadge();
}
@@ -1155,14 +1463,17 @@
});
} catch (e) { ul.innerHTML = "<li class='pj-empty-sm'>불러오기 실패</li>"; }
}
attachMentionInput(el("pj-comment-input"));
el("pj-comment-send").addEventListener("click", async function () {
const taskId = el("pj-t-id").value;
const inp = el("pj-comment-input");
const body = inp.value.trim();
if (!taskId || !body) return;
try {
await api("POST", "/project/api/tasks/" + taskId + "/comments", { body: body });
await api("POST", "/project/api/tasks/" + taskId + "/comments",
{ body: body, mentions: takeMentions(inp) });
inp.value = "";
clearMentions(inp);
loadHomeComments(taskId);
} catch (e) { alert("등록 실패: " + e.message); }
});
@@ -1459,7 +1770,7 @@
"</a></li>";
}
function syncProjectMyTaskPanel(t, removed) {
const groupEl = document.querySelector('.pj-project-mytasks .pj-mytree-group[data-group-id="' + t.project_id + '"]');
const groupEl = document.querySelector('.pj-mytasks-panel .pj-mytree-group[data-group-id="' + t.project_id + '"]');
const group = groupEl ? groupEl.querySelector(".pj-mytree-tasks") : null;
if (!group) return; // 이 프로젝트에 내 업무가 하나도 없었으면 다음 새로고침까지 생략.
const existingLink = group.querySelector('.pj-task-popup-link[data-task-id="' + t.id + '"]');
@@ -1467,6 +1778,7 @@
if (removed) {
if (existingLi) existingLi.remove();
updateMyTreeCounts(groupEl);
refreshMyTasksBadge();
return;
}
const wrap = document.createElement("div");
@@ -1521,9 +1833,36 @@
},
];
}
// ── 좌측 사이드바의 접이식 "내 업무" 메뉴 ──
// 기본은 접힘. 누르면 펼쳐지고, 업무를 하나 고르면 팝업이 열리면서 다시
// 접힌다(예전 화면 오른쪽에 항상 떠 있던 패널을 대체).
const myTasksToggle = el("pj-mytasks-toggle");
const myTasksPanel = el("pj-mytasks-panel");
function setMyTasksOpen(open) {
if (!myTasksToggle || !myTasksPanel) return;
myTasksPanel.hidden = !open;
myTasksToggle.setAttribute("aria-expanded", open ? "true" : "false");
}
if (myTasksToggle) myTasksToggle.addEventListener("click", function () {
setMyTasksOpen(myTasksPanel.hidden);
});
// 진행 중 업무 총합 배지 — 완료/삭제/재배정으로 목록이 바뀔 때마다 갱신.
function refreshMyTasksBadge() {
if (!myTasksToggle) return;
const badge = myTasksToggle.querySelector(".pj-side-navbadge-open");
if (!badge) return;
let n = 0;
document.querySelectorAll(".pj-mytasks-panel .pj-mtc-open").forEach(function (e2) {
n += parseInt(e2.textContent, 10) || 0;
});
badge.textContent = n;
badge.hidden = n === 0;
}
function wireMyTaskPopupLink(a) {
a.addEventListener("click", function (e) {
e.preventDefault();
setMyTasksOpen(false);
const t = myTasksById[a.dataset.taskId];
if (t) openTaskModal(t);
});
@@ -1535,7 +1874,7 @@
showContextMenu(e.clientX, e.clientY, myTaskContextItems(t));
});
}
document.querySelectorAll(".pj-project-mytasks .pj-task-popup-link").forEach(function (a) { wireMyTaskPopupLink(a); });
document.querySelectorAll(".pj-mytasks-panel .pj-task-popup-link").forEach(function (a) { wireMyTaskPopupLink(a); });
// 담당자/작성자 아이콘 = 구글 프로필 이미지(원형). 없으면 기본 아이콘.
function avatarHtml(email, cls) {
const url = email ? avatars[String(email).toLowerCase()] : "";
@@ -2126,45 +2465,33 @@
}
function renderBoard() {
// pj-board(바깥)는 overflow-y:auto 스크롤 뷰포트, pj-board-canvas(안쪽)가
// 실제 매이슨리 절대배치 캔버스 — 스크롤 컨테이너와 콘텐츠 높이 계산을
// 분리해야 pj-board 의 높이가 부모(flex) 크기를 그대로 따라간다.
// pj-board(바깥)는 가로 스크롤 뷰포트, pj-board-canvas(안쪽)는 세션을
// 가로로 늘어놓는 flex 컨테이너(width:max-content) — 세션이 아무리
// 늘어나도 아래로 접히지 않고 오른쪽으로 계속 이어진다.
const canvas = el("pj-board-canvas");
canvas.innerHTML = "";
const vis = visibleTasks();
if (boardAddStageBtn) boardAddStageBtn.hidden = !(viewScope === "project" && canManage);
if (viewScope === "project") renderBoardByStage(canvas, vis);
else renderBoardByName(canvas, vis);
layoutMasonry(canvas);
syncBoardHBar();
}
// 세션(보드 컬럼) 매이슨리 배치 — 열은 왼쪽부터 순서대로 고정 배정하고,
// 각 열은 자기 안에 쌓인 카드 높이만큼만 다음 세션을 그 밑에 이어붙인다
// (CSS Grid처럼 행 전체를 가장 큰 세션에 맞춰 늘리지 않는다).
function layoutMasonry(board) {
const items = Array.prototype.slice.call(board.children).filter(function (node) {
return node.classList.contains("pj-col");
});
if (!items.length) { board.style.height = "auto"; return; }
const gap = 16, minColWidth = 220, maxCols = 4;
const boardWidth = board.clientWidth || 1;
const cols = Math.max(1, Math.min(maxCols, Math.floor((boardWidth + gap) / (minColWidth + gap))));
const colWidth = (boardWidth - gap * (cols - 1)) / cols;
const colHeights = new Array(cols).fill(0);
items.forEach(function (node, i) {
const c = i % cols;
node.style.width = colWidth + "px";
node.style.left = (c * (colWidth + gap)) + "px";
node.style.top = colHeights[c] + "px";
colHeights[c] += node.offsetHeight + gap;
});
board.style.height = Math.max.apply(null, colHeights) + "px";
// 아사나식 가로 보드 — 세션은 CSS flex 로 왼쪽부터 나란히 놓이고, 세션이
// 늘어나면 아래로 접히지 않고 계속 오른쪽으로 이어지며 보드가 가로로
// 스크롤된다(예전 매이슨리 절대배치를 대체). 배치는 전부 CSS 가 하므로
// JS 는 직접 그리는 가로 스크롤 막대만 갱신한다.
let boardHBarUpdate = null;
function syncBoardHBar() {
const board = el("pj-board");
const bar = el("pj-board-hbar");
if (!board || !bar) return;
if (!boardHBarUpdate) boardHBarUpdate = attachHScrollIndicator(board, bar);
if (boardHBarUpdate) boardHBarUpdate();
}
let boardResizeTimer = null;
window.addEventListener("resize", function () {
if (currentView !== "board") return;
clearTimeout(boardResizeTimer);
boardResizeTimer = setTimeout(function () { layoutMasonry(el("pj-board-canvas")); }, 120);
syncBoardHBar();
});
function renderBoardByName(board, vis) {
@@ -2233,7 +2560,6 @@
if (!list.length && !vis.length) {
const empty = document.createElement("div");
empty.className = "pj-empty";
empty.style.gridColumn = "1 / -1";
empty.textContent = "세션이 없습니다. 위 \"+ 세션 추가\"로 만들어 보세요.";
board.appendChild(empty);
}
@@ -2446,6 +2772,93 @@
});
}
// ── 보드 카드에서 바로 고치는 담당자/마감일 ──
// 업무 팝업을 열지 않고 카드 위에서 끝낸다(아사나와 같은 조작감).
// 후보는 "그 업무가 속한 프로젝트"의 멤버다 — 전체 프로젝트 보기에서는
// 카드마다 프로젝트가 달라서 필요할 때 받아와 캐시한다.
const memberCacheByProject = {};
async function membersOfProject(pid) {
if (pid === projectId) return members;
if (memberCacheByProject[pid]) return memberCacheByProject[pid];
const res = await api("GET", "/project/api/projects/" + pid + "/members");
memberCacheByProject[pid] = res.members || [];
return memberCacheByProject[pid];
}
async function applyTaskPatch(t, patch, failMsg) {
try {
const res = await api("PUT", "/project/api/tasks/" + t.id, patch);
mergeTask(res.task);
if (myTasksById[t.id]) {
myTasksById[t.id] = Object.assign({}, myTasksById[t.id], res.task);
syncProjectMyTaskPanel(myTasksById[t.id]);
}
refreshActiveView();
} catch (e) { showToast(failMsg + ": " + e.message, "error"); }
}
async function openAssigneePicker(t, x, y) {
let list;
try { list = await membersOfProject(t.project_id); }
catch (e) { showToast("멤버 조회 실패: " + e.message, "error"); return; }
const cur = (t.assignee_email || "").toLowerCase();
const items = [{
label: (cur ? "" : "✓ ") + "(미지정)",
onClick: function () { applyTaskPatch(t, { assignee_email: "", assignee_name: "" }, "담당자 변경 실패"); },
}];
list.forEach(function (m) {
const email = m.user_email;
items.push({
label: (email.toLowerCase() === cur ? "✓ " : "") + idOf(email),
onClick: function () {
applyTaskPatch(t, { assignee_email: email, assignee_name: idOf(email) }, "담당자 변경 실패");
},
});
});
showContextMenu(x, y, items);
}
// 마감일 — 카드 위에 작은 날짜 입력칸을 띄운다. 값이 바뀌면 바로 저장하고,
// "지우기"로 마감일을 없앨 수 있다. 바깥을 누르면 닫힌다.
let inlineDateEl = null;
function closeInlineDate() {
if (inlineDateEl) { inlineDateEl.remove(); inlineDateEl = null; }
document.removeEventListener("mousedown", onInlineDateDown, true);
}
function onInlineDateDown(e) {
if (inlineDateEl && !inlineDateEl.contains(e.target)) closeInlineDate();
}
function openDuePicker(t, anchorEl) {
closeInlineDate();
const box = document.createElement("div");
box.className = "pj-inline-date";
box.innerHTML = '<input type="date" value="' + (t.due_date || "") + '" />' +
'<button type="button" class="pj-btn">지우기</button>';
document.body.appendChild(box);
const r = anchorEl.getBoundingClientRect();
let left = window.scrollX + r.left;
left = Math.min(left, window.scrollX + document.documentElement.clientWidth - box.offsetWidth - 8);
box.style.left = Math.max(8, left) + "px";
box.style.top = (window.scrollY + r.bottom + 4) + "px";
inlineDateEl = box;
const input = box.querySelector("input");
input.addEventListener("change", function () {
const v = input.value || null;
closeInlineDate();
if (v === (t.due_date || null)) return;
applyTaskPatch(t, { due_date: v }, "마감일 변경 실패");
});
box.querySelector("button").addEventListener("click", function () {
closeInlineDate();
if (!t.due_date) return;
applyTaskPatch(t, { due_date: null }, "마감일 변경 실패");
});
setTimeout(function () {
document.addEventListener("mousedown", onInlineDateDown, true);
try { input.focus(); if (input.showPicker) input.showPicker(); } catch (_) {}
}, 0);
}
function taskCard(t) {
const card = document.createElement("div");
card.className = "pj-card" + (t.completed_at ? " is-done" : "");
@@ -2464,20 +2877,32 @@
(t.priority && t.priority !== "normal"
? '<span class="pj-pri pj-pri-' + t.priority + '">' + (priorityLabels[t.priority] || t.priority) + "</span>"
: "") +
(t.assignee_email
? '<span class="pj-assignee">' + avatarHtml(t.assignee_email, "pj-gicon-sm") +
escapeHtml(idOf(t.assignee_email)) + "</span>"
: "") +
// 담당자/마감일은 카드에서 바로 바꿀 수 있다(아래 클릭 핸들러).
// 값이 없어도 자리는 남겨 둔다 — 카드에 마우스를 올리면 흐리게
// 나타나서 눌러 지정할 수 있다(.is-empty).
'<span class="pj-assignee pj-card-edit-hit pj-card-assignee' +
(t.assignee_email ? '' : ' is-empty') + '" title="담당자 변경">' +
avatarHtml(t.assignee_email, "pj-gicon-sm") +
escapeHtml(t.assignee_email ? idOf(t.assignee_email) : "담당자") + "</span>" +
(t.subtask_total
? '<span class="pj-card-subtasks" title="하위 업무">' + (t.subtask_done || 0) + "/" + t.subtask_total + "</span>"
: "") +
(t.due_date ? '<span class="pj-card-due">' + t.due_date + "</span>" : "") +
'<span class="pj-card-due pj-card-edit-hit' + (t.due_date ? '' : ' is-empty') +
'" title="마감일 변경">' + (t.due_date ? escapeHtml(t.due_date) : "마감일") + "</span>" +
(t.comment_count
? '<span class="pj-card-cmt pj-cmt-badge" data-task-id="' + t.id + '" data-count="' + t.comment_count +
'" title="댓글 ' + t.comment_count + '개">' + cmtBadge(t) + "</span>"
: "") +
"</div>";
card.addEventListener("click", function () { if (canManage) openTaskModal(t); });
card.addEventListener("click", function (e) {
if (!canManage) return;
// 담당자/마감일 칩을 누른 경우엔 업무 팝업 대신 그 자리 편집기를 연다.
const hitAssignee = e.target.closest(".pj-card-assignee");
if (hitAssignee) { e.stopPropagation(); openAssigneePicker(t, e.clientX, e.clientY); return; }
const hitDue = e.target.closest(".pj-card-due");
if (hitDue) { e.stopPropagation(); openDuePicker(t, hitDue); return; }
openTaskModal(t);
});
// 댓글 말풍선 더블클릭 → 채팅형 댓글 팝업(내 업무 패널과 동일 구현 공용).
if (cmt) cmt.wireBadge(card.querySelector(".pj-cmt-badge"));
if (canManage) {
@@ -3190,11 +3615,14 @@
const body = inp.value.trim();
if (!currentTaskId || !body) return;
try {
await api("POST", "/project/api/tasks/" + currentTaskId + "/comments", { body: body });
await api("POST", "/project/api/tasks/" + currentTaskId + "/comments",
{ body: body, mentions: takeMentions(inp) });
inp.value = "";
clearMentions(inp);
loadComments(currentTaskId);
} catch (e) { alert("등록 실패: " + e.message); }
}
attachMentionInput(el("pj-comment-input"));
el("pj-comment-send").addEventListener("click", sendComment);
el("pj-comment-input").addEventListener("keydown", function (e) {
if (e.key === "Enter") { e.preventDefault(); sendComment(); }
@@ -3821,6 +4249,8 @@
function initDescEditor() {
const box = el("pj-t-desc");
if (!box) return null;
// @ 를 누르면 멤버 목록 → 고르면 멘션 칩이 들어간다(수신함에 쌓인다).
attachMentionEditor(box);
const wrap = box.parentElement;
const imgInput = el("pj-desc-img-input");
const hint = el("pj-desc-hint");
@@ -3844,6 +4274,7 @@
if (!arg) return;
}
try { document.execCommand(cmd, false, arg); } catch (_) {}
if (cmd === "createLink") normalizeEditorLinks(box);
updateFmtState();
});
function updateFmtState() {
@@ -3907,6 +4338,12 @@
box.addEventListener("click", function (e) {
if (e.target.tagName === "IMG") selectImg(e.target);
else selectImg(null);
// contenteditable 안의 <a> 는 브라우저가 기본으로 열지 않는다 — 직접 연다.
const link = e.target.closest ? e.target.closest("a") : null;
if (link && link.getAttribute("href")) {
e.preventDefault();
window.open(link.href, "_blank", "noopener,noreferrer");
}
});
document.addEventListener("click", function (e) {
if (selectedImg && !wrap.contains(e.target)) selectImg(null);
@@ -4053,9 +4490,10 @@
}
}
// 이미지가 아니면 서식 없는 텍스트로만 붙여넣기(외부 사이트 서식 유입 방지).
// 단, 웹페이지 주소는 자동으로 링크(<a target="_blank">)로 바꾼다.
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData("text/plain");
insertHtmlAtCursor(escapeHtml(text).replace(/\n/g, "<br>"));
insertHtmlAtCursor(linkifyToHtml(text));
});
if (imgInput) imgInput.addEventListener("change", function () {
@@ -4065,7 +4503,11 @@
return {
setTaskId: setTaskId,
setHtml: function (html) { selectImg(null); lastRange = null; box.innerHTML = html || ""; },
setHtml: function (html) {
selectImg(null); lastRange = null;
box.innerHTML = html || "";
normalizeEditorLinks(box);
},
getHtml: function () { return box.innerHTML; },
isUploading: function () { return pendingUploads > 0; },
setOnImageRemoved: function (fn) { onImageRemoved = fn; },
@@ -4295,6 +4737,60 @@
} catch (_) {}
}
// ── 좌측 사이드바 "수신함" 배지 — 아직 확인하지 않은 @태그 개수 ──
async function initMentionBadge() {
const badge = document.getElementById("pj-mention-badge");
if (!badge) return;
try {
const res = await api("GET", "/project/api/mentions/unread-count");
const n = res.unread || 0;
badge.textContent = n > 99 ? "99+" : n;
badge.hidden = n === 0;
} catch (_) {}
}
// ── 수신함: "나를 태그한 업무" 목록 ──
// 항목을 누르면 확인 처리(읽음)하고, "열기"는 그 업무의 편집 팝업까지 연다
// (?task= — project.js 의 프로젝트 화면이 받아서 처리).
function initMentionInbox() {
const list = document.getElementById("pj-mention-tasks");
const readAll = document.getElementById("pj-mentions-readall");
const counter = document.getElementById("pj-mention-unread");
if (!list && !readAll) return;
function setCounter(n) {
if (!counter) return;
counter.textContent = n;
counter.hidden = n <= 0;
}
function remaining() {
return list ? list.querySelectorAll(".pj-mention-item.is-unread").length : 0;
}
async function markRead(li) {
if (!li.classList.contains("is-unread")) return;
try {
await api("POST", "/project/api/mentions/read", { task_id: Number(li.dataset.taskId) });
li.classList.remove("is-unread");
setCounter(remaining());
} catch (e) { showToast("처리 실패: " + e.message, "error"); }
}
if (readAll) readAll.addEventListener("click", async function () {
try {
await api("POST", "/project/api/mentions/read", {});
if (list) list.querySelectorAll(".pj-mention-item.is-unread")
.forEach(function (li) { li.classList.remove("is-unread"); });
setCounter(0);
} catch (e) { showToast("처리 실패: " + e.message, "error"); }
});
if (list) list.querySelectorAll(".pj-mention-item").forEach(function (li) {
li.addEventListener("click", function (e) {
if (e.target.closest("a")) return; // '열기' 링크는 그대로 통과
markRead(li);
});
const go = li.querySelector(".pj-inbox-go");
if (go) go.addEventListener("click", function () { markRead(li); });
});
}
// ── 알림센터 페이지 ──
function initInbox() {
const inbox = document.getElementById("pj-inbox");
@@ -4352,6 +4848,7 @@
} else if (d.ts !== baseline) {
baseline = d.ts;
initBell();
initMentionBadge();
if (softSyncProjectRef) softSyncProjectRef();
}
}
@@ -4455,7 +4952,7 @@
update();
}
function initScrollIndicators() {
document.querySelectorAll(".pj-home-side, .pj-home-main, .pj-side, .pj-board")
document.querySelectorAll(".pj-home-side, .pj-home-main, .pj-side")
.forEach(attachScrollIndicator);
}
@@ -4488,7 +4985,9 @@
initHome();
initProject();
initBell();
initMentionBadge();
initInbox();
initMentionInbox();
initLiveRefresh();
wireMyTreeToggles();
initScrollIndicators();