feat(project): 검색·필터·정렬 + 팔로워 + 마감 알림

검색·필터·정렬
- 좌측 사이드바 전체 검색(/api/search): 제목·설명·댓글, 볼 수 있는
  프로젝트의 업무(하위 업무 포함). 설명 HTML 태그에만 걸린 결과는 본문
  텍스트로 재확인해 제거. 어디서 걸렸는지 + 미리보기, 키보드(/ ↑↓ Enter).
- 프로젝트 화면 필터 바: 찾기·상태·담당자·마감·우선순위·정렬. visibleTasks()
  에서 걸러 보드/리스트/달력/타임라인/대시보드 모두 적용, 프로젝트별 기억.
  필터·정렬 중엔 보드 카드 순서 드래그 차단.
- 내 업무 화면에도 찾기·마감·우선순위 필터.

팔로워 · 알림
- task_followers(008): 만든 사람·담당자·댓글 작성자·@태그된 사람 자동 팔로우,
  기존 업무 백필. 업무 팝업에서 추가/빼기/내 팔로우 토글.
- 완료·댓글 인앱 알림 수신자: 프로젝트 멤버 전원 → 담당자 + 팔로워.
  008 미적용이면 예전 방식 폴백.
- 마감 알림(reminders.py, lifespan 에서 데몬 스레드): 영업일(주말·공휴일
  skip) 09시 KST 1회, 다음 영업일까지 마감/오늘 마감/지남(7일 이내).
  수신자 담당자(없으면 팔로워). task_reminders UNIQUE 로 중복 방지, 마감일
  바뀌면 재알림. PROJECT_REMINDER_EMAIL=true 면 요약 메일.
- 008: pg_trgm GIN 인덱스(제목·설명·댓글), 미완료 마감일 부분 인덱스.

버그
- 업무 팝업 담당자 선택지가 프로젝트 멤버뿐이라, 멤버 목록에 없는 담당자
  (프로젝트 owner, 멤버에서 빠진 사람)의 업무를 열고 저장하면 담당자가
  지워지던 문제 수정.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-23 13:28:19 +09:00
parent b74f92523d
commit 78b6e8df11
16 changed files with 1141 additions and 24 deletions
+73
View File
@@ -1076,3 +1076,76 @@ label.pj-desc-fmtbtn { line-height: 26px; }
.pj-btn-share { display: inline-flex; align-items: center; gap: 5px; }
.pj-btn-share .material-symbols-outlined { font-size: 14px; }
.pj-btn-share[hidden] { display: none; }
/* ── 좌측 사이드바 전체 검색 ── */
.pj-side-search { position: relative; display: flex; align-items: center; margin-bottom: 10px; }
.pj-side-search-ic { position: absolute; left: 9px; font-size: 18px; color: #8a9099; pointer-events: none; }
.pj-side-search input {
width: 100%; box-sizing: border-box; height: 34px; padding: 0 10px 0 32px;
border: 1px solid var(--pj-border); border-radius: 8px; background: #f7f8f9;
font-size: 13px; font-family: inherit; color: var(--pj-ink);
}
.pj-side-search input:focus { outline: none; background: #fff; border-color: var(--pj-accent); box-shadow: 0 0 0 3px var(--pj-accent-tint); }
.pj-search-results {
position: fixed; z-index: 1200; overflow-y: auto; background: #fff;
border: 1px solid var(--pj-border); border-radius: 10px; box-shadow: 0 12px 32px rgba(16,24,40,.16);
padding: 4px;
}
.pj-search-results[hidden] { display: none; }
.pj-sr-item { padding: 8px 10px; border-radius: 8px; cursor: pointer; }
.pj-sr-item:hover, .pj-sr-item.is-active { background: var(--pj-accent-tint); }
.pj-sr-title { font-size: 13.5px; font-weight: 700; color: var(--pj-ink); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
.pj-sr-item.is-done .pj-sr-title { color: var(--pj-ink-soft); }
.pj-sr-check { font-size: 16px; color: #1e8e5a; }
.pj-sr-parent { font-weight: 500; color: var(--pj-ink-soft); }
.pj-sr-meta { margin-top: 2px; font-size: 12px; color: var(--pj-ink-soft); }
.pj-sr-snippet { margin-top: 3px; font-size: 12px; color: #525860; line-height: 1.45; }
.pj-sr-where { display: inline-block; padding: 0 5px; margin-right: 2px; border-radius: 4px; background: #eef0f2; font-size: 11px; font-weight: 700; color: #6b6f76; }
.pj-search-results mark { background: #fff3b0; color: inherit; border-radius: 2px; padding: 0 1px; }
.pj-sr-empty { padding: 14px 12px; font-size: 13px; color: var(--pj-ink-soft); }
/* ── 필터 바 (프로젝트 화면 / 내 업무) ── */
.pj-filterbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; flex: none; margin: -6px 0 14px; }
.pj-fb-search {
display: flex; align-items: center; gap: 6px; height: 32px; padding: 0 10px;
border: 1px solid var(--pj-border); border-radius: 8px; background: #fff; flex: 0 1 280px; min-width: 180px;
}
.pj-fb-search .material-symbols-outlined { font-size: 18px; color: #8a9099; }
.pj-fb-search input { border: none; outline: none; background: transparent; font-size: 13px; font-family: inherit; width: 100%; color: var(--pj-ink); }
.pj-fb-search.is-set { border-color: var(--pj-accent); background: var(--pj-accent-tint); }
.pj-fb-search:focus-within { border-color: var(--pj-accent); }
.pj-fb-select {
height: 32px; padding: 0 8px; border: 1px solid var(--pj-border); border-radius: 8px; background: #fff;
font-size: 12.5px; font-weight: 600; font-family: inherit; color: #525860; cursor: pointer;
}
.pj-fb-select:hover { background: #f6f7f8; }
.pj-fb-select.is-set { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); }
.pj-fb-count { font-size: 12.5px; font-weight: 700; color: var(--pj-accent-dark); }
.pj-fb-count[hidden], .pj-fb-reset[hidden] { display: none; }
.pj-fb-reset { border: none; background: transparent; color: var(--pj-ink-soft); font-size: 12.5px; font-weight: 600; cursor: pointer; text-decoration: underline; padding: 0 4px; }
.pj-fb-reset:hover { color: var(--pj-ink); }
/* ── 업무 팝업 — 팔로워 ── */
.pj-followers { flex-wrap: wrap; row-gap: 6px; padding: 5px 0; }
.pj-follower-chips { display: flex; flex-wrap: wrap; gap: 6px; }
.pj-follower-chip {
display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 4px 0 4px;
border-radius: 999px; background: #f1f2f4; font-size: 12.5px; font-weight: 600; color: var(--pj-ink);
}
.pj-follower-chip .pj-gicon-sm { font-size: 18px; }
.pj-follower-x {
border: none; background: transparent; color: #8a9099; cursor: pointer; font-size: 14px; line-height: 1;
width: 18px; height: 18px; border-radius: 50%; padding: 0; display: inline-flex; align-items: center; justify-content: center;
}
.pj-follower-x:hover { background: #dfe2e6; color: #1e1f21; }
.pj-follower-add {
width: 26px; height: 26px; border-radius: 50%; border: 1px dashed #b8bec6; background: #fff;
color: #6b6f76; font-size: 16px; line-height: 1; cursor: pointer; padding: 0; display: inline-flex; align-items: center; justify-content: center;
}
.pj-follower-add:hover { border-color: var(--pj-accent); color: var(--pj-accent); }
.pj-follow-toggle {
margin-left: auto; height: 26px; padding: 0 10px; border-radius: 999px; border: 1px solid var(--pj-border);
background: #fff; font-size: 12px; font-weight: 700; color: #525860; cursor: pointer;
}
.pj-follow-toggle:hover { background: #f6f7f8; }
.pj-follow-toggle.is-on { background: var(--pj-accent-tint); border-color: var(--pj-accent); color: var(--pj-accent-dark); }
+352 -8
View File
@@ -946,10 +946,32 @@
},
];
// 검색어·마감·우선순위(필터 바) — 상태(진행 중/완료/전체)는 위 탭이 맡는다.
const mtFilter = Object.assign({}, TASK_FILTER_DEFAULT);
const mtQ = el("pj-mt-q"), mtDue = el("pj-mt-due"), mtPri = el("pj-mt-priority");
try {
const saved = JSON.parse(localStorage.getItem("pj_mt_filter") || "{}");
["q", "due", "priority"].forEach(function (k) { if (saved[k]) mtFilter[k] = saved[k]; });
} catch (_) {}
function saveMtFilter() {
try { localStorage.setItem("pj_mt_filter", JSON.stringify({ q: mtFilter.q, due: mtFilter.due, priority: mtFilter.priority })); } catch (_) {}
render();
}
if (mtQ) {
mtQ.value = mtFilter.q; mtDue.value = mtFilter.due; mtPri.value = mtFilter.priority;
let qt = null;
mtQ.addEventListener("input", function () {
clearTimeout(qt);
qt = setTimeout(function () { mtFilter.q = mtQ.value.trim(); saveMtFilter(); }, 150);
});
mtDue.addEventListener("change", function () { mtFilter.due = mtDue.value; saveMtFilter(); });
mtPri.addEventListener("change", function () { mtFilter.priority = mtPri.value; saveMtFilter(); });
}
function passFilter(t) {
if (filter === "open") return !t.completed_at;
if (filter === "done") return !!t.completed_at;
return true;
if (filter === "open" && t.completed_at) return false;
if (filter === "done" && !t.completed_at) return false;
return taskMatchesFilter(t, mtFilter, me, today);
}
// 최상위 업무만 — 하위 업무(parent_task_id 있음)는 render() 에서 해당
@@ -1235,11 +1257,82 @@
// 프로젝트 양쪽에서 각각 한 번씩 나온다 — 그래야 각 화면에 다 보인다).
// "전체" 모드는 원 소속(context_project_id === project_id)만 세어 중복을 없앤다.
let viewScope = "project";
function visibleTasks() {
// 필터 바(#pj-filterbar) 상태 — 프로젝트별로 이 브라우저에 기억한다.
const FILTER_KEY = "pj_filter_" + projectId;
let taskFilter = Object.assign({}, TASK_FILTER_DEFAULT);
try { Object.assign(taskFilter, JSON.parse(localStorage.getItem(FILTER_KEY) || "{}")); } catch (_) {}
const todayIso = data.today || localIso(new Date());
function scopeTasks() {
return viewScope === "project"
? tasks.filter(function (t) { return t.context_project_id === projectId; })
: tasks.filter(function (t) { return t.context_project_id === t.project_id; });
}
// 모든 뷰가 이 함수로 업무를 받는다 — 스코프 → 필터 → 정렬 순.
function visibleTasks() {
const rows = scopeTasks().filter(function (t) { return taskMatchesFilter(t, taskFilter, me, todayIso); });
return sortTasksBy(rows, taskFilter.sort);
}
// 보드 카드 순서 바꾸기는 "기본 정렬 + 필터 없음"일 때만 — 가려진 카드가 있거나
// 다른 기준으로 정렬돼 있으면 놓은 자리가 실제 순서와 어긋난다(아사나도 같다).
function manualOrderAllowed() {
return taskFilter.sort === "manual" && !taskFilterActive(taskFilter);
}
const FB = {
q: el("pj-fb-q"), status: el("pj-fb-status"), assignee: el("pj-fb-assignee"),
due: el("pj-fb-due"), priority: el("pj-fb-priority"), sort: el("pj-fb-sort"),
count: el("pj-fb-count"), reset: el("pj-fb-reset"),
};
// 담당자 선택지 = 이 프로젝트 멤버 + 지금 목록에 나오는 담당자(전체 스코프 대비).
function fillAssigneeFilter() {
if (!FB.assignee) return;
const emails = [];
members.forEach(function (m) { const e = (m.user_email || "").toLowerCase(); if (e && emails.indexOf(e) < 0) emails.push(e); });
scopeTasks().forEach(function (t) { const e = (t.assignee_email || "").toLowerCase(); if (e && emails.indexOf(e) < 0) emails.push(e); });
if (taskFilter.assignee.indexOf("@") > 0 && emails.indexOf(taskFilter.assignee) < 0) emails.push(taskFilter.assignee);
emails.sort(function (a, b) { return idOf(a).localeCompare(idOf(b)); });
FB.assignee.innerHTML =
'<option value="all">담당자: 전체</option><option value="me">나</option><option value="none">담당자 없음</option>' +
emails.map(function (e) { return '<option value="' + escapeHtml(e) + '">' + escapeHtml(idOf(e)) + "</option>"; }).join("");
FB.assignee.value = taskFilter.assignee;
}
function updateFilterSummary() {
if (!FB.count) return;
const active = taskFilterActive(taskFilter);
if (active) {
FB.count.textContent = visibleTasks().length + " / " + scopeTasks().length + "건";
}
FB.count.hidden = !active;
FB.reset.hidden = !(active || taskFilter.sort !== "manual");
Object.keys(FB).forEach(function (k) {
if (FB[k] && FB[k].tagName === "SELECT") FB[k].classList.toggle("is-set", FB[k].value !== TASK_FILTER_DEFAULT[k]);
});
if (FB.q) FB.q.parentNode.classList.toggle("is-set", !!taskFilter.q);
}
function applyFilterChange() {
try { localStorage.setItem(FILTER_KEY, JSON.stringify(taskFilter)); } catch (_) {}
refreshActiveView();
}
if (FB.q) {
FB.q.value = taskFilter.q;
["status", "due", "priority", "sort"].forEach(function (k) { FB[k].value = taskFilter[k]; });
fillAssigneeFilter();
let qTimer = null;
FB.q.addEventListener("input", function () {
clearTimeout(qTimer);
qTimer = setTimeout(function () { taskFilter.q = FB.q.value.trim(); applyFilterChange(); }, 150);
});
FB.q.addEventListener("keydown", function (e) { if (e.key === "Escape") { FB.q.value = ""; taskFilter.q = ""; applyFilterChange(); } });
["status", "assignee", "due", "priority", "sort"].forEach(function (k) {
FB[k].addEventListener("change", function () { taskFilter[k] = FB[k].value; applyFilterChange(); });
});
FB.reset.addEventListener("click", function () {
taskFilter = Object.assign({}, TASK_FILTER_DEFAULT);
FB.q.value = "";
["status", "assignee", "due", "priority", "sort"].forEach(function (k) { FB[k].value = taskFilter[k]; });
applyFilterChange();
});
}
// ── 뷰 토글 ──
const tabs = el("pj-view-tabs");
@@ -1280,7 +1373,9 @@
scopeToggle.querySelectorAll("[data-scope]").forEach(function (b) {
b.classList.toggle("is-active", b === btn);
});
fillAssigneeFilter(); // 스코프가 바뀌면 담당자 후보도 달라진다
renderView(currentView);
updateFilterSummary();
});
}
if (moveScopeHighlight) moveScopeHighlight(false);
@@ -2083,6 +2178,10 @@
const t = tasks.find(function (x) { return x.id === taskId; });
if (!t) return;
if (t.stage_id === stageId) {
if (!manualOrderAllowed()) {
showToast("필터·정렬을 쓰는 중에는 카드 순서를 바꿀 수 없습니다. (정렬: 기본, 필터 초기화 후 가능)", "error");
return;
}
// 같은 세션 안에서 카드 위치만 이동 — 세션 이동이 아니라 정렬.
const currentOrder = tasks.filter(function (x) { return x.stage_id === stageId; });
const idx = cardDropIndex(body, e.clientY, taskId);
@@ -2668,6 +2767,7 @@
// 모든 뷰 + 좌측 트리 클라이언트 재렌더(새로고침 없음).
renderView(currentView);
if (typeof renderTree === "function") renderTree();
updateFilterSummary();
}
// 업무 우클릭 메뉴 공용 항목 — 보드 카드·리스트 행·달력 막대·타임라인
@@ -2794,11 +2894,71 @@
if (e.key === "Escape" && !taskModal.hidden) { e.preventDefault(); attemptCloseTaskModal(); }
});
// ── 팔로워 (아사나의 협업자) — 완료·댓글 알림을 받는 사람 ──
// 저장 버튼과 무관하게 누르는 즉시 서버에 반영된다.
const followersRow = el("pj-followers-row");
let followersTask = null;
let followers = [];
function renderFollowers() {
const box = el("pj-follower-chips");
if (!box) return;
box.innerHTML = followers.map(function (e) {
return '<span class="pj-follower-chip" data-tip="' + escapeHtml(e) + '">' +
avatarHtml(e, "pj-gicon-sm") + '<span class="pj-follower-name">' + escapeHtml(idOf(e)) + "</span>" +
'<button type="button" class="pj-follower-x" data-email="' + escapeHtml(e) + '" title="팔로워에서 빼기">×</button></span>';
}).join("") || '<span class="pj-muted-sm">없음</span>';
box.querySelectorAll(".pj-follower-x").forEach(function (b) {
b.addEventListener("click", function () { setFollower(b.dataset.email, false); });
});
const followingMe = followers.indexOf(me) >= 0;
const tog = el("pj-follow-toggle");
tog.textContent = followingMe ? "팔로우 취소" : "팔로우";
tog.classList.toggle("is-on", followingMe);
}
async function setFollower(email, on) {
if (!followersTask) return;
const tid = followersTask.id;
try {
const res = on
? await api("POST", "/project/api/tasks/" + tid + "/followers", { email: email })
: await api("DELETE", "/project/api/tasks/" + tid + "/followers/" + encodeURIComponent(email));
if (!followersTask || followersTask.id !== tid) return; // 그 사이 다른 업무를 열었다
followers = res.followers || [];
renderFollowers();
} catch (e) { showToast("팔로워 변경 실패: " + e.message, "error"); }
}
function showFollowers(task, list) {
followersTask = task;
if (!followersRow) return;
if (!task || list == null) { followersRow.hidden = true; return; } // 새 업무 / 008 미적용
followers = list.map(function (e) { return String(e).toLowerCase(); });
followersRow.hidden = false;
renderFollowers();
}
if (followersRow) {
el("pj-follow-toggle").addEventListener("click", function () {
setFollower(me, followers.indexOf(me) < 0);
});
el("pj-follower-add").addEventListener("click", async function (e) {
if (!followersTask) return;
const r = e.currentTarget.getBoundingClientRect();
let list = [];
try { list = await membersOfProject(followersTask.project_id); } catch (_) {}
const cands = list.map(function (m) { return (m.user_email || "").toLowerCase(); })
.filter(function (em) { return em && followers.indexOf(em) < 0; });
if (!cands.length) { showToast("추가할 수 있는 멤버가 없습니다."); return; }
showContextMenu(r.left, r.bottom + 4, cands.map(function (em) {
return { label: idOf(em), onClick: function () { setFollower(em, true); } };
}));
});
}
async function loadTaskExtras(task) {
if (!task || (!subtaskBlock && !linksBlock)) return;
try {
const res = await api("GET", "/project/api/tasks/" + task.id);
const detail = res.task;
if (currentTaskId === task.id) showFollowers(task, detail.followers);
if (subtaskBlock) {
subtaskBlock.setContext({ taskId: task.id, projectId: task.project_id, canDelete: canDelete });
subtaskBlock.render(detail.subtasks || []);
@@ -2831,9 +2991,14 @@
try { list = (await api("GET", "/project/api/projects/" + projId + "/members")).members || []; }
catch (_) { list = []; }
}
sel.innerHTML = '<option value="">담당자 없음</option>' + list.map(function (m) {
const name = idOf(m.user_email);
return '<option value="' + m.user_email + '" data-name="' + escapeHtml(name) + '">' + escapeHtml(name) + "</option>";
const emails = list.map(function (m) { return m.user_email; });
// 지금 담당자가 멤버 목록에 없어도(프로젝트를 만든 owner, 멤버에서 빠진 사람)
// 선택지에 넣는다 — 없으면 칸이 비고, 저장하면 담당자가 지워졌다.
const cur = (currentEmail || "").toLowerCase();
if (cur && !emails.some(function (e) { return (e || "").toLowerCase() === cur; })) emails.push(currentEmail);
sel.innerHTML = '<option value="">담당자 없음</option>' + emails.map(function (e) {
const name = idOf(e);
return '<option value="' + escapeHtml(e) + '" data-name="' + escapeHtml(name) + '">' + escapeHtml(name) + "</option>";
}).join("");
sel.value = currentEmail || "";
}
@@ -2861,8 +3026,9 @@
const shareBtn = el("pj-share-task");
if (shareBtn) shareBtn.hidden = !task;
if (task) setCompleteBtn(!!task.completed_at);
// 댓글·첨부·하위업무·연결은 기존 업무 편집 시에만
// 댓글·첨부·하위업무·연결·팔로워는 기존 업무 편집 시에만
currentTaskId = task ? task.id : null;
showFollowers(null, null); // 상세를 받으면(loadTaskExtras) 다시 그린다
el("pj-attach-block").hidden = !task;
el("pj-comment-block").hidden = !task;
if (subtaskBlock) el("pj-subtask-block").hidden = !task;
@@ -3015,6 +3181,11 @@
inp.value = "";
clearMentions(inp);
loadComments(currentTaskId);
// 댓글을 달면(서버가) 자동 팔로우 — 화면의 팔로워 목록도 맞춘다.
if (followersTask && !followersRow.hidden && followers.indexOf(me) < 0) {
followers.push(me);
renderFollowers();
}
} catch (e) { alert("등록 실패: " + e.message); }
}
attachMentionInput(el("pj-comment-input"));
@@ -3515,6 +3686,7 @@
// 최초 렌더 — 아사나처럼 프로젝트에 들어오면 보드(세션)가 기본 화면이다
// (달력을 보던 중이었다면 그 기억된 뷰를 그린다, 위 VIEW_KEY 복원 참고).
renderView(currentView);
updateFilterSummary(); // 기억된 필터가 있으면 개수·초기화 버튼 표시
// 사이드 트리에서 업무 클릭(?task=ID)으로 들어오면 해당 업무 모달 자동 열기.
// 단, 처리 후 URL 에서 task 파라미터를 제거한다 — 같은 페이지에 머무는 동안
@@ -3555,6 +3727,7 @@
stages = snap.stages || [];
stagesByProject[projectId] = stages;
members = snap.members || [];
fillAssigneeFilter();
renderMemberList();
refreshActiveView();
refreshMyOpenBadge();
@@ -4038,6 +4211,176 @@
return String(email == null ? "" : email).split("@")[0];
}
// ════════════════════════════════════════════════════════════
// 업무 필터·정렬 (프로젝트 화면 필터 바 + 내 업무 화면 공용)
// f = { q, status, assignee, due, priority, sort }
// status : all | open | done
// assignee : all | me | none | <email>
// due : all | overdue | today | week | none
// priority : all | high | normal | low
// sort : manual | due | priority | title | assignee | created
// 서버 재조회 없이 이미 받은 업무 목록에서 거른다.
// ════════════════════════════════════════════════════════════
const TASK_FILTER_DEFAULT = { q: "", status: "all", assignee: "all", due: "all", priority: "all", sort: "manual" };
function localIso(d) {
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
// "이번 주" 마감 = 오늘부터 이번 주 일요일까지(월~일을 한 주로 본다).
function endOfWeekIso(todayIso) {
const d = new Date(todayIso + "T00:00:00");
const add = (7 - d.getDay()) % 7; // 일요일=0 → 오늘이 일요일이면 오늘까지
d.setDate(d.getDate() + add);
return localIso(d);
}
// 설명 HTML → 검색용 평문(업무 객체에 캐시 — 설명이 바뀌면 다시 만든다).
function taskSearchText(t) {
if (t._searchSrc !== t.description) {
t._searchSrc = t.description;
t._searchDesc = String(t.description || "").replace(/<[^>]*>/g, " ")
.replace(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")
.toLowerCase();
}
return t._searchDesc;
}
function taskFilterActive(f) {
return !!(f.q || f.status !== "all" || f.assignee !== "all" || f.due !== "all" || f.priority !== "all");
}
function taskMatchesFilter(t, f, me, todayIso) {
if (f.status === "open" && t.completed_at) return false;
if (f.status === "done" && !t.completed_at) return false;
const a = (t.assignee_email || "").toLowerCase();
if (f.assignee === "me" && a !== me) return false;
if (f.assignee === "none" && a) return false;
if (f.assignee !== "all" && f.assignee !== "me" && f.assignee !== "none" && a !== f.assignee) return false;
if (f.priority !== "all" && (t.priority || "normal") !== f.priority) return false;
const due = t.due_date ? t.due_date.slice(0, 10) : "";
if (f.due === "none" && due) return false;
if (f.due === "overdue" && !(due && due < todayIso && !t.completed_at)) return false;
if (f.due === "today" && due !== todayIso) return false;
if (f.due === "week" && !(due && due >= todayIso && due <= endOfWeekIso(todayIso))) return false;
if (f.q) {
const q = f.q.toLowerCase();
const hay = [t.title, idOf(a), t.project_name, t.stage_name].join(" ").toLowerCase();
if (hay.indexOf(q) < 0 && taskSearchText(t).indexOf(q) < 0) return false;
}
return true;
}
const PRIORITY_RANK = { high: 0, normal: 1, low: 2 };
function sortTasksBy(rows, sort) {
if (!sort || sort === "manual") return rows;
const key = {
due: function (t) { return t.due_date || "9999-99-99"; },
priority: function (t) { return PRIORITY_RANK[t.priority || "normal"]; },
title: function (t) { return (t.title || "").toLowerCase(); },
assignee: function (t) { return t.assignee_email ? idOf(t.assignee_email).toLowerCase() : "￿"; },
created: function (t) { return -t.id; },
}[sort];
if (!key) return rows;
return rows.slice().sort(function (a, b) {
const va = key(a), vb = key(b);
if (va < vb) return -1;
if (va > vb) return 1;
return (a.due_date || "9999").localeCompare(b.due_date || "9999") || a.id - b.id;
});
}
// ── 좌측 사이드바 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트 ──
function initGlobalSearch() {
const input = el("pj-global-search");
const box = el("pj-search-results");
if (!input || !box) return;
let timer = null, seq = 0, items = [], active = -1;
function close() { box.hidden = true; active = -1; }
// 사이드바는 자체 스크롤 영역이라 안에 두면 결과창이 잘린다 — 화면 기준(fixed)으로 띄운다.
function place() {
const r = input.getBoundingClientRect();
box.style.left = r.left + "px";
box.style.top = (r.bottom + 6) + "px";
box.style.width = Math.max(380, r.width) + "px";
box.style.maxHeight = Math.max(200, window.innerHeight - r.bottom - 24) + "px";
}
function show() { place(); box.hidden = false; }
window.addEventListener("resize", function () { if (!box.hidden) place(); });
function highlight(text, q) {
const s = String(text || "");
const i = s.toLowerCase().indexOf(q.toLowerCase());
if (!q || i < 0) return escapeHtml(s);
return escapeHtml(s.slice(0, i)) + "<mark>" + escapeHtml(s.slice(i, i + q.length)) + "</mark>" + escapeHtml(s.slice(i + q.length));
}
function go(r) { location.href = "/project/t/" + r.id; }
function setActive(i) {
const rows = box.querySelectorAll(".pj-sr-item");
rows.forEach(function (r, k) { r.classList.toggle("is-active", k === i); });
active = i;
if (rows[i]) rows[i].scrollIntoView({ block: "nearest" });
}
const MATCH_LABEL = { title: "제목", description: "설명", comment: "댓글" };
function render(q) {
if (!items.length) {
box.innerHTML = '<div class="pj-sr-empty">"' + escapeHtml(q) + '" 검색 결과가 없습니다.</div>';
show();
return;
}
box.innerHTML = items.map(function (r, i) {
return '<div class="pj-sr-item' + (r.completed ? " is-done" : "") + '" data-i="' + i + '">' +
'<div class="pj-sr-title">' +
(r.completed ? '<span class="material-symbols-outlined pj-sr-check">check_circle</span>' : "") +
(r.parent_title ? '<span class="pj-sr-parent">' + escapeHtml(r.parent_title) + " ›</span> " : "") +
highlight(r.title, q) + "</div>" +
'<div class="pj-sr-meta"><span style="color:' + escapeHtml(r.project_color) + '">●</span> ' +
escapeHtml(r.project_name) +
(r.assignee_email ? " · " + escapeHtml(idOf(r.assignee_email)) : "") +
(r.due_date ? " · 마감 " + escapeHtml(fmtDateKr(r.due_date)) : "") + "</div>" +
(r.snippet && r.match !== "title"
? '<div class="pj-sr-snippet"><span class="pj-sr-where">' + MATCH_LABEL[r.match] + "</span> " + highlight(r.snippet, q) + "</div>"
: "") +
"</div>";
}).join("");
show();
box.querySelectorAll(".pj-sr-item").forEach(function (row) {
row.addEventListener("mousedown", function (e) { e.preventDefault(); go(items[+row.dataset.i]); });
});
active = -1;
}
async function search() {
const q = input.value.trim();
if (q.length < 2) { items = []; close(); return; }
const my = ++seq;
try {
const res = await api("GET", "/project/api/search?q=" + encodeURIComponent(q));
if (my !== seq) return; // 더 늦게 친 검색어의 결과가 이미 왔다
items = res.results || [];
render(q);
} catch (e) {
if (my === seq) { box.innerHTML = '<div class="pj-sr-empty">검색 실패: ' + escapeHtml(e.message) + "</div>"; show(); }
}
}
input.addEventListener("input", function () { clearTimeout(timer); timer = setTimeout(search, 250); });
input.addEventListener("focus", function () { if (items.length && input.value.trim().length >= 2) show(); });
input.addEventListener("blur", function () { setTimeout(close, 150); });
input.addEventListener("keydown", function (e) {
if (e.key === "ArrowDown" && items.length) { e.preventDefault(); setActive(Math.min(items.length - 1, active + 1)); }
else if (e.key === "ArrowUp" && items.length) { e.preventDefault(); setActive(Math.max(0, active - 1)); }
else if (e.key === "Enter") {
e.preventDefault();
if (active >= 0 && items[active]) go(items[active]);
else if (items.length === 1) go(items[0]);
else { clearTimeout(timer); search(); }
} else if (e.key === "Escape") { close(); input.blur(); }
});
// 어디서든 "/" 를 누르면 검색창으로(입력칸·편집 중일 땐 제외) — 아사나 단축키와 같다.
document.addEventListener("keydown", function (e) {
if (e.key !== "/" || e.ctrlKey || e.metaKey || e.altKey) return;
const t = e.target;
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
e.preventDefault();
input.focus();
input.select();
});
}
function escapeHtml(s) {
return String(s == null ? "" : s)
.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
@@ -4301,6 +4644,7 @@
initInbox();
initMentionInbox();
initLiveRefresh();
initGlobalSearch();
initScrollIndicators();
initHoverTips();
});