91 lines
2.6 KiB
JavaScript
91 lines
2.6 KiB
JavaScript
(function (global) {
|
|
var root = document.querySelector("[data-toast]");
|
|
if (!root) return;
|
|
|
|
var panel = root.querySelector("[data-toast-panel]");
|
|
var textEl = root.querySelector("[data-toast-text]");
|
|
var iconSuccess = root.querySelector("[data-toast-icon-success]");
|
|
var iconError = root.querySelector("[data-toast-icon-error]");
|
|
var hideTimer = 0;
|
|
var removeTimer = 0;
|
|
var DEFAULT_MS = 2600;
|
|
|
|
function normalizeType(type) {
|
|
var t = String(type || "").toLowerCase();
|
|
if (t === "success" || t === "ok") return "success";
|
|
// 失败态:error / fail / warning 等非成功统一走失败样式
|
|
return "error";
|
|
}
|
|
|
|
function clearTimers() {
|
|
if (hideTimer) {
|
|
window.clearTimeout(hideTimer);
|
|
hideTimer = 0;
|
|
}
|
|
if (removeTimer) {
|
|
window.clearTimeout(removeTimer);
|
|
removeTimer = 0;
|
|
}
|
|
}
|
|
|
|
function hide() {
|
|
root.classList.remove("is-visible");
|
|
removeTimer = window.setTimeout(function () {
|
|
root.setAttribute("hidden", "");
|
|
root.classList.remove("is-success", "is-error");
|
|
if (textEl) textEl.textContent = "";
|
|
if (iconSuccess) {
|
|
iconSuccess.setAttribute("hidden", "");
|
|
iconSuccess.style.display = "none";
|
|
}
|
|
if (iconError) {
|
|
iconError.setAttribute("hidden", "");
|
|
iconError.style.display = "none";
|
|
}
|
|
}, 220);
|
|
}
|
|
|
|
function showToast(message, type, duration) {
|
|
var tip = String(message == null ? "" : message).trim();
|
|
if (!tip || !panel || !textEl) return;
|
|
|
|
var kind = normalizeType(type);
|
|
clearTimers();
|
|
|
|
root.classList.remove("is-success", "is-error", "is-visible");
|
|
root.classList.add(kind === "success" ? "is-success" : "is-error");
|
|
textEl.textContent = tip;
|
|
|
|
if (iconSuccess) {
|
|
if (kind === "success") {
|
|
iconSuccess.removeAttribute("hidden");
|
|
iconSuccess.style.display = "";
|
|
} else {
|
|
iconSuccess.setAttribute("hidden", "");
|
|
iconSuccess.style.display = "none";
|
|
}
|
|
}
|
|
if (iconError) {
|
|
if (kind === "error") {
|
|
iconError.removeAttribute("hidden");
|
|
iconError.style.display = "";
|
|
} else {
|
|
iconError.setAttribute("hidden", "");
|
|
iconError.style.display = "none";
|
|
}
|
|
}
|
|
|
|
root.removeAttribute("hidden");
|
|
// 下一帧再加 visible,保证过渡动画生效
|
|
window.requestAnimationFrame(function () {
|
|
root.classList.add("is-visible");
|
|
});
|
|
|
|
var ms = Number(duration);
|
|
if (!ms || ms < 800) ms = DEFAULT_MS;
|
|
hideTimer = window.setTimeout(hide, ms);
|
|
}
|
|
|
|
global.showToast = showToast;
|
|
})(window);
|