feat(project): add cell moves and width menus
This commit is contained in:
@@ -2275,8 +2275,13 @@ class ProjectStore:
|
||||
def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None:
|
||||
m = store.validate_goal_month(month, allow_year=True)
|
||||
text = store.validate_goal_text(body)
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone():
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
# 빈 대상 칸을 포함해 일반 저장·이동·병합이 같은 영역 잠금으로 직렬화된다.
|
||||
area = conn.execute(
|
||||
"SELECT a.id AS area_id FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id "
|
||||
"WHERE r.id = %s FOR UPDATE OF a", (row_id,),
|
||||
).fetchone()
|
||||
if not area:
|
||||
raise KeyError(row_id)
|
||||
halves = self._table_exists(conn, "goal_cell_merges")
|
||||
if m > 12 and not halves:
|
||||
@@ -2285,7 +2290,7 @@ class ProjectStore:
|
||||
raise store.GoalMigration017Needed()
|
||||
if halves:
|
||||
# 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장
|
||||
area_id = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()["area_id"]
|
||||
area_id = area["area_id"]
|
||||
ids, merges, _ = self._area_geometry(conn, int(area_id))
|
||||
if self._covered_by(merges, ids.index(row_id), store.GOAL_COL_ORDER.index(m)):
|
||||
raise ValueError("병합된 칸입니다. 새로고침해 주세요.")
|
||||
@@ -2299,6 +2304,77 @@ class ProjectStore:
|
||||
(row_id, m, text, store.norm_str(updated_by, lower=True)),
|
||||
)
|
||||
|
||||
def move_goal_cell(
|
||||
self, *, source_row: Any, source_month: Any, target_row: Any, target_month: Any,
|
||||
source_body: str, target_body: str, body: str, updated_by: str = "",
|
||||
) -> str:
|
||||
"""같은 연도 안에서 셀의 내용·서식을 이동한다. 두 값의 비교와 이동은 한 트랜잭션.
|
||||
|
||||
병합 시작 칸끼리도 내용만 이동하며 병합 배치·영역 색·열 너비는 유지한다.
|
||||
응답만 유실된 요청을 다시 보내면 이미 같은 이동이 완료된 상태는 성공으로 돌려준다.
|
||||
"""
|
||||
try:
|
||||
sr, tr = int(source_row), int(target_row)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("이동할 셀이 올바르지 않습니다.")
|
||||
sm = store.validate_goal_month(source_month, allow_year=True)
|
||||
tm = store.validate_goal_month(target_month, allow_year=True)
|
||||
if sr <= 0 or tr <= 0 or (sr, sm) == (tr, tm):
|
||||
raise ValueError("서로 다른 두 셀을 골라 주세요.")
|
||||
expected_source, expected_target = store.validate_goal_text(source_body), store.validate_goal_text(target_body)
|
||||
moved = store.validate_goal_text(body)
|
||||
if not expected_source or not moved or store.goal_text_plain(moved).strip() != store.goal_text_plain(expected_source).strip():
|
||||
raise ValueError("원본 내용과 이동할 내용이 일치하지 않습니다.")
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
rows = conn.execute(
|
||||
"SELECT r.id, r.area_id, a.year FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id "
|
||||
"WHERE r.id = ANY(%s)", ([sr, tr],),
|
||||
).fetchall()
|
||||
by_id = {int(r["id"]): r for r in rows}
|
||||
if sr not in by_id or tr not in by_id:
|
||||
raise KeyError(sr if sr not in by_id else tr)
|
||||
if by_id[sr]["year"] != by_id[tr]["year"]:
|
||||
raise ValueError("같은 연도의 셀로만 이동할 수 있습니다.")
|
||||
areas = sorted({int(r["area_id"]) for r in rows})
|
||||
# 교차 영역 이동도 같은 순서로 잠가 교착을 피하고, 행 삭제도 함께 차단한다.
|
||||
conn.execute("SELECT id FROM goal_areas WHERE id = ANY(%s) ORDER BY id FOR UPDATE", (areas,)).fetchall()
|
||||
locked = conn.execute(
|
||||
"SELECT id, area_id FROM goal_rows WHERE id = ANY(%s) ORDER BY id FOR UPDATE", ([sr, tr],),
|
||||
).fetchall()
|
||||
if len(locked) != len(by_id):
|
||||
raise KeyError("이동할 줄이 삭제되었습니다.")
|
||||
halves = self._table_exists(conn, "goal_cell_merges")
|
||||
if (sm > 12 or tm > 12) and not halves:
|
||||
raise store.GoalMigration014Needed()
|
||||
if (sm in store.GOAL_Q_NEW or tm in store.GOAL_Q_NEW) and not self._goal_quarters(conn):
|
||||
raise store.GoalMigration017Needed()
|
||||
geometry = {a: self._area_geometry(conn, a) for a in areas} if halves else {}
|
||||
for rid, month in ((sr, sm), (tr, tm)):
|
||||
if halves:
|
||||
ids, merges, _ = geometry[int(by_id[rid]["area_id"])]
|
||||
if rid not in ids or self._covered_by(merges, ids.index(rid), store.GOAL_COL_ORDER.index(month)):
|
||||
raise store.GoalCellConflict("병합 배치가 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.")
|
||||
cells = conn.execute(
|
||||
"SELECT row_id, month, body FROM goal_cells "
|
||||
"WHERE (row_id = %s AND month = %s) OR (row_id = %s AND month = %s) FOR UPDATE",
|
||||
(sr, sm, tr, tm),
|
||||
).fetchall()
|
||||
values = {(int(c["row_id"]), int(c["month"])): store.validate_goal_text(c["body"]) for c in cells}
|
||||
source, target = values.get((sr, sm), ""), values.get((tr, tm), "")
|
||||
if not source and target == moved:
|
||||
return moved
|
||||
if source != expected_source or target != expected_target:
|
||||
raise store.GoalCellConflict("원본 또는 대상 내용이 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.")
|
||||
conn.execute(
|
||||
"INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s) "
|
||||
"ON CONFLICT (row_id, month) DO UPDATE "
|
||||
"SET body = EXCLUDED.body, updated_by = EXCLUDED.updated_by, updated_at = now()",
|
||||
(tr, tm, moved, store.norm_str(updated_by, lower=True)),
|
||||
)
|
||||
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (sr, sm))
|
||||
return moved
|
||||
|
||||
# ── 엑셀식 사각형 병합 ─────────────────────────────────────────
|
||||
@staticmethod
|
||||
def _column_exists(conn: Any, table: str, column: str) -> bool:
|
||||
|
||||
@@ -2598,6 +2598,8 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_016_MSG)
|
||||
except store.GoalMigration017Needed:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_017_MSG)
|
||||
except store.GoalCellConflict as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
except UndefinedTable:
|
||||
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
|
||||
except KeyError:
|
||||
@@ -2807,6 +2809,22 @@ def api_set_goal_cell(
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/api/goals/cells/move")
|
||||
def api_move_goal_cell(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""내용·글자 서식만 원자적으로 이동. 원본·대상의 예상값이 바뀌면 409, 병합 배치는 유지."""
|
||||
user = _require_admin(request)
|
||||
st = _db_or_503(request)
|
||||
if any(not isinstance(payload.get(k), str) for k in ("source_body", "target_body", "body")):
|
||||
raise HTTPException(status_code=400, detail="이동할 내용과 두 칸의 현재 내용을 보내 주세요.")
|
||||
body = _goal_call(
|
||||
st.move_goal_cell, source_row=payload.get("source_row"), source_month=payload.get("source_month"),
|
||||
target_row=payload.get("target_row"), target_month=payload.get("target_month"),
|
||||
source_body=payload["source_body"], target_body=payload["target_body"], body=payload["body"],
|
||||
updated_by=user["email"],
|
||||
)
|
||||
return JSONResponse({"ok": True, "body": body})
|
||||
|
||||
|
||||
@router.post("/api/goals/areas/{area_id}/merge")
|
||||
def api_merge_goal_rect(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""엑셀식 병합 {row_from, row_to(줄 id), col_from, col_to(칸 번호 0·1~12·13~16)} — 같은 영역 안 사각형,
|
||||
|
||||
@@ -397,6 +397,10 @@ class GoalMigration017Needed(RuntimeError):
|
||||
"""2·4분기 글 칸(15·16)은 마이그레이션 017(분기) 뒤에만 된다."""
|
||||
|
||||
|
||||
class GoalCellConflict(RuntimeError):
|
||||
"""셀 이동 전에 다른 창에서 원본 또는 대상 내용이 바뀜."""
|
||||
|
||||
|
||||
GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간
|
||||
# 분기 글 칸(2026-10-01 상·하반기 → 1~4분기). 칸 번호는 예전 반기 칸을 그대로 이어 쓴다 — 데이터 옮기기 없이
|
||||
# 예전 상반기 글(13)은 1분기, 하반기 글(14)은 3분기에 보인다. 2분기(15)·4분기(16)는 마이그레이션 017 뒤에 저장.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -296,5 +296,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -208,6 +208,7 @@
|
||||
<div class="pj-goal-foot">
|
||||
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 글자를 드래그해 선택하면 선택한 셀 상단에서 12색 견본·크기 2px 증감·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다. 모든 행의 셀 오른쪽 경계를 끌어 열 너비를 조절하고, 더블클릭하면 그 열의 가장 긴 문단에 맞춥니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
|
||||
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함). 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 끌면 내용과 서식이 함께 이동합니다(대상에 글이 있으면 덮어쓰기 확인, Esc로 취소).
|
||||
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
|
||||
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
|
||||
</div>
|
||||
@@ -223,5 +224,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003c" defer></script>
|
||||
<script src="/static/project.js?v=20261003g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261002d" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -100,6 +100,8 @@
|
||||
<span class="pjh-ui">서식 초기화</span>는 선택한 글자를 기본 서식으로 되돌리며 내용은 유지합니다. 서식도 자동으로 저장됩니다. 색상은 12색의 네모 견본에서 고릅니다.
|
||||
<b>모든 행의 셀 오른쪽 경계</b>를 끌어 열 너비를 조절하고, 더블클릭하면 <b>그 열의 가장 긴 문단에 맞춰</b> 자동으로 조절합니다.
|
||||
직접 넣은 줄바꿈은 유지하며 글자 크기·굵기·여백도 반영합니다. 병합 칸에서는 다른 열 너비를 유지하고 오른쪽 끝 열만 맞춥니다. 너비는 내 브라우저에 기억됩니다.
|
||||
셀을 <b>우클릭</b>하면 <span class="pjh-ui">현재 열 너비 자동 맞춤</span>·<span class="pjh-ui">전체 열 너비 자동 맞춤</span>을 사용할 수 있습니다. 전체 맞춤에는 접힌 월 열도 포함됩니다.
|
||||
관리자는 글 칸 하나를 클릭한 뒤 <b>위·아래·왼쪽 테두리</b>를 잡아 다른 글 칸으로 끌면 <b>내용과 글자 서식을 함께 이동</b>할 수 있습니다. 대상에 글이 있으면 덮어쓰기를 확인하며, <kbd>Esc</kbd>로 끌기를 취소합니다.
|
||||
<b>행 높이는 가장 높은 글 칸에 맞춰</b> 자동으로 늘어나거나 줄어들며, 위·아래 여백은 각각 6px입니다. 짧은 글도 같은 위치에서 상단 정렬됩니다.
|
||||
영역·줄 이름은 <b>눌러서 그 자리에서 고치고</b>(Enter 저장, Esc 취소),
|
||||
구역·항목 칸을 <b>우클릭</b>하거나 칸 오른쪽 위의 작은 <span class="pjh-ui">⋮</span> 버튼(마우스를 올리면 보임)을 눌러 색·순서·줄 추가·삭제를 합니다.
|
||||
@@ -108,7 +110,7 @@
|
||||
끌어 여러 칸을 고른 뒤 우클릭 → "셀 병합", 병합된 칸은 우클릭 → "병합 해제"(글은 왼쪽 위 칸에 남음).
|
||||
가로 병합은 같은 분기의 월 칸끼리만(연간·분기 칸은 세로로만) 되고, 칸들의 글은 순서대로 첫 칸에 모입니다.
|
||||
<br><b>저장이 안 되면</b>(네트워크 끊김 등) 칸 테두리가 빨갛게 되고 <b>쓴 글은 그대로 남습니다</b> — 다시 입력하거나 칸을 떠나면 다시 저장합니다.
|
||||
저장 안 된 칸이 있으면 줄·영역 추가·병합은 하지 않고 알려 주며, 그 상태로 페이지를 떠나려 하면 브라우저가 한 번 묻습니다.
|
||||
저장 안 된 칸이 있으면 줄·영역 추가·병합·셀 이동은 하지 않고 알려 주며, 그 상태로 페이지를 떠나려 하면 브라우저가 한 번 묻습니다.
|
||||
글은 내 브라우저에도 잠시 보관되어, 저장되지 못한 채 창이 닫혀도 다음에 열면 되살아납니다(그 사이 다른 사람이 같은 칸을 고쳤으면 되살리지 않음).</li>
|
||||
<li><b>주간 회의록</b>(목표 표의 월 이름) — <b>지난주 리뷰</b>는 언제나 바로 앞 주(7일 전 월~일) 회의록만 보여 줍니다. 그 주 회의록이 없으면
|
||||
"회의록 없음"으로 비워 두고, 몇 주 전 결과를 지난주처럼 보이지 않습니다. 회의록을 만드는 순서(다음 주를 먼저 만들어도)와 줄 이름 변경·순서 이동과
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -104,5 +104,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261003g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -496,5 +496,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261003g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003g" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -2349,6 +2349,17 @@ html.pj-goal-selecting .pj-goal-menu-btn { pointer-events: none; }
|
||||
box-shadow: inset 0 0 0 2px var(--pj-accent);
|
||||
background-image: linear-gradient(rgba(123, 104, 238, .12), rgba(123, 104, 238, .12));
|
||||
}
|
||||
.pj-goal-table td.pj-goal-texttd.is-goal-active { box-shadow: inset 0 0 0 2px var(--pj-accent); }
|
||||
.pj-goal-move-edge { display: none; position: absolute; z-index: 4; cursor: grab; }
|
||||
.is-goal-active > .pj-goal-move-edge { display: block; }
|
||||
.pj-goal-move-edge[data-edge="top"] { top: 0; left: 0; right: 0; height: 4px; }
|
||||
.pj-goal-move-edge[data-edge="bottom"] { bottom: 0; left: 0; right: 0; height: 4px; }
|
||||
.pj-goal-move-edge[data-edge="left"] { top: 4px; bottom: 4px; left: 0; width: 4px; }
|
||||
.pj-goal-move-edge[data-edge="right"] { top: 4px; bottom: 4px; right: 0; width: 4px; }
|
||||
.pj-goal-table td.is-goal-moving { opacity: .55; }
|
||||
.pj-goal-table td.is-goal-move-target { box-shadow: inset 0 0 0 3px var(--pj-accent); background-image: linear-gradient(var(--pj-accent-tint), var(--pj-accent-tint)); }
|
||||
.pj-goal-table td.is-goal-move-saving { pointer-events: none; opacity: .65; }
|
||||
html.pj-goal-moving, html.pj-goal-moving * { cursor: grabbing !important; user-select: none !important; }
|
||||
|
||||
.pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; }
|
||||
|
||||
|
||||
+163
-7
@@ -352,6 +352,13 @@
|
||||
prune: prune, onBeforeUnload: onBeforeUnload,
|
||||
savedOf: function (f) { const s = states.get(f); return s ? s.saved : undefined; },
|
||||
failedOf: function (f) { const s = states.get(f); return !!(s && s.failed); },
|
||||
acceptSaved: function (f, value) {
|
||||
const s = states.get(f);
|
||||
if (!s) return;
|
||||
clearTimeout(s.timer); s.timer = null; s.saved = value; s.failed = false;
|
||||
writeDraft(f, s);
|
||||
if (cfg.onClear) cfg.onClear(f);
|
||||
},
|
||||
};
|
||||
}
|
||||
// 저장 실패 표시 — 칸 빨간 테두리 + 안내(입력한 내용은 지우지 않는다)
|
||||
@@ -8667,13 +8674,16 @@
|
||||
}
|
||||
addColHandles();
|
||||
function naturalCellWidth(td) {
|
||||
// 원본은 건드리지 않는다. 같은 셀 안의 숨은 복사본으로 폰트·부분 서식·여백을
|
||||
// 원본은 건드리지 않는다. 같은 표 구조의 숨은 복사본으로 폰트·부분 서식·여백을
|
||||
// 그대로 재되, 화면 폭에 따른 줄바꿈만 해제한다(직접 넣은 줄바꿈은 유지).
|
||||
const probe = document.createElement("div"), copy = td.cloneNode(true);
|
||||
const measureTable = table.cloneNode(false), section = td.parentElement.parentElement.cloneNode(false), row = td.parentElement.cloneNode(false);
|
||||
probe.style.cssText = "position:fixed;left:0;top:0;visibility:hidden;pointer-events:none;width:max-content;";
|
||||
probe.setAttribute("aria-hidden", "true");
|
||||
[measureTable, section, row].forEach(function (n) { n.removeAttribute("id"); });
|
||||
measureTable.style.cssText += ";width:max-content;table-layout:auto;";
|
||||
copy.classList.add("pj-goal-autofit-measure");
|
||||
copy.querySelectorAll(".pj-goal-colresize, .pj-goal-menu-btn").forEach(function (n) { n.remove(); });
|
||||
copy.querySelectorAll(".pj-goal-colresize, .pj-goal-menu-btn, .pj-goal-move-edge").forEach(function (n) { n.remove(); });
|
||||
// input의 현재 초안은 HTML 속성과 다를 수 있고, 기본 입력칸의 내재 너비도 제외한다.
|
||||
copy.querySelectorAll("input, textarea").forEach(function (n) {
|
||||
const text = document.createElement("span");
|
||||
@@ -8691,7 +8701,9 @@
|
||||
}
|
||||
});
|
||||
copy.style.setProperty("display", "block", "important");
|
||||
probe.appendChild(copy); td.appendChild(probe);
|
||||
row.appendChild(copy); section.appendChild(row); measureTable.appendChild(section); probe.appendChild(measureTable);
|
||||
// 접힌 분기의 display:none 셀도 전체 자동 맞춤 때 측정할 수 있다.
|
||||
pane.appendChild(probe);
|
||||
try { return Math.ceil(copy.getBoundingClientRect().width / uiZoom()) + 2; }
|
||||
finally { probe.remove(); }
|
||||
}
|
||||
@@ -8707,6 +8719,36 @@
|
||||
colW[key] = width;
|
||||
applyColW(); saveColW(); fitAll(); stickKpi();
|
||||
}
|
||||
function autoFitAllCols() {
|
||||
const cells = Array.from(table.querySelectorAll("[data-goal-cols]")).map(function (td) {
|
||||
return { keys: td.dataset.goalCols.split(","), width: naturalCellWidth(td) };
|
||||
});
|
||||
Object.keys(colDefault).forEach(function (key) { colW[key] = colLimit(key)[0]; });
|
||||
cells.filter(function (cell) { return cell.keys.length === 1; }).forEach(function (cell) {
|
||||
colW[cell.keys[0]] = Math.max(colW[cell.keys[0]], cell.width);
|
||||
});
|
||||
cells.filter(function (cell) { return cell.keys.length > 1; }).forEach(function (cell) {
|
||||
const sum = cell.keys.reduce(function (w, key) { return w + colW[key]; }, 0);
|
||||
if (cell.width > sum) colW[cell.keys[cell.keys.length - 1]] += cell.width - sum;
|
||||
});
|
||||
applyColW(); saveColW(); fitAll(); stickKpi();
|
||||
}
|
||||
function widthMenuItems(td) {
|
||||
const key = (td.dataset.goalCols || "").split(",").pop();
|
||||
if (!colDefault[key]) return [];
|
||||
return [
|
||||
{ label: "현재 열 너비 자동 맞춤", icon: menuIcon("fit_screen"), onClick: function () { autoFitCol(key); } },
|
||||
{ label: "전체 열 너비 자동 맞춤", icon: menuIcon("view_week"), onClick: autoFitAllCols },
|
||||
];
|
||||
}
|
||||
table.addEventListener("contextmenu", function (e) {
|
||||
const td = e.target.closest("th, td");
|
||||
if (!td || !table.contains(td)) return;
|
||||
// 관리자 업무 셀·이름 칸은 아래의 기존 편집 메뉴에 합쳐 표시한다.
|
||||
if (isAdmin && td.closest("tbody.pj-goal-area") &&
|
||||
(td.tagName === "TH" || table.dataset.halves === "true" || td.dataset.month === "0")) return;
|
||||
e.preventDefault(); showContextMenu(e.clientX, e.clientY, widthMenuItems(td));
|
||||
});
|
||||
table.addEventListener("mousedown", function (e) {
|
||||
const h = e.target.closest(".pj-goal-colresize");
|
||||
if (!h) return;
|
||||
@@ -8987,6 +9029,12 @@
|
||||
if (ta.dataset.bound) return;
|
||||
ta.dataset.bound = "1";
|
||||
if (ta.tagName !== "TEXTAREA") window.PJGoalText.attach(ta);
|
||||
["top", "right", "bottom", "left"].forEach(function (edge) {
|
||||
const handle = document.createElement("span");
|
||||
handle.className = "pj-goal-move-edge"; handle.dataset.edge = edge;
|
||||
handle.title = "끌어서 내용과 서식 이동"; handle.setAttribute("aria-hidden", "true");
|
||||
ta.closest("td").appendChild(handle);
|
||||
});
|
||||
const r = textSaver.track(ta, ta.value);
|
||||
if (r === "restored") restored++;
|
||||
else if (r === "conflict") conflict++;
|
||||
@@ -8999,6 +9047,110 @@
|
||||
}
|
||||
bindTexts(table);
|
||||
window.PJGoalText.init(table, el("pj-goal-format"));
|
||||
let moveBusy = false, moveClickUntil = 0;
|
||||
function goalCellTd(node) {
|
||||
const td = node && node.closest && node.closest("tbody.pj-goal-area td.pj-goal-texttd");
|
||||
return td && table.contains(td) && td.querySelector(".pj-goal-text") ? td : null;
|
||||
}
|
||||
function setMoveActive(td) {
|
||||
table.querySelectorAll(".is-goal-active").forEach(function (cell) { cell.classList.remove("is-goal-active"); });
|
||||
if (td) td.classList.add("is-goal-active");
|
||||
}
|
||||
function moveBody(editor) {
|
||||
// 열의 기본 서식도 현재 표시값으로 명시해 연간·분기의 굵기가 이동 뒤 달라지지 않게 한다.
|
||||
const cs = getComputedStyle(editor), rgb = cs.color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
|
||||
const defaults = { bold: Number(cs.fontWeight) >= 600 || cs.fontWeight === "bold", italic: cs.fontStyle === "italic",
|
||||
underline: (cs.textDecorationLine || "").includes("underline") };
|
||||
const size = Math.round(parseFloat(cs.fontSize)); if (size >= 10 && size <= 32) defaults.size = size;
|
||||
if (rgb) defaults.color = "#" + rgb.slice(1).map(function (v) { return Number(v).toString(16).padStart(2, "0"); }).join("");
|
||||
return window.PJGoalText.encode(window.PJGoalText.readRuns(editor).map(function (run) { return Object.assign({}, defaults, run); }));
|
||||
}
|
||||
function moveCell(sourceTd, targetTd) {
|
||||
if (moveBusy || sourceTd === targetTd) return;
|
||||
moveBusy = true;
|
||||
return withStruct(async function () {
|
||||
const source = sourceTd.querySelector(".pj-goal-text"), target = targetTd.querySelector(".pj-goal-text");
|
||||
const fields = [source, target], attrs = fields.map(function (n) { return n.getAttribute("contenteditable"); });
|
||||
try {
|
||||
if (!document.contains(sourceTd) || !document.contains(targetTd) || !source.value) return;
|
||||
fields.forEach(function (n) { n.setAttribute("contenteditable", "false"); n.closest("td").classList.add("is-goal-move-saving"); });
|
||||
await flushTexts();
|
||||
const sourceBody = source.value, targetBody = target.value;
|
||||
if (targetBody && !await confirm("대상 셀의 내용을 덮어쓸까요? 원본의 내용과 서식으로 바뀝니다.", { okText: "덮어쓰기", cancelText: "취소" })) return;
|
||||
const res = await api("POST", "/project/api/goals/cells/move", {
|
||||
source_row: source.dataset.row, source_month: source.dataset.month,
|
||||
target_row: target.dataset.row, target_month: target.dataset.month,
|
||||
source_body: sourceBody, target_body: targetBody, body: moveBody(source),
|
||||
});
|
||||
source.value = ""; target.value = res.body;
|
||||
textSaver.acceptSaved(source, ""); textSaver.acceptSaved(target, target.value);
|
||||
fit(source); fit(target); clearMergeSel(); setMoveActive(targetTd); flashSaved(targetTd);
|
||||
showToast("내용과 서식을 이동했습니다.");
|
||||
} catch (err) {
|
||||
showToast("셀 이동 실패: " + err.message + " — 두 칸의 화면 내용은 유지됩니다. 다시 시도하거나 새로고침해 저장 상태를 확인해 주세요.", "error");
|
||||
} finally {
|
||||
fields.forEach(function (n, i) {
|
||||
if (attrs[i] == null) n.removeAttribute("contenteditable"); else n.setAttribute("contenteditable", attrs[i]);
|
||||
n.closest("td").classList.remove("is-goal-move-saving");
|
||||
});
|
||||
moveBusy = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
// 선택한 셀의 테두리는 이동, 일반 본문 드래그는 기존 글/병합 범위 선택을 유지한다.
|
||||
table.addEventListener("mousedown", function (e) {
|
||||
if (e.button !== 0 || e.shiftKey) return;
|
||||
const source = goalCellTd(e.target), handle = e.target.closest(".pj-goal-move-edge");
|
||||
if (!source) return;
|
||||
if (!handle) { if (!moveBusy) setMoveActive(source); return; }
|
||||
e.preventDefault(); e.stopImmediatePropagation();
|
||||
if (moveBusy || !source.querySelector(".pj-goal-text").value) return;
|
||||
const startX = e.clientX, startY = e.clientY;
|
||||
let moving = false, target = null, frame = null, x = startX, y = startY;
|
||||
function updateTarget() {
|
||||
table.querySelectorAll(".is-goal-move-target").forEach(function (n) { n.classList.remove("is-goal-move-target"); });
|
||||
target = goalCellTd(document.elementFromPoint(x, y));
|
||||
if (target === source) target = null;
|
||||
if (target) target.classList.add("is-goal-move-target");
|
||||
}
|
||||
function scroll() {
|
||||
const r = pane.getBoundingClientRect();
|
||||
if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) {
|
||||
if (x < r.left + 24) pane.scrollLeft -= 16; else if (x > r.right - 24) pane.scrollLeft += 16;
|
||||
if (y < r.top + 24) pane.scrollTop -= 16; else if (y > r.bottom - 24) pane.scrollTop += 16;
|
||||
}
|
||||
updateTarget(); frame = requestAnimationFrame(scroll);
|
||||
}
|
||||
function move(ev) {
|
||||
x = ev.clientX; y = ev.clientY;
|
||||
if (!moving && Math.hypot(x - startX, y - startY) < 4) return;
|
||||
if (!moving) {
|
||||
moving = true; source.classList.add("is-goal-moving");
|
||||
document.documentElement.classList.add("pj-goal-moving");
|
||||
const selection = window.getSelection(); if (selection) selection.removeAllRanges();
|
||||
frame = requestAnimationFrame(scroll);
|
||||
}
|
||||
updateTarget();
|
||||
}
|
||||
function end(ev) {
|
||||
if (frame !== null) cancelAnimationFrame(frame);
|
||||
document.removeEventListener("mousemove", move); document.removeEventListener("mouseup", end);
|
||||
document.removeEventListener("keydown", key, true); window.removeEventListener("blur", cancel);
|
||||
source.classList.remove("is-goal-moving"); document.documentElement.classList.remove("pj-goal-moving");
|
||||
table.querySelectorAll(".is-goal-move-target").forEach(function (n) { n.classList.remove("is-goal-move-target"); });
|
||||
if (moving) moveClickUntil = Date.now() + 300;
|
||||
if (ev && moving && target) moveCell(source, target);
|
||||
}
|
||||
function cancel() { end(null); }
|
||||
function key(ev) { if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); cancel(); } }
|
||||
document.addEventListener("mousemove", move); document.addEventListener("mouseup", end);
|
||||
document.addEventListener("keydown", key, true); window.addEventListener("blur", cancel);
|
||||
}, true);
|
||||
table.addEventListener("click", function (e) {
|
||||
if ((Date.now() < moveClickUntil && e.detail !== 0 && goalCellTd(e.target)) || e.target.closest(".pj-goal-move-edge")) {
|
||||
e.preventDefault(); e.stopImmediatePropagation();
|
||||
}
|
||||
}, true);
|
||||
// 칸이 세로로 길어도(옆 칸 글이 길거나 세로 병합) 칸 아무 곳이나 누르면 그 칸 입력 — 커서는 글 끝(엑셀처럼).
|
||||
// 입력칸(textarea)은 글 높이만큼이라 그 아래를 누르면 아무것도 안 되던 것. Shift+클릭(범위 고르기)·끌기는 그대로.
|
||||
table.addEventListener("click", function (e) {
|
||||
@@ -9238,7 +9390,7 @@
|
||||
return items;
|
||||
}
|
||||
function openAreaMenu(th, x, y, opts) {
|
||||
showContextMenu(x, y, areaMenuItems(th.closest("tbody"), { x: x, y: y }),
|
||||
showContextMenu(x, y, areaMenuItems(th.closest("tbody"), { x: x, y: y }).concat([null], widthMenuItems(th)),
|
||||
Object.assign({ label: textOf(th, ".pj-goal-area-text") + " 구역 메뉴" }, opts || {}));
|
||||
}
|
||||
table.addEventListener("contextmenu", function (e) {
|
||||
@@ -9326,7 +9478,7 @@
|
||||
// 2열 = 항목 칸 밖에 따로 추가(묶음의 맨 위·맨 아래 기준), 묶인 칸이면 "항목 칸 나누기"도
|
||||
const grouped = (th.rowSpan || 1) > 1;
|
||||
showContextMenu(x, y, rowMenuItems(tr, labelGroupBottom(tr), true,
|
||||
{ splitRow: grouped ? tr : null, move: grouped ? null : tr }),
|
||||
{ splitRow: grouped ? tr : null, move: grouped ? null : tr }).concat([null], widthMenuItems(th)),
|
||||
Object.assign({ label: (textOf(th, ".pj-goal-row-text") || "이름 없는") + " 줄 메뉴" }, opts || {}));
|
||||
}
|
||||
table.addEventListener("contextmenu", function (e) {
|
||||
@@ -9371,7 +9523,7 @@
|
||||
if (!td || !table.contains(td)) return;
|
||||
e.preventDefault();
|
||||
const r = yearCellRows(td);
|
||||
showContextMenu(e.clientX, e.clientY, rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }));
|
||||
showContextMenu(e.clientX, e.clientY, rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }).concat([null], widthMenuItems(td)));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9487,12 +9639,14 @@
|
||||
let drag = null;
|
||||
clearMergeSel = function () {
|
||||
sel = null;
|
||||
setMoveActive(null);
|
||||
table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); });
|
||||
};
|
||||
const paint = function () {
|
||||
table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); });
|
||||
if (!sel) return;
|
||||
sel.cells.forEach(function (c) { if (hits(c, sel)) c.td.classList.add("is-merge-sel"); });
|
||||
setMoveActive(sel.n === 1 ? sel.cells.find(function (c) { return hits(c, sel); }).td : null);
|
||||
};
|
||||
const select = function (tbody, a, b) {
|
||||
const cells = gridOf(tbody);
|
||||
@@ -9578,6 +9732,7 @@
|
||||
clearMergeSel();
|
||||
anchorCell = { tbody: tbody, td: td };
|
||||
drag = { tbody: tbody, td: td, moved: false };
|
||||
select(tbody, td, td);
|
||||
});
|
||||
table.addEventListener("mouseover", function (e) {
|
||||
if (!drag) return;
|
||||
@@ -9633,7 +9788,8 @@
|
||||
if (items.length) items.push(null);
|
||||
rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }).forEach(function (it) { items.push(it); });
|
||||
}
|
||||
if (!items.length) { clearMergeSel(); return; }
|
||||
if (items.length) items.push(null);
|
||||
widthMenuItems(td).forEach(function (item) { items.push(item); });
|
||||
e.preventDefault();
|
||||
showContextMenu(e.clientX, e.clientY, items);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user