/* 아사나식 날짜 팝업 · 날짜 버튼 — 공용(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(), enhance(input, opts), enhanceRange(startInput, endInput, opts), mountRange(box, opts), fmt(iso), fmtFull(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; } // 'YYYY-MM-DD' → 'YYYY.MM.DD(요일)' — 입사일처럼 연도가 꼭 보여야 하는 날짜(2026-10-27) function fmtFull(iso) { if (!iso) return ""; const d = new Date(String(iso).slice(0, 10) + "T00:00:00"); if (isNaN(d.getTime())) return iso; return d.getFullYear() + "." + String(d.getMonth() + 1).padStart(2, "0") + "." + String(d.getDate()).padStart(2, "0") + "(" + ["일", "월", "화", "수", "목", "금", "토"][d.getDay()] + ")"; } 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 = { "부처님오신날": "석가탄신일", "추석·개천절": "추석" }; // 요일 줄 + 6주 날짜 칸(팝업·붙박이 달력 공용). extra(iso) = 그 칸에 더할 클래스 목록 // locale(선택, 라이브 커머스 영문 화면): { weekdays[7], shortName(이름), title(연, 월0), prev, next } — 없으면 한글 function gridHtml(viewY, viewM, holidays, today, extra, locale) { 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"); cls.push.apply(cls, extra(iso, d)); if (holName) cls.push("has-hol"); const holShort = locale && locale.shortName ? locale.shortName(holName) : /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName); days += '"; } return '
' + ((locale && locale.weekdays) || ["일", "월", "화", "수", "목", "금", "토"]).map(function (w, i) { return '' + w + ""; }).join("") + days + "
"; } 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), // yearNav(bool — « » 1년씩, 입사일처럼 먼 날짜), 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() { pop.innerHTML = '
' + (opts.allowStart ? (showStart ? field("start", start) : '") : "") + field("due", due) + "
" + '
' + (opts.yearNav ? '' : "") + '' + '' + viewY + "년 " + (viewM + 1) + "월" + '' + (opts.yearNav ? '' : "") + "
" + gridHtml(viewY, viewM, holidays, today, function (iso) { const c = []; if (iso === due || (showStart && iso === start)) c.push("is-selected"); if (showStart && start && due && iso > start && iso < due) c.push("is-inrange"); return c; }) + '
' + '' + (opts.clear === false ? "" : '') + "
"; 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; while (viewM < 0) { viewM += 12; viewY--; } while (viewM > 11) { viewM -= 12; 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 하나 → 날짜 버튼 하나(2026-10-27, 입사일 등). opts: { label, placeholder, format(iso), yearNav, clear(기본 true), holidays } // input 은 숨긴 값 저장소 — value 쓰기를 가로채 버튼 글자도 바뀌고, 고르거나 지우면 input·change 이벤트를 낸다. function enhance(input, opts) { if (!input || input.dataset.erpDate) return null; opts = opts || {}; const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value"); const format = opts.format || fmt; input.dataset.erpDate = "1"; input.style.display = "none"; const btn = document.createElement("button"); btn.type = "button"; btn.className = "pj-date-btn erp-date-btn" + (opts.className ? " " + opts.className : ""); input.after(btn); Object.defineProperty(input, "value", { configurable: true, get: function () { return desc.get.call(this); }, set: function (v) { desc.set.call(this, v); sync(); }, }); function sync() { const text = format(input.value); btn.innerHTML = 'calendar_month'; btn.querySelector(".pj-date-btn-text").textContent = text || opts.placeholder || "날짜 선택"; btn.classList.toggle("is-empty", !text); btn.title = (opts.label || "날짜") + (text ? " 변경" : " 지정"); } btn.addEventListener("click", function (e) { e.preventDefault(); e.stopPropagation(); open(btn, { due: input.value, allowStart: false, clear: opts.clear !== false, yearNav: !!opts.yearNav, holidays: opts.holidays || {}, labels: { due: opts.label || "날짜" }, onChange: function (patch) { const v = patch.due_date || ""; if ((input.value || "") === v) return; input.value = v; input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); }, }); }); sync(); return { sync: sync, button: btn }; } // 시작·끝 날짜 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 }; } // 화면에 붙박이는 기간 달력(2026-11-02, 휴가 신청) — 팝업과 같은 달력 서식(.pj-dp-*). // 첫 클릭 = 시작일(동그라미), 다음 클릭 = 종료일(둥근 막대), 그다음 클릭 = 새로 시작. 시작일보다 앞을 누르면 그 날이 새 시작일. // opts: { start, end, holidays, single() — true 면 클릭마다 하루, onChange(start, end), locale }. 반환 { set(start, end) } function mountRange(box, opts) { const holidays = opts.holidays || {}; const today = isoToday(); let start = opts.start || "", end = opts.end || opts.start || "", picking = false; const base = new Date((start || today) + "T00:00:00"); let viewY = base.getFullYear(), viewM = base.getMonth(); function bandClasses(iso, d) { if (!start || iso < start || iso > end) return []; if (start === end) return ["is-selected"]; const c = ["is-band"]; if (iso === start) c.push("is-selected", "is-band-start"); else if (iso === end) c.push("is-selected", "is-band-end"); if (d.getDay() === 0) c.push("is-row-first"); if (d.getDay() === 6) c.push("is-row-last"); return c; } function render() { const loc = opts.locale || {}; box.innerHTML = '
' + '' + '' + esc(loc.title ? loc.title(viewY, viewM) : viewY + "년 " + (viewM + 1) + "월") + "" + '' + "
" + gridHtml(viewY, viewM, holidays, today, bandClasses, opts.locale); } box.addEventListener("click", function (e) { const nav = e.target.closest(".pj-dp-navbtn"); if (nav) { const d = new Date(viewY, viewM + +nav.dataset.nav, 1); viewY = d.getFullYear(); viewM = d.getMonth(); render(); return; } const day = e.target.closest(".pj-dp-day"); if (!day) return; const iso = day.dataset.iso; if (!picking || iso < start || (opts.single && opts.single())) { start = end = iso; picking = !(opts.single && opts.single()); } else { end = iso; picking = false; } render(); if (opts.onChange) opts.onChange(start, end); }); render(); return { set: function (s, e) { start = s; end = e; picking = false; render(); } }; } window.ErpDatePop = { open: open, close: close, enhance: enhance, enhanceRange: enhanceRange, mountRange: mountRange, fmt: fmt, fmtFull: fmtFull, parse: parseTyped }; })();