`;
}
function syncCalcModeRows(target) {
const r = root(); if (!r) return;
const ci = $("[data-calc-interest]", r);
if (ci && target.name === "ciDayMode") {
const m = (ci.querySelector('input[name="ciDayMode"]:checked') || {}).value;
$('[data-ci-row="manual"]', r).hidden = m !== "manual";
$('[data-ci-row="range"]', r).hidden = m !== "range";
}
const cd = $("[data-calc-discount]", r);
if (cd && target.name === "cdMatMode") {
const m = (cd.querySelector('input[name="cdMatMode"]:checked') || {}).value;
$('[data-cd-row="date"]', r).hidden = m !== "date";
$('[data-cd-row="after"]', r).hidden = m !== "after";
}
if (cd && target.name === "cdBill") {
const v = (cd.querySelector('input[name="cdBill"]:checked') || {}).value;
const hint = $("[data-cd-bill-hint]", r);
if (hint) hint.textContent = v === "bank" ? "银承:流通性较好,贴现利率通常低于商承。" : "商承:请重点评估承兑人信用;贴现利率通常高于银承。";
}
}
function applyCdMonths() {
const r = root(); const f = r && $("[data-calc-discount]", r); if (!f) return;
if (f.issue && isDateField(f.issue) && !applyDateValue(f.issue).ok) return;
const iss = f.issue.value;
if (!iss) { toast("请先填出票日"); return; }
const mo = parseInt(f.months.value, 10);
if (!(mo >= 1 && mo <= 12)) { toast("期限月数须为 1-12"); return; }
const p = iss.split("-").map(Number);
const d = cAddMonths(p[0], p[1], p[2], mo);
f.due.value = cYmd(d);
const pv = $("[data-cd-mat-preview]", r);
if (pv) pv.textContent = "推算到期:" + cYmd(d);
initCalc();
}
function histRefill(i) {
const r = root(); const f = r && $("[data-calc-discount]", r); if (!f) return;
const h = dcHist()[i]; if (!h) return;
f.face.value = h.face; f.rate.value = h.rate;
initCalc(); toast("已回填票面金额与利率");
}
function calcAction(act) {
const r = root(); if (!r) return;
const cd = $("[data-calc-discount]", r);
if (act === "calc") {
const form = $("[data-calc-interest]", r) || $("[data-calc-discount]", r);
if (form && !normalizeFormDates(form)) return;
initCalc();
return;
}
if (act === "reset") {
const ci = $("[data-calc-interest]", r);
if (ci) {
ci.amt.value = ""; ci.rate.value = ""; ci.days.value = ""; ci.d1.value = ""; ci.d2.value = "";
[ci.d1, ci.d2].forEach((el) => { if (el) setErr(el, ""); });
initCalc(); toast("已重置"); return;
}
const cd2 = $("[data-calc-discount]", r);
if (cd2) {
cd2.face.value = ""; cd2.rate.value = ""; cd2.issue.value = ""; cd2.due.value = ""; cd2.netIn.value = ""; cd2.per10.value = "";
[cd2.issue, cd2.now, cd2.due].forEach((el) => { if (el) setErr(el, ""); });
const pv = $("[data-cd-mat-preview]", r); if (pv) pv.textContent = "";
initCalc(); toast("已重置"); return;
}
return;
}
if (act === "copy") {
const last = cd ? window._dcLast : window._ciLast;
if (!last) { toast("请先完成一次有效计算"); return; }
const txt = last.text;
if (navigator.clipboard) navigator.clipboard.writeText(txt).then(() => toast("结果已复制"), () => toast(txt));
else toast(txt);
return;
}
if (act === "save" && cd) {
if (!window._dcLast) { toast("请先完成一次有效计算"); return; }
const arr = dcHist();
const l = window._dcLast;
arr.unshift({ t: new Date().toLocaleString("zh-CN", { hour12: false }), face: l.face, rate: l.rate, days: l.days, intr: l.intr, net: l.net });
dcHistSave(arr); renderDcHist(); toast("已保存到本地历史");
}
}
function initCalc() {
const r = root(); if (!r) return;
if ($("[data-calc-interest]", r)) renderInterest();
if ($("[data-calc-discount]", r)) { renderDiscount(); renderDcHist(); }
}
/* ============================================================
HEL-349 · 自定义锚定弹层(下拉 / 日历)
原生 select 展开列表与 input[type=date] 日历无法可靠换肤/定位,
用现有 fusion 栈做 fixed 锚定层;原生控件仍负责取值与提交。
============================================================ */
const WEEKDAYS = ["日", "一", "二", "三", "四", "五", "六"];
let popHost = null;
let menuEl = null;
let dpEl = null;
let popAnchor = null;
let popKind = null;
let dpView = null;
let dpFocusYmd = null;
let popRepositionBound = false;
function popRoot() {
return root() || document.body;
}
function ensurePops() {
const host = popRoot();
if (popHost === host && menuEl && dpEl) return;
popHost = host;
if (menuEl && menuEl.parentNode) menuEl.remove();
if (dpEl && dpEl.parentNode) dpEl.remove();
menuEl = document.createElement("div");
menuEl.id = "jn-select-menu";
menuEl.className = "jn-pop jn-menu";
menuEl.hidden = true;
menuEl.setAttribute("role", "listbox");
menuEl.setAttribute("tabindex", "-1");
dpEl = document.createElement("div");
dpEl.id = "jn-datepicker";
dpEl.className = "jn-pop jn-dp";
dpEl.hidden = true;
dpEl.setAttribute("role", "dialog");
dpEl.setAttribute("aria-label", "选择日期");
host.appendChild(menuEl);
host.appendChild(dpEl);
}
function placePopover(pop, anchor) {
const gap = 6, margin = 8;
pop.hidden = false;
pop.style.top = "0px";
pop.style.left = "0px";
const ar = anchor.getBoundingClientRect();
const pr = pop.getBoundingClientRect();
const vw = window.innerWidth, vh = window.innerHeight;
let top = ar.bottom + gap;
if (top + pr.height > vh - margin && ar.top - gap - pr.height >= margin) {
top = ar.top - gap - pr.height;
}
top = Math.min(Math.max(margin, top), Math.max(margin, vh - pr.height - margin));
let left = ar.left;
if (left + pr.width > vw - margin) left = vw - pr.width - margin;
left = Math.max(margin, left);
pop.style.top = Math.round(top) + "px";
pop.style.left = Math.round(left) + "px";
if (pop === menuEl) {
pop.style.minWidth = Math.round(ar.width) + "px";
pop.style.maxWidth = Math.min(480, vw - margin * 2) + "px";
}
}
function repositionOpenPop() {
if (!popAnchor || !popKind) return;
const pop = popKind === "menu" ? menuEl : dpEl;
if (!pop || pop.hidden) return;
if (!popAnchor.isConnected) { closePops(); return; }
placePopover(pop, popAnchor);
}
function bindPopReposition(on) {
if (on && !popRepositionBound) {
window.addEventListener("resize", repositionOpenPop);
window.addEventListener("scroll", repositionOpenPop, true);
popRepositionBound = true;
} else if (!on && popRepositionBound) {
window.removeEventListener("resize", repositionOpenPop);
window.removeEventListener("scroll", repositionOpenPop, true);
popRepositionBound = false;
}
}
function closePops() {
const prev = popAnchor;
const kind = popKind;
const ae = document.activeElement;
const focusBack = !!(prev && ae && (ae === prev || (menuEl && menuEl.contains(ae)) || (dpEl && dpEl.contains(ae))));
if (menuEl) {
menuEl.hidden = true;
menuEl.innerHTML = "";
}
if (dpEl) dpEl.hidden = true;
if (prev) {
prev.setAttribute("aria-expanded", "false");
prev.removeAttribute("aria-controls");
}
popAnchor = null;
popKind = null;
bindPopReposition(false);
if (focusBack) prev.focus();
return !!kind;
}
function nativeSelect(el) {
return el && el.tagName === "SELECT" && !el.multiple && !(+el.size > 1);
}
function openSelectMenu(select) {
if (!nativeSelect(select) || select.disabled) return;
ensurePops();
if (popKind === "menu" && popAnchor === select) { closePops(); return; }
closePops();
popAnchor = select;
popKind = "menu";
select.setAttribute("aria-expanded", "true");
select.setAttribute("aria-controls", "jn-select-menu");
menuEl.innerHTML = "";
const opts = Array.from(select.options);
opts.forEach((opt, i) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "jn-menu-opt";
btn.setAttribute("role", "option");
btn.dataset.index = String(i);
btn.textContent = opt.textContent;
if (opt.disabled) {
btn.disabled = true;
btn.setAttribute("aria-disabled", "true");
}
if (opt.selected) btn.setAttribute("aria-selected", "true");
menuEl.appendChild(btn);
});
placePopover(menuEl, select);
bindPopReposition(true);
const active = menuEl.querySelector(".jn-menu-opt[aria-selected='true']:not(:disabled)") || menuEl.querySelector(".jn-menu-opt:not(:disabled)");
if (active) active.focus();
}
function commitSelect(index) {
const select = popAnchor;
if (!nativeSelect(select)) { closePops(); return; }
const opt = select.options[index];
if (!opt || opt.disabled) return;
if (select.selectedIndex !== index) {
select.selectedIndex = index;
select.dispatchEvent(new Event("input", { bubbles: true }));
select.dispatchEvent(new Event("change", { bubbles: true }));
}
closePops();
select.focus();
}
function parseLimit(v) {
const s = String(v || "").trim();
return /^\d{4}-\d{2}-\d{2}$/.test(s) ? s : "";
}
function inDateRange(ymd, min, max) {
if (min && ymd < min) return false;
if (max && ymd > max) return false;
return true;
}
function isDateField(el) {
return !!(el && el.tagName === "INPUT" && (el.type === "date" || el.hasAttribute("data-jn-date")));
}
function dateFieldMin(input) {
return parseLimit(input.getAttribute("data-min") || input.min);
}
function dateFieldMax(input) {
return parseLimit(input.getAttribute("data-max") || input.max);
}
function applyDateValue(input, opts) {
const fire = !opts || opts.fire !== false;
const raw = String(input.value || "").trim();
if (raw === "") {
if (input.value !== "") input.value = "";
setErr(input, "");
return { ok: true, ymd: "" };
}
const parsed = ymdParts(raw);
if (!parsed) {
setErr(input, "请输入有效日期(YYYY-MM-DD)");
return { ok: false, ymd: "" };
}
const min = dateFieldMin(input), max = dateFieldMax(input);
const changed = input.value !== parsed.ymd;
if (changed) input.value = parsed.ymd;
if (!inDateRange(parsed.ymd, min, max)) {
if (changed && fire) {
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
setErr(input, "日期超出允许范围");
return { ok: false, ymd: parsed.ymd };
}
setErr(input, "");
if (changed && fire) {
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
return { ok: true, ymd: parsed.ymd };
}
function normalizeFormDates(form) {
if (!form) return true;
let ok = true, firstBad = null;
form.querySelectorAll('input[data-jn-date], input[type="date"]').forEach((input) => {
if (input.disabled) return;
const r = applyDateValue(input);
if (!r.ok) {
ok = false;
if (!firstBad) firstBad = input;
}
});
if (firstBad) {
try { firstBad.scrollIntoView({ block: "center", behavior: "smooth" }); firstBad.focus(); } catch (e) {}
}
return ok;
}
function yearBounds(input) {
const now = new Date().getFullYear();
let yMin = now - 40, yMax = now + 20;
const min = dateFieldMin(input), max = dateFieldMax(input);
if (min) yMin = parseInt(min.slice(0, 4), 10);
if (max) yMax = parseInt(max.slice(0, 4), 10);
if (yMin > yMax) yMax = yMin;
return { yMin, yMax };
}
function ymDisabled(y, m, min, max) {
const start = y + "-" + cPad(m + 1) + "-01";
const end = y + "-" + cPad(m + 1) + "-" + cPad(new Date(y, m + 1, 0).getDate());
if (min && end < min) return true;
if (max && start > max) return true;
return false;
}
function yearDisabled(y, min, max) {
if (min && y < parseInt(min.slice(0, 4), 10)) return true;
if (max && y > parseInt(max.slice(0, 4), 10)) return true;
return false;
}
function armDateInput(input) {
if (!isDateField(input) || input.dataset.jnArmed === "1") return;
input.dataset.jnArmed = "1";
if (input.type === "date") {
const v = input.value;
const min = input.getAttribute("min") || "";
const max = input.getAttribute("max") || "";
input.type = "text";
input.setAttribute("data-jn-date", "");
if (min) input.setAttribute("data-min", min);
if (max) input.setAttribute("data-max", max);
input.removeAttribute("min");
input.removeAttribute("max");
if (v) input.value = v;
}
if (!input.getAttribute("inputmode")) input.setAttribute("inputmode", "numeric");
input.setAttribute("autocomplete", "off");
input.setAttribute("spellcheck", "false");
if (!input.getAttribute("placeholder")) input.setAttribute("placeholder", "YYYY-MM-DD");
input.setAttribute("maxlength", "10");
input.classList.add("num");
}
function enhanceDateInputs(scope) {
const host = scope && scope.querySelectorAll ? scope : document;
host.querySelectorAll('input[type="date"], input[data-jn-date]').forEach(armDateInput);
}
let dpMode = "day";
let dpYearPage = null;
let dpFocusPick = null;
function renderDatePicker() {
if (!dpEl || !popAnchor) return;
const input = popAnchor;
const min = dateFieldMin(input), max = dateFieldMax(input);
const selected = (ymdParts(input.value) || {}).ymd || "";
const today = cYmd(new Date());
if (!dpView) {
const seed = cParseYmd(selected) || new Date();
dpView = { y: seed.getFullYear(), m: seed.getMonth() };
}
if (!dpFocusYmd) dpFocusYmd = selected || today;
const y = dpView.y, m = dpView.m;
const { yMin, yMax } = yearBounds(input);
if (!dpYearPage) dpYearPage = Math.floor(y / 12) * 12;
dpYearPage = Math.min(Math.max(dpYearPage, yMin), Math.max(yMin, yMax - 11));
const navLabel = dpMode === "year" ? "年" : (dpMode === "month" ? "年" : "月");
let body = "";
if (dpMode === "year") {
let cells = "";
for (let i = 0; i < 12; i++) {
const yy = dpYearPage + i;
const disabled = yy < yMin || yy > yMax || yearDisabled(yy, min, max);
const sel = yy === y;
const isFocus = dpFocusPick === yy;
cells += ``;
}
body = `
${cells}
`;
} else if (dpMode === "month") {
let cells = "";
for (let i = 0; i < 12; i++) {
const disabled = ymDisabled(y, i, min, max);
const sel = i === m;
const isFocus = dpFocusPick === i;
cells += ``;
}
body = `
${cells}
`;
} else {
const first = new Date(y, m, 1);
const startDow = first.getDay();
const gridStart = new Date(y, m, 1 - startDow);
let days = "";
for (let i = 0; i < 42; i++) {
const d = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i);
const ymd = cYmd(d);
const out = d.getMonth() !== m;
const disabled = !inDateRange(ymd, min, max);
const sel = selected && ymd === selected;
const isFocus = ymd === dpFocusYmd;
days += ``;
}
body = `
${WEEKDAYS.map((w) => `${w}`).join("")}
${days}
`;
}
dpEl.innerHTML = `
${body}
`;
let focusBtn = null;
if (dpMode === "year") {
focusBtn = dpEl.querySelector(`.jn-dp-pick[data-dp-year="${dpFocusPick}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-pick:not(:disabled)");
} else if (dpMode === "month") {
focusBtn = dpEl.querySelector(`.jn-dp-pick[data-dp-month="${dpFocusPick}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-pick:not(:disabled)");
} else {
focusBtn = dpEl.querySelector(`.jn-dp-day[data-ymd="${dpFocusYmd}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-day:not(:disabled)");
if (focusBtn) dpFocusYmd = focusBtn.dataset.ymd;
}
if (focusBtn) {
focusBtn.tabIndex = 0;
focusBtn.focus();
}
}
function openDatePicker(input) {
if (!isDateField(input) || input.disabled || input.readOnly) return;
armDateInput(input);
ensurePops();
if (popKind === "date" && popAnchor === input) { closePops(); return; }
closePops();
popAnchor = input;
popKind = "date";
dpMode = "day";
input.setAttribute("aria-expanded", "true");
input.setAttribute("aria-controls", "jn-datepicker");
input.setAttribute("aria-haspopup", "dialog");
const seed = cParseYmd(input.value) || new Date();
dpView = { y: seed.getFullYear(), m: seed.getMonth() };
dpFocusYmd = parseLimit(input.value) || cYmd(new Date());
dpYearPage = Math.floor(dpView.y / 12) * 12;
dpFocusPick = dpView.y;
renderDatePicker();
placePopover(dpEl, input);
bindPopReposition(true);
}
function commitDate(ymd) {
const input = popAnchor;
if (!isDateField(input)) { closePops(); return; }
if (ymd === "") {
if (input.value !== "") {
input.value = "";
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
setErr(input, "");
closePops();
input.focus();
return;
}
const min = dateFieldMin(input), max = dateFieldMax(input);
if (!inDateRange(ymd, min, max)) return;
if (input.value !== ymd) {
input.value = ymd;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
setErr(input, "");
closePops();
input.focus();
}
function shiftDpFocus(days) {
const cur = cParseYmd(dpFocusYmd) || new Date();
cur.setDate(cur.getDate() + days);
dpFocusYmd = cYmd(cur);
dpView = { y: cur.getFullYear(), m: cur.getMonth() };
renderDatePicker();
repositionOpenPop();
}
function shiftDpMonth(delta) {
if (!dpView) return;
const d = new Date(dpView.y, dpView.m + delta, 1);
dpView = { y: d.getFullYear(), m: d.getMonth() };
const keep = cParseYmd(dpFocusYmd) || d;
const last = new Date(dpView.y, dpView.m + 1, 0).getDate();
const day = Math.min(keep.getDate(), last);
dpFocusYmd = cYmd(new Date(dpView.y, dpView.m, day));
renderDatePicker();
repositionOpenPop();
}
function shiftDpNav(delta) {
if (dpMode === "year") {
const { yMin, yMax } = yearBounds(popAnchor);
dpYearPage = Math.min(Math.max((dpYearPage || yMin) + delta * 12, yMin), Math.max(yMin, yMax - 11));
dpFocusPick = Math.min(Math.max((dpFocusPick || dpView.y) + delta * 12, yMin), yMax);
renderDatePicker();
repositionOpenPop();
return;
}
if (dpMode === "month") {
if (!dpView) return;
dpView = { y: dpView.y + delta, m: dpView.m };
dpFocusPick = dpView.m;
renderDatePicker();
repositionOpenPop();
return;
}
shiftDpMonth(delta);
}
if (typeof HTMLInputElement !== "undefined" && HTMLInputElement.prototype.showPicker) {
const nativeShowPicker = HTMLInputElement.prototype.showPicker;
HTMLInputElement.prototype.showPicker = function () {
if (isDateField(this) && this.closest("[data-variant-root]")) {
openDatePicker(this);
return;
}
return nativeShowPicker.call(this);
};
}
document.addEventListener("mousedown", (e) => {
const t = e.target;
if (menuEl && !menuEl.hidden && menuEl.contains(t)) return;
if (dpEl && !dpEl.hidden && dpEl.contains(t)) return;
const dateInp = t.closest && t.closest("input");
if (dateInp && isDateField(dateInp) && dateInp.closest("[data-variant-root]")) {
if (dateInp.disabled || dateInp.readOnly) return;
e.preventDefault();
armDateInput(dateInp);
dateInp.focus();
openDatePicker(dateInp);
return;
}
const sel = t.closest && t.closest("select");
if (sel && nativeSelect(sel) && sel.closest("[data-variant-root]")) {
if (sel.disabled) return;
e.preventDefault();
sel.focus();
openSelectMenu(sel);
return;
}
if (popKind) closePops();
}, true);
document.addEventListener("click", (e) => {
const dateInp = e.target.closest && e.target.closest("input");
if (dateInp && isDateField(dateInp) && dateInp.closest("[data-variant-root]")) {
e.preventDefault();
}
}, true);
document.addEventListener("click", (e) => {
const t = e.target;
if (!dpEl || dpEl.hidden || !dpEl.contains(t)) return;
const nav = t.closest("[data-dp-nav]");
if (nav) { shiftDpNav(+nav.dataset.dpNav); return; }
const viewBtn = t.closest("[data-dp-view]");
if (viewBtn) {
const next = viewBtn.dataset.dpView;
dpMode = dpMode === next ? "day" : next;
dpFocusPick = dpMode === "year" ? dpView.y : dpView.m;
renderDatePicker();
repositionOpenPop();
return;
}
const yPick = t.closest("[data-dp-year]");
if (yPick && !yPick.disabled) {
dpView = { y: +yPick.dataset.dpYear, m: dpView.m };
dpMode = "month";
dpFocusPick = dpView.m;
renderDatePicker();
repositionOpenPop();
return;
}
const mPick = t.closest("[data-dp-month]");
if (mPick && !mPick.disabled) {
dpView = { y: dpView.y, m: +mPick.dataset.dpMonth };
dpMode = "day";
const keep = cParseYmd(dpFocusYmd) || new Date(dpView.y, dpView.m, 1);
const last = new Date(dpView.y, dpView.m + 1, 0).getDate();
dpFocusYmd = cYmd(new Date(dpView.y, dpView.m, Math.min(keep.getDate(), last)));
renderDatePicker();
repositionOpenPop();
return;
}
if (t.closest("[data-dp-clear]")) { commitDate(""); return; }
if (t.closest("[data-dp-today]")) {
const today = cYmd(new Date());
const input = popAnchor;
const min = input ? dateFieldMin(input) : "";
const max = input ? dateFieldMax(input) : "";
if (inDateRange(today, min, max)) commitDate(today);
return;
}
const day = t.closest(".jn-dp-day");
if (day && !day.disabled) commitDate(day.dataset.ymd);
});
document.addEventListener("click", (e) => {
const t = e.target;
if (!menuEl || menuEl.hidden || !menuEl.contains(t)) return;
const opt = t.closest(".jn-menu-opt");
if (opt && !opt.disabled) commitSelect(+opt.dataset.index);
});
/* ---------- 事件委托 ---------- */
document.addEventListener("click", (e) => {
const t = e.target;
const themeBtn = t.closest("[data-theme-btn]");
if (themeBtn) { setTheme(themeBtn.dataset.themeBtn); return; }
const copyBtn = t.closest("[data-copy-text]");
if (copyBtn) {
const txt = copyBtn.dataset.copyText;
if (navigator.clipboard) navigator.clipboard.writeText(txt).then(() => toast("大写金额已复制"), () => toast(txt));
else toast(txt);
return;
}
const checkAll = t.closest("[data-check-all]");
if (checkAll) {
e.stopPropagation();
$$("[data-check]", root()).forEach((b) => {
b.checked = checkAll.checked;
const tr = b.closest("tr");
if (tr) tr.toggleAttribute("data-checked", checkAll.checked);
});
syncCheckAll();
return;
}
const check = t.closest("[data-check]");
if (check) {
e.stopPropagation();
const tr = check.closest("tr");
if (tr) tr.toggleAttribute("data-checked", check.checked);
syncCheckAll();
return;
}
if (t.closest("[data-clear-check]")) {
$$("[data-check]", root()).forEach((b) => {
b.checked = false;
const tr = b.closest("tr");
if (tr) tr.removeAttribute("data-checked");
});
const all = $("[data-check-all]", root());
if (all) { all.checked = false; all.indeterminate = false; }
syncCheckAll();
return;
}
const sw = t.closest("[data-switch]");
if (sw) { sw.setAttribute("aria-checked", String(sw.getAttribute("aria-checked") !== "true")); initCalc(); return; }
const calcAct = t.closest("[data-calc-act]");
if (calcAct) { calcAction(calcAct.dataset.calcAct); return; }
const refRate = t.closest("[data-ref-rate]");
if (refRate) { const f = refRate.closest("form"); if (f && f.rate) { f.rate.value = refRate.dataset.refRate; initCalc(); } return; }
if (t.closest("[data-apply-months]")) { applyCdMonths(); return; }
const histFill = t.closest("[data-hist-fill]");
if (histFill) { histRefill(+histFill.dataset.histFill); return; }
if (t.closest("[data-hist-clear]")) { dcHistSave([]); renderDcHist(); toast("本地历史已清空"); return; }
const dtab = t.closest("[data-dtab]");
if (dtab) { switchDrawerTab(dtab.dataset.dtab); return; }
const openModalBtn = t.closest("[data-open-modal]");
if (openModalBtn) { openModal(openModalBtn.dataset.openModal, openModalBtn); return; }
if (t.closest("[data-close-modal]")) { closeModal(); return; }
const opener = t.closest("[data-open-detail]");
if (opener) { if (!t.closest("a,button,input,select,textarea,label")) openDetail(opener.dataset.openDetail); return; }
if (t.closest("[data-close-drawer]")) { closeOverlays(); return; }
});
document.addEventListener("change", (e) => {
if (e.target.closest("[data-calc-interest]") || e.target.closest("[data-calc-discount]")) { syncCalcModeRows(e.target); initCalc(); }
});
document.addEventListener("input", (e) => {
if (e.target.closest(".form-field") || isDateField(e.target)) setErr(e.target, "");
if (e.target.closest("[data-calc-interest]") || e.target.closest("[data-calc-discount]")) {
const ci = e.target.closest("[data-calc-interest]");
if (ci) {
if (e.target.id === "ci-days" && e.target.value) { ci.d1.value = ""; ci.d2.value = ""; const l = $("[data-ci-range-label]", root()); if (l) l.textContent = ""; }
if ((e.target.id === "ci-d1" || e.target.id === "ci-d2") && e.target.value) { ci.days.value = ""; }
}
initCalc();
}
});
document.addEventListener("keydown", (e) => {
if (e.key === "Enter" && e.target.matches && e.target.matches("[data-open-detail]")) openDetail(e.target.dataset.openDetail);
if (popKind === "menu" && menuEl && !menuEl.hidden) {
const opts = $$(".jn-menu-opt:not(:disabled)", menuEl);
if (e.key === "Escape") { e.preventDefault(); closePops(); return; }
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
if (!opts.length) return;
const cur = opts.indexOf(document.activeElement);
const next = e.key === "ArrowDown"
? (cur + 1) % opts.length
: (cur <= 0 ? opts.length - 1 : cur - 1);
opts[next].focus();
return;
}
if (e.key === "Home" && opts[0]) { e.preventDefault(); opts[0].focus(); return; }
if (e.key === "End" && opts.length) { e.preventDefault(); opts[opts.length - 1].focus(); return; }
if ((e.key === "Enter" || e.key === " ") && document.activeElement && document.activeElement.classList.contains("jn-menu-opt")) {
e.preventDefault();
commitSelect(+document.activeElement.dataset.index);
return;
}
if (e.key === "Tab") { closePops(); return; }
}
if (popKind === "date" && dpEl && !dpEl.hidden) {
if (e.key === "Escape") { e.preventDefault(); closePops(); return; }
if (e.key === "Tab") { e.preventDefault(); closePops(); return; }
if (dpMode === "year" || dpMode === "month") {
const picks = $$(".jn-dp-pick:not(:disabled)", dpEl);
if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
if (!picks.length) return;
const cols = 3;
const cur = picks.indexOf(document.activeElement);
const i = cur < 0 ? 0 : cur;
let next = i;
if (e.key === "ArrowLeft") next = i <= 0 ? picks.length - 1 : i - 1;
if (e.key === "ArrowRight") next = (i + 1) % picks.length;
if (e.key === "ArrowUp") next = (i - cols + picks.length) % picks.length;
if (e.key === "ArrowDown") next = (i + cols) % picks.length;
picks[next].focus();
dpFocusPick = dpMode === "year" ? +picks[next].dataset.dpYear : +picks[next].dataset.dpMonth;
return;
}
if ((e.key === "Enter" || e.key === " ") && document.activeElement && document.activeElement.classList.contains("jn-dp-pick") && !document.activeElement.disabled) {
e.preventDefault();
document.activeElement.click();
return;
}
if (e.key === "PageUp") { e.preventDefault(); shiftDpNav(-1); return; }
if (e.key === "PageDown") { e.preventDefault(); shiftDpNav(1); return; }
} else {
if (e.key === "ArrowLeft") { e.preventDefault(); shiftDpFocus(-1); return; }
if (e.key === "ArrowRight") { e.preventDefault(); shiftDpFocus(1); return; }
if (e.key === "ArrowUp") { e.preventDefault(); shiftDpFocus(-7); return; }
if (e.key === "ArrowDown") { e.preventDefault(); shiftDpFocus(7); return; }
if (e.key === "PageUp") { e.preventDefault(); shiftDpMonth(-1); return; }
if (e.key === "PageDown") { e.preventDefault(); shiftDpMonth(1); return; }
if (e.key === "Home") { e.preventDefault(); shiftDpFocus(-((cParseYmd(dpFocusYmd) || new Date()).getDay())); return; }
if (e.key === "End") { e.preventDefault(); shiftDpFocus(6 - ((cParseYmd(dpFocusYmd) || new Date()).getDay())); return; }
if (e.key === "Enter" && document.activeElement && document.activeElement.classList.contains("jn-dp-day") && !document.activeElement.disabled) {
e.preventDefault();
commitDate(document.activeElement.dataset.ymd);
return;
}
}
}
const dateInp = e.target.closest && e.target.closest("input");
if (dateInp && isDateField(dateInp) && !dateInp.disabled && (e.key === "ArrowDown" || e.key === " " || (e.altKey && e.key === "ArrowDown"))) {
e.preventDefault();
openDatePicker(dateInp);
return;
}
const sel = e.target.closest && e.target.closest("select");
if (nativeSelect(sel) && !sel.disabled && (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === " " || e.key === "Enter")) {
e.preventDefault();
openSelectMenu(sel);
return;
}
if (e.key === "Escape") {
if (closePops()) return;
closeOverlays(); closeModal();
}
});
/* — 抽屉拖拽关闭(1:1 跟手 + 速度判定 + 边界阻尼) — */
let drag = null;
document.addEventListener("pointerdown", (e) => {
const grip = e.target.closest("[data-grip]");
const r = root();
if (!grip || !r) return;
if (drag) return;
drag = { startX: e.clientX, dx: 0, v: 0, lastX: e.clientX, lastT: performance.now() };
$("[data-drawer]", r).setAttribute("data-dragging", "");
grip.setPointerCapture?.(e.pointerId);
});
document.addEventListener("pointermove", (e) => {
if (!drag) return;
const now = performance.now();
const dt = Math.max(now - drag.lastT, 1);
drag.v = 0.7 * drag.v + 0.3 * ((e.clientX - drag.lastX) / dt);
drag.lastX = e.clientX; drag.lastT = now;
let dx = e.clientX - drag.startX;
if (dx < 0) dx = dx * 0.25;
drag.dx = dx;
const d = $("[data-drawer]", root());
if (d) d.style.transform = `translateX(${dx}px)`;
});
function endDrag() {
if (!drag) return;
const d = $("[data-drawer]", root());
if (d) {
d.removeAttribute("data-dragging");
if (drag.dx > 110 || drag.v > 0.11) closeOverlays();
else d.style.transform = "translateX(0)";
}
drag = null;
}
document.addEventListener("pointerup", endDrag);
document.addEventListener("pointercancel", endDrag);
/* — 按住确认(慢填充 1.4s linear / 松手回弹;按住完成后提交目标表单) — */
let holdTimer = null;
document.addEventListener("pointerdown", (e) => {
const btn = e.target.closest("[data-hold-delete]");
if (!btn) return;
btn.setAttribute("data-holding", "");
clearTimeout(holdTimer);
holdTimer = setTimeout(() => {
btn.removeAttribute("data-holding");
const sel = btn.dataset.holdDelete;
const form = sel && sel !== "1" ? document.querySelector(sel) : btn.closest("form");
if (form) form.submit();
else toast("已确认");
}, 1400);
});
["pointerup", "pointerleave", "pointercancel"].forEach((ev) =>
document.addEventListener(ev, (e) => {
const btn = e.target.closest && e.target.closest("[data-hold-delete]");
if (btn) { clearTimeout(holdTimer); btn.removeAttribute("data-holding"); }
})
);
document.addEventListener("focusout", (e) => {
const input = e.target;
if (!isDateField(input) || input.disabled || input.readOnly) return;
const next = e.relatedTarget;
if (dpEl && next && dpEl.contains(next)) return;
applyDateValue(input);
});
document.addEventListener("submit", (e) => {
const form = e.target;
if (!form || form.tagName !== "FORM") return;
if (!normalizeFormDates(form)) {
e.preventDefault();
e.stopPropagation();
}
}, true);
/* ---------- 启动 ---------- */
document.addEventListener("DOMContentLoaded", () => {
syncThemeButtons();
syncCheckAll();
initCalc();
enhanceDateInputs();
const mo = new MutationObserver((recs) => {
recs.forEach((r) => {
r.addedNodes.forEach((n) => {
if (n.nodeType !== 1) return;
if (isDateField(n)) armDateInput(n);
else enhanceDateInputs(n);
});
});
});
mo.observe(document.body, { childList: true, subtree: true });
});