Files
jinniu-daikuan/public/assets/fusion.js
T
f729e49710 HEL-349: fix night-mode selects, anchored date popover, and scrollbars
Native select lists and date calendars could not be reliably themed or positioned, so popovers now use existing fusion tokens and stay anchored to the trigger.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-09-01 21:56:19 +08:00

896 lines
41 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 金牛贷款档案 · 霜曜融合交互层(服务端渲染版)
行为模型与定版样板一致:属性驱动、事件委托、可打断。 */
"use strict";
const $ = (s, r) => (r || document).querySelector(s);
const $$ = (s, r) => Array.from((r || document).querySelectorAll(s));
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const root = () => document.querySelector("[data-variant-root]");
/* ---------- 主题(日间 / 夜间,记住选择,无首屏闪白由页头内联脚本保证) ---------- */
const THEME_KEY = "jn_theme";
function currentTheme() {
const r = root();
return r && r.getAttribute("data-theme") === "night" ? "night" : "day";
}
function setTheme(next, animate = true) {
if (next !== "day" && next !== "night") return;
const r = root(); if (!r) return;
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (animate && !reduce) {
r.setAttribute("data-theme-anim", "");
setTimeout(() => r.removeAttribute("data-theme-anim"), 240);
}
if (next === "night") r.setAttribute("data-theme", "night");
else r.removeAttribute("data-theme");
try { localStorage.setItem(THEME_KEY, next); } catch (e) {}
$$("[data-theme-btn]", r).forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.themeBtn === next)));
$$("img[data-brand-logo]", r).forEach((img) => {
const src = next === "night" ? img.dataset.logoNight : img.dataset.logoDay;
if (src) img.src = src;
});
}
function syncThemeButtons() { setTheme(currentTheme(), false); }
/* ---------- Toast(与定版同结构) ---------- */
const toastRoot = document.createElement("div");
document.addEventListener("DOMContentLoaded", () => document.body.appendChild(toastRoot));
function toast(msg) {
toastRoot.innerHTML = `<div class="v-fusion"><div class="toast-wrap"><div class="toast" data-hidden role="status"><span class="tick" aria-hidden="true">✓</span><span>${esc(msg)}</span></div></div></div>`;
const t = toastRoot.querySelector(".toast");
requestAnimationFrame(() => requestAnimationFrame(() => t.removeAttribute("data-hidden")));
clearTimeout(toast._t);
toast._t = setTimeout(() => t.setAttribute("data-hidden", ""), 2600);
}
window.jnToast = toast;
/* ---------- 勾选:三态全选 + 零几何动效 + 批量条 ---------- */
function syncCheckAll() {
const r = root(); if (!r) return;
const all = $("[data-check-all]", r);
if (!all) return;
const boxes = $$("[data-check]", r);
const n = boxes.filter((b) => b.checked).length;
all.checked = n > 0 && n === boxes.length;
all.indeterminate = n > 0 && n < boxes.length;
const slot = $("[data-batch-slot]", r);
if (slot) {
slot.toggleAttribute("data-has-selection", n > 0);
const cnt = $("[data-batch-count]", slot);
if (cnt) cnt.textContent = n;
slot.style.display = n > 0 ? "" : "none";
}
}
/* ---------- 抽屉(行点击 · 拉取服务端片段) ---------- */
let openArchiveId = null;
function openDetail(id) {
const r = root(); if (!r) return;
openArchiveId = id;
const d = $("[data-drawer]", r);
fetch(`index.php?action=archive_detail&id=${encodeURIComponent(id)}&drawer=1`, { credentials: "same-origin" })
.then((res) => res.text())
.then((html) => {
if (openArchiveId !== id) return;
d.innerHTML = html;
r.setAttribute("data-drawer-open", "");
d.setAttribute("data-open-state", "");
const c = $(".drawer-close", r); if (c) c.focus();
})
.catch(() => { location.href = `index.php?action=archive_detail&id=${encodeURIComponent(id)}`; });
}
function switchDrawerTab(tab) {
if (!openArchiveId) return;
const r = root(); const d = $("[data-drawer]", r);
fetch(`index.php?action=archive_detail&id=${encodeURIComponent(openArchiveId)}&drawer=1&dtab=${encodeURIComponent(tab)}`, { credentials: "same-origin" })
.then((res) => res.text())
.then((html) => { d.innerHTML = html; })
.catch(() => {});
}
function closeOverlays() {
const r = root(); if (!r) return;
r.removeAttribute("data-drawer-open");
const d = $("[data-drawer]", r);
if (d && d.hasAttribute("data-open-state")) {
d.removeAttribute("data-dragging");
d.style.transform = "translateX(102%)";
setTimeout(() => { d.removeAttribute("data-open-state"); d.style.transform = ""; }, 460);
}
openArchiveId = null;
}
/* ---------- 弹层(导入等,服务端已渲染,切属性即可) ---------- */
function openModal(name) { root()?.setAttribute("data-modal-open", name); }
function closeModal() { root()?.removeAttribute("data-modal-open"); }
/* ---------- 表单错误提示(与定版同结构) ---------- */
function setErr(input, msg) {
const field = input.closest(".form-field");
if (!field) return;
if (msg) {
field.setAttribute("data-error", "");
const e = field.querySelector("[data-err]");
if (e) e.textContent = msg;
input.setAttribute("aria-invalid", "true");
} else {
field.removeAttribute("data-error");
const e = field.querySelector("[data-err]");
if (e) e.textContent = "";
input.removeAttribute("aria-invalid");
}
}
window.jnSetErr = setErr;
/* ============================================================
计算器引擎(HEL-324/325 口径,与原系统一致,未删减)
============================================================ */
const CN_HOLIDAYS = (() => {
const H2025 = ["2025-01-01","2025-01-28","2025-01-29","2025-01-30","2025-01-31","2025-02-01","2025-02-02","2025-02-03","2025-02-04","2025-04-04","2025-04-05","2025-04-06","2025-05-01","2025-05-02","2025-05-03","2025-05-04","2025-05-05","2025-05-31","2025-06-01","2025-06-02","2025-10-01","2025-10-02","2025-10-03","2025-10-04","2025-10-05","2025-10-06","2025-10-07","2025-10-08"];
const H2026 = ["2026-01-01","2026-01-02","2026-01-03","2026-02-15","2026-02-16","2026-02-17","2026-02-18","2026-02-19","2026-02-20","2026-02-21","2026-02-22","2026-02-23","2026-04-04","2026-04-05","2026-04-06","2026-05-01","2026-05-02","2026-05-03","2026-05-04","2026-05-05","2026-06-19","2026-06-20","2026-06-21","2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"];
const S = {}; H2025.concat(H2026).forEach((x) => { S[x] = 1; }); return S;
})();
const cPad = (n) => (n < 10 ? "0" : "") + n;
const cYmd = (d) => d.getFullYear() + "-" + cPad(d.getMonth() + 1) + "-" + cPad(d.getDate());
function cParseYmd(s) { const p = String(s || "").split("-"); if (p.length !== 3) return null; const d = new Date(+p[0], +p[1] - 1, +p[2]); return isNaN(d.getTime()) ? null : d; }
function cIsNonWork(d) { const w = d.getDay(); return w === 0 || w === 6 || !!CN_HOLIDAYS[cYmd(d)]; }
function cNextWorkday(ymdStr) {
const d = cParseYmd(ymdStr); if (!d) return ymdStr;
for (let i = 0; i < 20; i++) { if (!cIsNonWork(d)) return cYmd(d); d.setDate(d.getDate() + 1); }
return cYmd(d);
}
function cAddMonths(y, m, day, add) {
const nm = m - 1 + add, ny = y + Math.floor(nm / 12), nmo = ((nm % 12) + 12) % 12;
const last = new Date(ny, nmo + 1, 0).getDate();
return new Date(ny, nmo, Math.min(day, last));
}
function cNum(s) { s = String(s || "").replace(/,/g, "").trim(); if (s === "") return NaN; const v = parseFloat(s); return isFinite(v) ? v : NaN; }
function cM2(n) { if (!isFinite(n)) return ""; const p = (Math.round(n * 100) / 100).toFixed(2).split("."); p[0] = p[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return p.join("."); }
function caps(n) {
if (!(n > 0)) return "—";
const units = ["", "拾", "佰", "仟"], big = ["", "万", "亿"];
let integer = Math.floor(n), decimal = Math.round((n - integer) * 100);
let s = "", i = 0;
if (integer === 0) s = "零";
while (integer > 0) {
let seg = integer % 10000, segStr = "";
for (let j = 0; seg > 0; j++) {
const d = seg % 10;
segStr = (d ? "零壹贰叁肆伍陆柒捌玖"[d] + units[j] : (segStr && !segStr.startsWith("零") ? "零" : "")) + segStr;
seg = Math.floor(seg / 10);
}
s = segStr + big[i] + s;
integer = Math.floor(integer / 10000); i++;
}
s += "元";
if (decimal === 0) s += "整";
else { const j = Math.floor(decimal / 10), f = decimal % 10; if (j) s += "零壹贰叁肆伍陆柒捌玖"[j] + "角"; if (f) s += "零壹贰叁肆伍陆柒捌玖"[f] + "分"; }
return "人民币" + s;
}
function ciDaysFromRange(d1, d2, mode) {
if (!d1 || !d2) return NaN;
const t0 = new Date(d1 + "T12:00:00").getTime(), t1 = new Date(d2 + "T12:00:00").getTime();
if (t1 < t0) return NaN;
const diff = Math.round((t1 - t0) / 86400000);
return mode === "inclusive" ? diff + 1 : diff;
}
function renderInterest() {
const r = root(); const f = r && $("[data-calc-interest]", r); if (!f) return;
const slot = $("[data-ci-result]", r);
const P = cNum(f.amt.value), rate = cNum(f.rate.value), kind = f.rateKind.value;
const basis = f.basis.value, cm = f.countMode.value;
const mode = (f.querySelector('input[name="ciDayMode"]:checked') || {}).value || "manual";
const fmtEl = $("[data-ci-fmt]", r), capEl = $("[data-ci-cap]", r);
if (fmtEl) fmtEl.innerHTML = isFinite(P) && P > 0 ? `格式化:<b>${cM2(P)}</b> 元` : "";
if (capEl) capEl.innerHTML = isFinite(P) && P > 0 ? `· 大写:<b>${caps(Math.floor(P)).replace(/^人民币/, "")}</b>` : "";
const rangeLabel = $("[data-ci-range-label]", r);
let days;
if (mode === "manual") { const n = parseInt(f.days.value, 10); days = isFinite(n) && n >= 0 ? n : NaN; if (rangeLabel) rangeLabel.textContent = ""; }
else { days = ciDaysFromRange(f.d1.value, f.d2.value, cm); if (rangeLabel) rangeLabel.textContent = isFinite(days) ? `→ 计息天数 ${days}` : ""; }
const invalid = !(P > 0) ? "请输入有效本金" : !(rate > 0) ? "请输入有效利率" : (!isFinite(days) || days < 0) ? "请检查计息天数或起止日期" : "";
if (invalid) {
window._ciLast = null;
slot.innerHTML = `
<div class="section-title" style="margin:0 0 8px;">计算结果</div>
<div class="calc-note" style="margin-top:2px;">${invalid},结果区即时更新</div>`;
return;
}
let interest, dref;
if (kind === "annual") { interest = P * (rate / 100) * (days / +basis); dref = (rate / 100) / +basis; }
else if (kind === "monthly") { interest = P * (rate / 100) * (days / 30); dref = (rate / 100) / 30; }
else { interest = P * (rate / 100) * days; dref = rate / 100; }
const total = P + interest;
const kindTxt = { annual: "年利率", monthly: "月利率", daily: "日利率" }[kind];
const formula = kind === "annual" ? `${cM2(P)} × ${rate}% ÷ ${basis} × ${days} 天` : kind === "monthly" ? `${cM2(P)} × ${rate}% ÷ 30 × ${days} 天` : `${cM2(P)} × ${rate}% × ${days} 天`;
window._ciLast = { text: `利息 ${cM2(interest)} 元 | 本息合计 ${cM2(total)} 元 | 天数 ${days}` };
slot.innerHTML = `
<div class="section-title" style="margin:0 0 8px;">计算结果</div>
<div style="padding:6px 0 4px;">
<div style="font-size:11px; font-weight:700; letter-spacing:0.12em; color:var(--gold);">应付利息</div>
<div class="calc-result-hero num">${cM2(interest)}</div>
<div class="calc-caps-block">
<span class="caps-label">大写</span>
<span class="calc-caps">${caps(interest)}</span>
<button type="button" class="caps-copy" data-copy-text="${esc(caps(interest))}">复制</button>
</div>
</div>
<div class="summary-row"><span>本息合计</span><b class="num">${cM2(total)} 元</b></div>
<div class="summary-row"><span>实际计息天数</span><b class="num">${days} 天</b></div>
<div class="summary-row"><span>参考日利率</span><b class="num" style="font-weight:600; font-size:12px;">${(dref * 100).toFixed(6)}%</b></div>
<div class="calc-note">参考日利率按当前利率种类换算,仅供参考 · ${kindTxt} ${rate}% · ${cm === "inclusive" ? "记首记尾" : "记首不记尾"} · ${basis} 天/年</div>
<div class="calc-formula num">${formula}</div>
<button type="button" class="btn btn--plain" style="width:100%; margin-top:12px;" data-calc-act="copy">复制结果</button>`;
}
/* — 承兑贴现计算器 — */
function dcHist() {
try { const raw = localStorage.getItem("dc_hist_v1"); if (raw) return JSON.parse(raw); } catch (e) {}
return [];
}
function dcHistSave(arr) { try { localStorage.setItem("dc_hist_v1", JSON.stringify(arr.slice(0, 30))); } catch (e) {} }
function fmtWanShort(n) { return n >= 10000 ? (n / 10000).toFixed(2).replace(/\.00$/, "") + " 万" : cM2(n); }
function renderDcHist() {
const box = document.querySelector("[data-dc-hist]"); if (!box) return;
const arr = dcHist();
box.innerHTML = arr.length ? arr.map((h, i) => `
<div class="hist-row">
<div><div class="hist-main num">${fmtWanShort(h.face)} · ${(+h.rate).toFixed(2)}%</div><div class="hist-sub num">${h.t} · ${h.days} 天</div></div>
<div class="hist-amt num">${cM2(h.net)}</div>
<button type="button" class="btn btn--plain btn--sm" data-hist-fill="${i}">回填</button>
</div>`).join("") : `<div class="calc-note" style="padding:10px 0 4px;">暂无历史记录,计算后点击「保存记录」</div>`;
}
function renderDiscount() {
const r = root(); const f = r && $("[data-calc-discount]", r); if (!f) return;
const slot = $("[data-cd-result]", r);
if (!f.now.value) { const t = new Date(); f.now.value = cYmd(t); }
const face = cNum(f.face.value);
const fmtEl = $("[data-cd-fmt]", r), capEl = $("[data-cd-cap]", r);
if (fmtEl) fmtEl.innerHTML = isFinite(face) && face > 0 ? `格式化:<b>${cM2(face)}</b> 元` : "";
if (capEl) capEl.innerHTML = isFinite(face) && face > 0 ? `· 大写:<b>${caps(Math.floor(face)).replace(/^人民币/, "")}</b>` : "";
const matMode = (f.querySelector('input[name="cdMatMode"]:checked') || {}).value || "date";
const holiday = $("[data-cd-holiday]", r)?.getAttribute("aria-checked") === "true";
const remote = $("[data-cd-remote]", r)?.getAttribute("aria-checked") === "true";
const rule = f.rule.value;
const dis = f.now.value, mat = f.due.value;
const invalid0 = !(face > 0) ? "票面金额须大于 0" : (matMode === "after" && !mat) ? "请先「推算到期日」或改选指定到期日" : (!dis || !mat) ? "请完善贴现日与到期日" : "";
if (invalid0) {
window._dcLast = null;
slot.innerHTML = `<div class="section-title" style="margin:0 0 8px;">计算结果</div><div class="calc-note" style="margin-top:2px;">${invalid0}</div>`;
return;
}
const matEff = holiday ? cNextWorkday(mat) : mat;
const d0 = cParseYmd(dis), d1 = cParseYmd(matEff);
const rawDiff = d0 && d1 ? Math.round((d1 - d0) / 86400000) : NaN;
const base = rule === "inclusive" ? rawDiff + 1 : rawDiff;
const days = isFinite(base) && base >= 0 ? base + (remote ? 3 : 0) : NaN;
if (!isFinite(days) || days <= 0) {
window._dcLast = null;
slot.innerHTML = `<div class="section-title" style="margin:0 0 8px;">计算结果</div><div class="calc-note" style="margin-top:2px;">贴现日须早于到期日,且计息天数须为正</div>`;
return;
}
const shiftDays = Math.max(0, Math.round(((cParseYmd(matEff) || 0) - (cParseYmd(mat) || 0)) / 86400000));
const netIn = cNum(f.netIn.value), per10 = cNum(f.per10.value);
let rate = cNum(f.rate.value), interest, revLine = "";
if (isFinite(netIn) && netIn > 0 && netIn < face) {
rate = (face - netIn) * 360 / (face * days) * 100;
if (!isFinite(rate) || !(rate > 0)) { slot.innerHTML = `<div class="section-title" style="margin:0 0 8px;">计算结果</div><div class="calc-note" style="margin-top:2px;">无法根据实付金额反推利率,请检查天数与金额</div>`; window._dcLast = null; return; }
interest = face - netIn;
f.rate.value = rate.toFixed(4);
revLine = `已按实付金额反推贴现年利率:${rate.toFixed(4)}%`;
} else if (isFinite(per10) && per10 > 0) {
interest = per10 * (face / 100000);
rate = (interest * 360 / (face * days)) * 100;
if (!isFinite(rate) || !(rate > 0)) { slot.innerHTML = `<div class="section-title" style="margin:0 0 8px;">计算结果</div><div class="calc-note" style="margin-top:2px;">无法根据每10万扣息反推利率</div>`; window._dcLast = null; return; }
f.rate.value = rate.toFixed(4);
revLine = `已按每10万扣息反推贴现年利率:${rate.toFixed(4)}%`;
} else {
if (!(rate > 0)) { slot.innerHTML = `<div class="section-title" style="margin:0 0 8px;">计算结果</div><div class="calc-note" style="margin-top:2px;">请输入贴现年利率,或填写反推字段</div>`; window._dcLast = null; return; }
interest = face * (rate / 100) * (days / 360);
}
const net = face - interest;
const ann = net > 0 ? (interest / net) * (360 / days) * 100 : NaN;
const p10 = face > 0 ? interest / (face / 100000) : NaN;
const dayNote = (remote ? "(含异地+3天)" : "") + (holiday ? ";到期日已按工作日顺延" : "");
window._dcLast = { face, intr: interest, net, days, rate: (+rate).toFixed(4), text: `票面 ${(face / 10000).toFixed(2)}万 | 贴现息 ${cM2(interest)}元 | 实付 ${cM2(net)}元 | 天数 ${days}天` };
slot.innerHTML = `
<div class="section-title" style="margin:0 0 8px;">计算结果</div>
<div style="padding:6px 0 4px;">
<div style="font-size:11px; font-weight:700; letter-spacing:0.12em; color:var(--gold);">实付金额</div>
<div class="calc-result-hero num">${cM2(net)}</div>
<div class="calc-caps-block">
<span class="caps-label">大写</span>
<span class="calc-caps">${caps(net)}</span>
<button type="button" class="caps-copy" data-copy-text="${esc(caps(net))}">复制</button>
</div>
</div>
<div class="summary-row"><span>贴现利息</span><b class="num">${cM2(interest)} 元</b></div>
<div class="summary-row"><span>贴现天数</span><b class="num">${days} 天 <span style="font-weight:500; font-size:11px; color:var(--text-3);">${dayNote}</span></b></div>
<div class="summary-row"><span>天数拆解</span><b class="num" style="font-weight:600; font-size:12px;">计息 ${base}${shiftDays ? `(含顺延 ${shiftDays})` : ""}${remote ? " + 异地 3" : ""}</b></div>
<div class="summary-row"><span>年化成本率</span><b class="num">${isFinite(ann) ? ann.toFixed(4) + "%" : "—"}</b></div>
<div class="summary-row"><span>每10万扣息</span><b class="num">${isFinite(p10) ? cM2(p10) + " 元" : "—"}</b></div>
${shiftDays ? `<div class="summary-row"><span>到期日顺延至</span><b class="num">${matEff}</b></div>` : ""}
${revLine ? `<div class="rev-line">${revLine}</div>` : ""}
<div class="calc-note">票据类型:${(f.querySelector('input[name="cdBill"]:checked') || {}).value === "commercial" ? "商业承兑汇票" : "银行承兑汇票"} · ${rule === "inclusive" ? "记首记尾" : "记首不记尾"} · 360 天/年</div>
<div class="calc-formula num">${cM2(face)} × ${(+rate).toFixed(4)}% ÷ 360 × ${days} 天 = ${cM2(interest)}</div>
<button type="button" class="btn btn--plain" style="width:100%; margin-top:12px;" data-calc-act="copy">复制结果</button>`;
}
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;
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") { 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 = ""; 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 = ""; 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 renderDatePicker() {
if (!dpEl || !popAnchor) return;
const input = popAnchor;
const min = parseLimit(input.min), max = parseLimit(input.max);
const selected = parseLimit(input.value);
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 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 += `<button type="button" class="jn-dp-day" data-ymd="${ymd}"${out ? " data-out" : ""}${ymd === today ? " data-today" : ""}${sel ? ' aria-selected="true"' : ""}${disabled ? " disabled" : ""} tabindex="${isFocus && !disabled ? "0" : "-1"}">${d.getDate()}</button>`;
}
dpEl.innerHTML = `
<div class="jn-dp-head">
<button type="button" class="jn-dp-nav" data-dp-nav="-1" aria-label="上一月">‹</button>
<div class="jn-dp-month" aria-live="polite">${y}年${m + 1}月</div>
<button type="button" class="jn-dp-nav" data-dp-nav="1" aria-label="下一月">›</button>
</div>
<div class="jn-dp-week">${WEEKDAYS.map((w) => `<span>${w}</span>`).join("")}</div>
<div class="jn-dp-grid">${days}</div>
<div class="jn-dp-foot"><button type="button" class="btn btn--plain btn--sm" data-dp-today>今天</button></div>`;
const focusBtn = dpEl.querySelector(`.jn-dp-day[data-ymd="${dpFocusYmd}"]:not(:disabled)`) || dpEl.querySelector(".jn-dp-day:not(:disabled)");
if (focusBtn) {
dpFocusYmd = focusBtn.dataset.ymd;
focusBtn.tabIndex = 0;
focusBtn.focus();
}
}
function openDatePicker(input) {
if (!input || input.type !== "date" || input.disabled || input.readOnly) return;
ensurePops();
if (popKind === "date" && popAnchor === input) { closePops(); return; }
closePops();
popAnchor = input;
popKind = "date";
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());
renderDatePicker();
placePopover(dpEl, input);
bindPopReposition(true);
}
function commitDate(ymd) {
const input = popAnchor;
if (!input || input.type !== "date") { closePops(); return; }
const min = parseLimit(input.min), max = parseLimit(input.max);
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 }));
}
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();
}
if (typeof HTMLInputElement !== "undefined" && HTMLInputElement.prototype.showPicker) {
const nativeShowPicker = HTMLInputElement.prototype.showPicker;
HTMLInputElement.prototype.showPicker = function () {
if (this.type === "date" && 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[type="date"]');
if (dateInp && dateInp.closest("[data-variant-root]")) {
if (dateInp.disabled || dateInp.readOnly) return;
e.preventDefault();
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 t = e.target;
if (!dpEl || dpEl.hidden || !dpEl.contains(t)) return;
const nav = t.closest("[data-dp-nav]");
if (nav) { shiftDpMonth(+nav.dataset.dpNav); return; }
if (t.closest("[data-dp-today]")) {
const today = cYmd(new Date());
const input = popAnchor;
const min = input ? parseLimit(input.min) : "";
const max = input ? parseLimit(input.max) : "";
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); 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")) 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 === "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[type="date"]');
if (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("DOMContentLoaded", () => {
syncThemeButtons();
syncCheckAll();
initCalc();
});