/* 아사나식 날짜 팝업 · 날짜 버튼 — 공용(2026-10-27).
프로젝트 모듈 project.js 의 openDatePopover · enhanceDateInput 과 같은 모양·같은 동작을 다른 모듈에서 쓰려고 떼어 낸 것
(프로젝트 화면은 아직 project.js 안의 것을 쓴다 — 동작을 바꾸면 두 곳 모두 고칠 것). 스타일 = erp-datepop.css.
· 브라우저 기본 달력(input[type=date])은 숨기고 그 옆에 날짜 버튼을 둔다 — input 은 값 저장소(.value 읽기/쓰기·change 이벤트 그대로).
· 팝업: 위 칸(시작일·종료일 — 직접 입력 2026-10-27 / 10.27 / 10월 27일 / 1027, Enter), 월 달력(일·공휴일 빨강, 토 파랑,
공휴일 이름은 숫자 밑, 오늘 테두리, 기간 옅은 파랑), 오늘 · 지우기. 바깥 클릭·Esc 로 닫힘, 앵커 아래(자리 없으면 위).
window.ErpDatePop = { open(anchor, opts), close(), enhanceRange(startInput, endInput, opts), fmt(iso) } */
(function () {
"use strict";
function esc(s) {
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
});
}
function isoOf(d) {
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
// 오늘 = 한국시간 날짜(브라우저 시간대와 무관 — 프로젝트 isoToday 와 같음)
function isoToday() { return new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 10); }
// 'YYYY-MM-DD' → 'mm/dd(요일)' — 오늘·내일·어제는 글자로(프로젝트 날짜 버튼과 같음), 다른 해면 앞에 연도
function fmt(iso) {
if (!iso) return "";
const d = new Date(String(iso).slice(0, 10) + "T00:00:00");
if (isNaN(d.getTime())) return iso;
const today = isoToday();
const diff = Math.round((d - new Date(today + "T00:00:00")) / 86400000);
if (diff === 0) return "오늘";
if (diff === 1) return "내일";
if (diff === -1) return "어제";
const wd = ["일", "월", "화", "수", "목", "금", "토"][d.getDay()];
const md = String(d.getMonth() + 1).padStart(2, "0") + "/" + String(d.getDate()).padStart(2, "0") + "(" + wd + ")";
return (String(d.getFullYear()) === today.slice(0, 4) ? "" : d.getFullYear() + "/") + md;
}
function fmtField(iso) {
if (!iso) return "";
const d = new Date(iso + "T00:00:00");
const same = d.getFullYear() === new Date().getFullYear();
return (same ? "" : d.getFullYear() + "년 ") + (d.getMonth() + 1) + "월 " + d.getDate() + "일";
}
// 직접 입력 해석 — 2026-09-30 / 2026.9.30 / 9/30 / 9월 30일 / 0930. 빈 값 = "", 해석 불가 = null.
function parseTyped(text, baseIso) {
const v = String(text || "").trim().replace(/\s+/g, "");
if (!v) return "";
let m = v.match(/^(\d{4})[-./년](\d{1,2})[-./월](\d{1,2})[.일]?$/);
let y, mo, d;
if (m) { y = +m[1]; mo = +m[2]; d = +m[3]; }
else if ((m = v.match(/^(\d{1,2})[-./월](\d{1,2})[.일]?$/))) { y = +baseIso.slice(0, 4); mo = +m[1]; d = +m[2]; }
else if ((m = v.match(/^(\d{2})(\d{2})$/))) { y = +baseIso.slice(0, 4); mo = +m[1]; d = +m[2]; }
else return null;
const dt = new Date(y, mo - 1, d);
if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d) return null;
return isoOf(dt);
}
const HOLIDAY_SHORT = { "부처님오신날": "석가탄신일", "추석·개천절": "추석" };
let popEl = null, cleanup = null;
function close() {
if (cleanup) cleanup();
cleanup = null;
if (popEl) { popEl.remove(); popEl = null; }
}
// opts: { start, due, allowStart, active("start"|"due"), labels {start, due}, holidays {iso: 이름}, clear(bool, 기본 true),
// onChange(patch {due_date, start_date?}) } — 날짜를 누를 때마다 onChange, 마감(종료)일을 고르면 닫힘.
function open(anchor, opts) {
close();
opts = opts || {};
const labels = Object.assign({ start: "시작일", due: "마감일" }, opts.labels || {});
const holidays = opts.holidays || {};
const today = isoToday();
let start = opts.start ? String(opts.start).slice(0, 10) : "";
let due = opts.due ? String(opts.due).slice(0, 10) : "";
let showStart = !!(opts.allowStart && (start || opts.active === "start"));
let active = opts.allowStart && opts.active === "start" ? "start" : "due";
const base = new Date(((active === "start" ? start : due) || start || due || today) + "T00:00:00");
let viewY = base.getFullYear(), viewM = base.getMonth();
const pop = document.createElement("div");
pop.className = "pj-datepop";
document.body.appendChild(pop);
popEl = pop;
function emit() {
const patch = { due_date: due || null };
if (opts.allowStart) patch.start_date = start || null;
if (opts.onChange) opts.onChange(patch);
}
function field(kind, val) {
return '';
}
function render() {
const first = new Date(viewY, viewM, 1);
const gridStart = new Date(viewY, viewM, 1 - first.getDay());
let days = "";
for (let i = 0; i < 42; i++) {
const d = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i);
const iso = isoOf(d);
const cls = ["pj-dp-day"];
if (d.getMonth() !== viewM) cls.push("is-out");
const holName = holidays[iso] || "";
if (d.getDay() === 0 || holName) cls.push("is-sun");
else if (d.getDay() === 6) cls.push("is-sat");
if (iso === today) cls.push("is-today");
if (iso === due || (showStart && iso === start)) cls.push("is-selected");
if (showStart && start && due && iso > start && iso < due) cls.push("is-inrange");
if (holName) cls.push("has-hol");
const holShort = /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
days += '";
}
pop.innerHTML =
'
' +
(opts.allowStart ? (showStart ? field("start", start) : '") : "") +
field("due", due) +
"
" +
'' +
'' +
'' + viewY + "년 " + (viewM + 1) + "월" +
'' +
"
" +
'' +
["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) {
return '' + w + "";
}).join("") + days +
"
" +
'";
wire();
}
// 시작일 칸이 활성이면 시작일(그 뒤 마감일로), 아니면 마감일(저장하고 닫음). 시작일 > 마감일이 되지 않게 맞춘다.
function pick(iso) {
if (active === "start") {
start = iso;
if (due && due < iso) due = iso;
active = "due";
render(); emit(); focusActive();
return;
}
due = iso;
if (start && start > iso) start = iso;
emit();
close();
}
function wire() {
pop.querySelectorAll(".pj-dp-day").forEach(function (b) {
b.addEventListener("click", function () { pick(b.dataset.iso); });
});
pop.querySelectorAll(".pj-dp-navbtn").forEach(function (b) {
b.addEventListener("click", function () {
viewM += +b.dataset.nav;
if (viewM < 0) { viewM = 11; viewY--; } else if (viewM > 11) { viewM = 0; viewY++; }
render();
});
});
const add = pop.querySelector(".pj-dp-addstart");
if (add) add.addEventListener("click", function () { showStart = true; active = "start"; render(); focusActive(); });
pop.querySelectorAll(".pj-dp-field").forEach(function (inp) {
inp.addEventListener("focus", function () {
active = inp.dataset.kind;
pop.querySelectorAll(".pj-dp-field").forEach(function (x) { x.classList.toggle("is-active", x === inp); });
});
function commit() {
const kind = inp.dataset.kind;
const cur = kind === "start" ? start : due;
const parsed = parseTyped(inp.value, today);
if (parsed === null || parsed === cur) { inp.value = fmtField(cur); return; }
if (!parsed) {
if (opts.clear === false) { inp.value = fmtField(cur); return; }
if (kind === "start") { start = ""; showStart = false; } else due = "";
render(); emit(); return;
}
active = kind;
const d = new Date(parsed + "T00:00:00");
viewY = d.getFullYear(); viewM = d.getMonth();
pick(parsed);
}
inp.addEventListener("keydown", function (e) {
if (e.isComposing) return;
if (e.key === "Enter") { e.preventDefault(); commit(); }
});
inp.addEventListener("change", commit);
});
pop.querySelector(".pj-dp-today").addEventListener("click", function () {
const d = new Date(); viewY = d.getFullYear(); viewM = d.getMonth();
pick(today);
});
const clr = pop.querySelector(".pj-dp-clear");
if (clr) clr.addEventListener("click", function () { start = ""; due = ""; emit(); close(); });
}
function focusActive() {
const f = pop.querySelector('.pj-dp-field[data-kind="' + active + '"]');
if (f) f.focus();
}
function place() {
const r = anchor.getBoundingClientRect();
const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight;
const w = pop.offsetWidth, h = pop.offsetHeight;
const ax = r.left + r.width / 2;
const left = Math.min(Math.max(8, ax - w / 2), vw - w - 8);
const below = r.bottom + 10 + h <= vh - 8 || r.top - 10 - h < 8;
pop.classList.toggle("is-above", !below);
pop.style.left = left + "px";
pop.style.top = (below ? r.bottom + 10 : r.top - 10 - h) + "px";
pop.style.setProperty("--pj-dp-tail", Math.min(Math.max(ax - left, 16), w - 16) + "px");
}
function onDown(e) {
if (pop.contains(e.target) || anchor.contains(e.target)) return;
close();
}
function onKey(e) { if (e.key === "Escape") { e.stopPropagation(); close(); } }
render();
place();
setTimeout(function () {
if (popEl !== pop) return; // 그 사이 닫혔으면 걸지 않는다(남은 Esc 처리가 이후 Esc 를 삼키지 않게)
document.addEventListener("mousedown", onDown, true);
document.addEventListener("keydown", onKey, true);
}, 0);
window.addEventListener("resize", close);
cleanup = function () {
document.removeEventListener("mousedown", onDown, true);
document.removeEventListener("keydown", onKey, true);
window.removeEventListener("resize", close);
};
focusActive();
}
// 시작·끝 날짜 input 두 개 → 날짜 버튼 두 개(각 input 자리), 어느 쪽을 눌러도 같은 기간 팝업(누른 쪽 칸이 먼저).
// endInput 이 숨겨져 있으면(opts.single() 이 true — 예: 반차) 하루짜리 팝업으로 시작=끝을 같이 맞춘다.
// input 은 숨겨 값 저장소로 둔다 — value 쓰기를 가로채 버튼 글자도 따라 바뀌고, 고르면 input·change 이벤트를 낸다.
function enhanceRange(startInput, endInput, opts) {
opts = opts || {};
const labels = Object.assign({ start: "시작일", due: "종료일" }, opts.labels || {});
const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
const pairs = [[startInput, "start"], [endInput, "due"]].filter(function (p) { return p[0] && !p[0].dataset.erpDate; });
const btns = {};
pairs.forEach(function (p) {
const inp = p[0], kind = p[1];
inp.dataset.erpDate = "1";
inp.style.display = "none";
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pj-date-btn erp-date-btn";
btn.dataset.kind = kind;
inp.after(btn);
btns[kind] = btn;
Object.defineProperty(inp, "value", {
configurable: true,
get: function () { return desc.get.call(this); },
set: function (v) { desc.set.call(this, v); sync(); },
});
btn.addEventListener("click", function (e) {
e.preventDefault(); e.stopPropagation();
const single = !!(opts.single && opts.single());
open(btn, {
start: single ? "" : startInput.value, due: single ? startInput.value : endInput.value,
allowStart: !single, active: single ? "due" : kind, clear: false, holidays: opts.holidays || {},
labels: single ? { due: opts.singleLabel || "날짜" } : labels,
onChange: function (patch) {
if (single) { set(startInput, patch.due_date); set(endInput, patch.due_date); return; }
set(startInput, patch.start_date);
set(endInput, patch.due_date);
},
});
});
});
function set(inp, v) {
if (!v || (inp.value || "") === v) return; // 필수 칸 — 비우지 않는다
inp.value = v;
inp.dispatchEvent(new Event("input", { bubbles: true }));
inp.dispatchEvent(new Event("change", { bubbles: true }));
}
function sync() {
[["start", startInput], ["due", endInput]].forEach(function (p) {
const btn = btns[p[0]];
if (!btn) return;
const text = fmt(p[1].value);
btn.innerHTML = 'calendar_month';
btn.querySelector(".pj-date-btn-text").textContent = text || labels[p[0]] + " 선택";
btn.classList.toggle("is-empty", !text);
btn.title = text ? labels[p[0]] + " 변경" : labels[p[0]] + " 지정";
});
}
sync();
return { sync: sync, buttons: btns };
}
window.ErpDatePop = { open: open, close: close, enhanceRange: enhanceRange, fmt: fmt, parse: parseTyped };
})();