Initial commit
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
// admin.js — legacy reference file, not imported by any HTML page.
|
||||
// admin-dashboard.html uses auth.js + inline scripts exclusively.
|
||||
// Kept here as a reference stub; safe to delete if no longer needed.
|
||||
|
||||
// All shared utilities (authFetch, logoutUser, guardAuth, escapeHtml,
|
||||
// reviewBadge, buildYearOptions) are now in /js/auth.js.
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* auth.js — shared utilities loaded by every protected page.
|
||||
*
|
||||
* Provides:
|
||||
* authFetch(url, options) — fetch with Bearer token + auto-redirect on 401
|
||||
* logoutUser() — clear storage and redirect to /login
|
||||
* guardAuth(requiredRoles) — redirect if token missing or role not in list
|
||||
* escapeHtml(str) — XSS-safe string for innerHTML insertion
|
||||
* reviewBadge(status) — returns safe HTML badge string
|
||||
* buildYearOptions(selectId, def) — populate a <select> with current year - 3 years
|
||||
* initSessionWarning() — toast warning + auto-logout before JWT expiry (#17)
|
||||
* makeLabelsKeyboardAccessible(root) — make upload labels keyboard-navigable (#18)
|
||||
*/
|
||||
|
||||
(function () {
|
||||
|
||||
/* ── escapeHtml ──────────────────────────────────────────────────────── */
|
||||
window.escapeHtml = function (str) {
|
||||
return String(str == null ? "" : str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
};
|
||||
|
||||
/* ── authFetch ───────────────────────────────────────────────────────── */
|
||||
window.authFetch = async function (url, options = {}) {
|
||||
const token = localStorage.getItem("token");
|
||||
options.headers = {
|
||||
...(options.headers || {}),
|
||||
Authorization: "Bearer " + token,
|
||||
};
|
||||
const res = await fetch(url, options);
|
||||
if (res.status === 401) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("selected_tax_year");
|
||||
window.location.href = "/login";
|
||||
return null;
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ── logoutUser ──────────────────────────────────────────────────────── */
|
||||
window.logoutUser = function () {
|
||||
const role = localStorage.getItem("role");
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("selected_tax_year");
|
||||
window.location.href = "/login";
|
||||
};
|
||||
|
||||
/* ── guardAuth ───────────────────────────────────────────────────────── */
|
||||
window.guardAuth = function (requiredRoles = ["user"]) {
|
||||
const token = localStorage.getItem("token");
|
||||
const role = localStorage.getItem("role");
|
||||
if (!token || !requiredRoles.includes(role)) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("selected_tax_year");
|
||||
window.location.href = "/login";
|
||||
}
|
||||
};
|
||||
|
||||
/* ── reviewBadge ─────────────────────────────────────────────────────── */
|
||||
window.reviewBadge = function (reviewStatus) {
|
||||
const map = {
|
||||
approved: { bg: "#e6f9ec", color: "#2e7d32", text: `<span class="material-symbols-outlined">check</span> Approved` },
|
||||
rejected: { bg: "#fdecea", color: "#c62828", text: `<span class="material-symbols-outlined">close</span> Rejected` },
|
||||
pending: { bg: "#fff8e1", color: "#f57f17", text: `<span class="material-symbols-outlined">pending</span> Pending Review` },
|
||||
};
|
||||
const s = map[reviewStatus] || map.pending;
|
||||
return `<span style="
|
||||
display:inline-block;padding:2px 8px;border-radius:20px;
|
||||
font-size:11px;font-weight:600;
|
||||
background:${s.bg};color:${s.color};vertical-align:middle;margin-left:6px;
|
||||
">${s.text}</span>`;
|
||||
};
|
||||
|
||||
/* ── buildYearOptions ────────────────────────────────────────────────── */
|
||||
window.buildYearOptions = function (selectId, defaultYear) {
|
||||
const sel = document.getElementById(selectId);
|
||||
if (!sel) return;
|
||||
sel.innerHTML = "";
|
||||
const cur = new Date().getFullYear();
|
||||
const def = defaultYear || cur;
|
||||
for (let y = cur; y >= cur - 3; y--) {
|
||||
const o = document.createElement("option");
|
||||
o.value = y;
|
||||
o.textContent = y;
|
||||
if (y === def) o.selected = true;
|
||||
sel.appendChild(o);
|
||||
}
|
||||
};
|
||||
|
||||
/* ── initSessionWarning (#17) ────────────────────────────────────────── */
|
||||
/**
|
||||
* Call once after guardAuth() on every protected page.
|
||||
* Shows a persistent warning toast 5 minutes before token expiry,
|
||||
* then auto-logs out when the token actually expires.
|
||||
*/
|
||||
window.initSessionWarning = function () {
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) return;
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split(".")[1]));
|
||||
const expiresIn = (payload.exp * 1000) - Date.now();
|
||||
|
||||
// Already expired — kick out immediately
|
||||
if (expiresIn <= 0) { window.logoutUser(); return; }
|
||||
|
||||
// Warn 5 minutes before expiry
|
||||
const warnAt = expiresIn - 5 * 60 * 1000;
|
||||
if (warnAt > 0) {
|
||||
setTimeout(() => {
|
||||
if (window.showToast) {
|
||||
showToast("Your session expires in 5 minutes. Save your work.", "warning", 0);
|
||||
}
|
||||
}, warnAt);
|
||||
}
|
||||
|
||||
// Auto-logout at exact expiry
|
||||
setTimeout(() => {
|
||||
if (window.showToast) showToast("Session expired. Redirecting to login…", "info");
|
||||
setTimeout(window.logoutUser, 2000);
|
||||
}, expiresIn);
|
||||
|
||||
} catch (e) {
|
||||
// Malformed token — let the next API call handle it via 401
|
||||
}
|
||||
};
|
||||
|
||||
/* ── makeLabelsKeyboardAccessible (#18) ─────────────────────────────── */
|
||||
/**
|
||||
* Make styled <label> upload buttons keyboard-accessible.
|
||||
* Call after rendering any upload labels with tabindex="0".
|
||||
* @param {Element} [root=document] — scope the search to a container
|
||||
*/
|
||||
window.makeLabelsKeyboardAccessible = function (root) {
|
||||
const scope = root || document;
|
||||
scope.querySelectorAll("label.upload-label[tabindex='0']").forEach(lbl => {
|
||||
if (lbl._kbAttached) return;
|
||||
lbl._kbAttached = true;
|
||||
lbl.addEventListener("keydown", e => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
lbl.click();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* confirm-modal.js — non-blocking replacement for window.confirm().
|
||||
*
|
||||
* Usage:
|
||||
* const ok = await confirmModal("Delete this document?");
|
||||
* if (!ok) return;
|
||||
*
|
||||
* Optional second argument for the confirm button label:
|
||||
* await confirmModal("Remove user?", "Delete")
|
||||
*/
|
||||
|
||||
(function () {
|
||||
/* Inject styles once */
|
||||
if (!document.getElementById("confirm-modal-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "confirm-modal-styles";
|
||||
style.textContent = `
|
||||
.cm-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.35);
|
||||
z-index: 100000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: cm-fade-in 0.15s ease;
|
||||
}
|
||||
.cm-box {
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 28px 32px;
|
||||
max-width: 380px;
|
||||
width: 90%;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.18);
|
||||
text-align: center;
|
||||
animation: cm-slide-in 0.15s ease;
|
||||
}
|
||||
.cm-icon {
|
||||
font-size: 36px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.cm-message {
|
||||
font-family: "Poppins", "Segoe UI", sans-serif;
|
||||
font-size: 15px;
|
||||
color: #333;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 22px;
|
||||
white-space: pre-line;
|
||||
}
|
||||
.cm-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
}
|
||||
.cm-btn {
|
||||
padding: 10px 24px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.cm-btn:hover { opacity: 0.85; }
|
||||
.cm-btn-cancel { background: #f0f0f0; color: #555; }
|
||||
.cm-btn-confirm { background: #ff4d4d; color: #fff; }
|
||||
@keyframes cm-fade-in { from { opacity:0 } to { opacity:1 } }
|
||||
@keyframes cm-slide-in { from { transform:scale(0.92) } to { transform:scale(1) } }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} message — text shown in the modal
|
||||
* @param {string} [confirmLabel="Confirm"] — label for the confirm button
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
window.confirmModal = function (message, confirmLabel = "Confirm") {
|
||||
return new Promise((resolve) => {
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.className = "cm-backdrop";
|
||||
|
||||
backdrop.innerHTML = `
|
||||
<div class="cm-box" role="dialog" aria-modal="true">
|
||||
<div class="cm-icon"><span class="material-symbols-outlined">warning</span></div>
|
||||
<div class="cm-message">${escapeHtml ? escapeHtml(message) : message}</div>
|
||||
<div class="cm-actions">
|
||||
<button class="cm-btn cm-btn-cancel" id="cm-cancel">Cancel</button>
|
||||
<button class="cm-btn cm-btn-confirm" id="cm-confirm">${confirmLabel}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
function cleanup(result) {
|
||||
backdrop.remove();
|
||||
resolve(result);
|
||||
}
|
||||
|
||||
backdrop.querySelector("#cm-cancel").addEventListener("click", () => cleanup(false));
|
||||
backdrop.querySelector("#cm-confirm").addEventListener("click", () => cleanup(true));
|
||||
|
||||
/* Close on backdrop click */
|
||||
backdrop.addEventListener("click", (e) => {
|
||||
if (e.target === backdrop) cleanup(false);
|
||||
});
|
||||
|
||||
/* Close on Escape */
|
||||
function onKeyDown(e) {
|
||||
if (e.key === "Escape") { document.removeEventListener("keydown", onKeyDown); cleanup(false); }
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
|
||||
document.body.appendChild(backdrop);
|
||||
/* Focus the cancel button by default (safer UX) */
|
||||
backdrop.querySelector("#cm-cancel").focus();
|
||||
});
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Password strength indicator.
|
||||
* Call initPasswordStrength("inputId") to attach to a password field.
|
||||
* A bar + label appear below the field automatically.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
if (!document.getElementById("pw-strength-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "pw-strength-styles";
|
||||
style.textContent = `
|
||||
.pw-strength-bar-wrap {
|
||||
height: 4px;
|
||||
background: #e0e0e0;
|
||||
border-radius: 2px;
|
||||
margin-top: -8px;
|
||||
margin-bottom: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.pw-strength-bar {
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
transition: width 0.3s ease, background 0.3s ease;
|
||||
width: 0;
|
||||
}
|
||||
.pw-strength-label {
|
||||
font-size: 12px;
|
||||
margin-bottom: 10px;
|
||||
margin-top: -6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.pw-weak { background: #c62828; }
|
||||
.pw-medium { background: #f57f17; }
|
||||
.pw-strong { background: #2e7d32; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function checkStrength(pw) {
|
||||
if (!pw || pw.length < 8) return { level: "weak", pct: 25, label: "Too short (min 8 chars)", cls: "pw-weak" };
|
||||
const hasUpper = /[A-Z]/.test(pw);
|
||||
const hasNum = /[0-9]/.test(pw);
|
||||
const hasSymbol = /[^A-Za-z0-9]/.test(pw);
|
||||
const long = pw.length >= 12;
|
||||
|
||||
const score = [hasUpper, hasNum, hasSymbol, long].filter(Boolean).length;
|
||||
|
||||
if (score <= 1) return { level: "weak", pct: 33, label: "Weak — add uppercase & numbers", cls: "pw-weak" };
|
||||
if (score === 2) return { level: "medium", pct: 66, label: "Medium — getting better", cls: "pw-medium" };
|
||||
return { level: "strong", pct: 100, label: `Strong password <span class="material-symbols-outlined">check</span>`, cls: "pw-strong" };
|
||||
}
|
||||
|
||||
window.initPasswordStrength = function (inputId) {
|
||||
const input = document.getElementById(inputId);
|
||||
if (!input) return;
|
||||
|
||||
// Create bar + label
|
||||
const barWrap = document.createElement("div");
|
||||
barWrap.className = "pw-strength-bar-wrap";
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "pw-strength-bar";
|
||||
barWrap.appendChild(bar);
|
||||
|
||||
const label = document.createElement("div");
|
||||
label.className = "pw-strength-label";
|
||||
label.style.color = "#888";
|
||||
|
||||
// Insert after input's parent wrapper (handles both plain input and wrapped input)
|
||||
const after = input.closest("div") || input;
|
||||
after.after(label);
|
||||
after.after(barWrap);
|
||||
|
||||
input.addEventListener("input", () => {
|
||||
const val = input.value;
|
||||
if (!val) {
|
||||
bar.style.width = "0";
|
||||
bar.className = "pw-strength-bar";
|
||||
label.textContent = "";
|
||||
return;
|
||||
}
|
||||
const { pct, label: lbl, cls } = checkStrength(val);
|
||||
bar.style.width = pct + "%";
|
||||
bar.className = "pw-strength-bar " + cls;
|
||||
label.textContent = lbl;
|
||||
label.style.color = cls === "pw-weak" ? "#c62828" : cls === "pw-medium" ? "#f57f17" : "#2e7d32";
|
||||
});
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,70 @@
|
||||
async function signupUser() {
|
||||
const name = document.getElementById('name')?.value?.trim() || '';
|
||||
const email = document.getElementById('email')?.value?.trim() || '';
|
||||
const phone = document.getElementById('phone')?.value?.trim() || '';
|
||||
const password = document.getElementById('password')?.value || '';
|
||||
|
||||
if (!name || !email || !password) {
|
||||
showToast('Please fill in all required fields', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/signup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, email, phone, password })
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
if (!res.ok) {
|
||||
showToast(`Signup failed: ${data.detail || data.error || 'Unknown error'}`, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Email verification required — show message, do NOT log in
|
||||
if (data.email_verification_required) {
|
||||
const container = document.getElementById('signupForm')?.closest('.container')
|
||||
|| document.querySelector('.container');
|
||||
if (container) {
|
||||
container.innerHTML = `
|
||||
<div style="text-align:center;padding:10px 0;">
|
||||
<div style="font-size:52px;margin-bottom:18px;">📧</div>
|
||||
<h2 style="color:#0077c8;margin-bottom:14px;">Check your email</h2>
|
||||
<p style="color:#555;font-size:15px;line-height:1.7;margin-bottom:20px;">
|
||||
We've sent a verification link to<br>
|
||||
<strong>${escapeHtml ? escapeHtml(email) : email}</strong><br><br>
|
||||
Click the link in the email to activate your account.
|
||||
</p>
|
||||
<p style="font-size:13px;color:#888;margin-bottom:6px;">Didn't receive it?</p>
|
||||
<a href="/resend-verification"
|
||||
style="color:#FF7F11;font-weight:600;font-size:14px;text-decoration:none;">
|
||||
Resend verification email
|
||||
</a>
|
||||
<div style="margin-top:20px;">
|
||||
<a href="/login" style="color:#0077c8;font-size:14px;">Back to Login</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
showToast('Account created! Check your email to verify before logging in.', 'success', 6000);
|
||||
window.location.href = '/login';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Admin accounts created via backend bypass verification — log them in directly
|
||||
if (data.access_token) {
|
||||
localStorage.setItem('token', data.access_token);
|
||||
localStorage.setItem('role', data.role || 'user');
|
||||
localStorage.setItem('user_id', data.user_id || '');
|
||||
window.location.href = '/dashboard';
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error('Signup error', err);
|
||||
showToast('Network error. Please try again.', 'error');
|
||||
}
|
||||
}
|
||||
window.signupUser = signupUser;
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Spinner helpers — no dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* showSpinner(container) // replace content with spinner
|
||||
* hideSpinner(container, html) // restore container with new html
|
||||
* spinnerHtml() // returns raw spinner html string (for innerHTML)
|
||||
*/
|
||||
|
||||
(function () {
|
||||
if (!document.getElementById("spinner-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "spinner-styles";
|
||||
style.textContent = `
|
||||
.spinner-wrap {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 40px 20px;
|
||||
}
|
||||
.spinner {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border: 3px solid #e0e0e0;
|
||||
border-top-color: #0077c8;
|
||||
border-radius: 50%;
|
||||
animation: _spin 0.7s linear infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.spinner.spinner-sm {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-width: 2px;
|
||||
}
|
||||
@keyframes _spin { to { transform: rotate(360deg); } }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
window.spinnerHtml = function (small = false) {
|
||||
return `<div class="spinner-wrap"><div class="spinner${small ? " spinner-sm" : ""}"></div></div>`;
|
||||
};
|
||||
|
||||
window.showSpinner = function (el) {
|
||||
if (!el) return;
|
||||
el._savedContent = el.innerHTML;
|
||||
el.innerHTML = spinnerHtml();
|
||||
};
|
||||
|
||||
window.hideSpinner = function (el, html) {
|
||||
if (!el) return;
|
||||
el.innerHTML = html !== undefined ? html : (el._savedContent || "");
|
||||
};
|
||||
|
||||
window.setButtonLoading = function(btn, isLoading, originalText = "") {
|
||||
if (!btn) return;
|
||||
if (isLoading) {
|
||||
btn.disabled = true;
|
||||
btn._savedText = btn.innerHTML;
|
||||
btn.innerHTML = `<div class="spinner spinner-sm" style="border-top-color:#fff; border-right-color:rgba(255,255,255,0.3); border-bottom-color:rgba(255,255,255,0.3); border-left-color:rgba(255,255,255,0.3); width:16px; height:16px; display:inline-block; vertical-align:middle; margin-right:8px;"></div> ${originalText || 'Processing...'}`;
|
||||
} else {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalText || btn._savedText || "";
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
(function() {
|
||||
function setTheme(isDark) {
|
||||
if (isDark) {
|
||||
document.documentElement.classList.add('dark-theme');
|
||||
if (document.body) document.body.classList.add('dark-theme');
|
||||
localStorage.setItem('theme', 'dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark-theme');
|
||||
if (document.body) document.body.classList.remove('dark-theme');
|
||||
localStorage.setItem('theme', 'light');
|
||||
}
|
||||
// Update all toggle icons if they exist
|
||||
document.querySelectorAll('.theme-toggle-icon').forEach(icon => {
|
||||
icon.textContent = isDark ? 'light_mode' : 'dark_mode';
|
||||
});
|
||||
}
|
||||
|
||||
window.toggleTheme = function() {
|
||||
const isDark = document.documentElement.classList.contains('dark-theme');
|
||||
setTheme(!isDark);
|
||||
};
|
||||
|
||||
function initTheme() {
|
||||
const savedTheme = localStorage.getItem('theme');
|
||||
|
||||
if (savedTheme === 'dark') {
|
||||
setTheme(true);
|
||||
} else {
|
||||
setTheme(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize immediately (for documentElement) to avoid flash
|
||||
initTheme();
|
||||
|
||||
// Also run on DOMContentLoaded to ensure body gets the class if script was in <head>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
initTheme();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Toast notification system — no dependencies, no libraries.
|
||||
* Usage:
|
||||
* showToast("Saved successfully") // green success
|
||||
* showToast("Something failed", "error") // red error
|
||||
* showToast("Processing...", "info", 0) // blue, stays until dismissed
|
||||
* showToast("Check your input", "warning") // orange warning
|
||||
*/
|
||||
|
||||
(function () {
|
||||
// Inject styles once
|
||||
if (!document.getElementById("toast-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "toast-styles";
|
||||
style.textContent = `
|
||||
#toast-container {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
z-index: 99999;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-width: 340px;
|
||||
}
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 13px 16px;
|
||||
border-radius: 10px;
|
||||
font-family: "Poppins", "Segoe UI", sans-serif;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.13);
|
||||
cursor: pointer;
|
||||
animation: toast-in 0.3s ease;
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
}
|
||||
.toast.toast-out {
|
||||
opacity: 0;
|
||||
transform: translateX(20px);
|
||||
}
|
||||
.toast.success { background:#e6f9ec; color:#1b5e20; border-left:4px solid #2e7d32; }
|
||||
.toast.error { background:#fdecea; color:#b71c1c; border-left:4px solid #c62828; }
|
||||
.toast.info { background:#e3f2fd; color:#0d47a1; border-left:4px solid #1565c0; }
|
||||
.toast.warning { background:#fff8e1; color:#e65100; border-left:4px solid #f57f17; }
|
||||
.toast-icon { font-size: 18px; flex-shrink: 0; margin-top: 1px; }
|
||||
.toast-msg { flex: 1; }
|
||||
.toast-close { font-size: 16px; cursor: pointer; opacity: 0.5; flex-shrink: 0; margin-top: 1px; }
|
||||
.toast-close:hover { opacity: 1; }
|
||||
@keyframes toast-in {
|
||||
from { opacity: 0; transform: translateX(20px); }
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function getContainer() {
|
||||
let c = document.getElementById("toast-container");
|
||||
if (!c) {
|
||||
c = document.createElement("div");
|
||||
c.id = "toast-container";
|
||||
document.body.appendChild(c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
const ICONS = {
|
||||
success: '<span class="material-symbols-outlined">check_circle</span>',
|
||||
error: '<span class="material-symbols-outlined">cancel</span>',
|
||||
info: '<span class="material-symbols-outlined">info</span>',
|
||||
warning: '<span class="material-symbols-outlined">warning</span>',
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string} message — text to show
|
||||
* @param {string} type — "success" | "error" | "info" | "warning"
|
||||
* @param {number} duration — ms before auto-dismiss (0 = stay until clicked)
|
||||
*/
|
||||
window.showToast = function (message, type = "success", duration = 3500) {
|
||||
const container = getContainer();
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast ${type}`;
|
||||
|
||||
toast.innerHTML = `
|
||||
<span class="toast-icon">${ICONS[type] || "💬"}</span>
|
||||
<span class="toast-msg">${message}</span>
|
||||
<span class="toast-close" title="Dismiss">✕</span>
|
||||
`;
|
||||
|
||||
function dismiss() {
|
||||
toast.classList.add("toast-out");
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}
|
||||
|
||||
toast.addEventListener("click", dismiss);
|
||||
|
||||
if (duration > 0) {
|
||||
setTimeout(dismiss, duration);
|
||||
}
|
||||
|
||||
container.appendChild(toast);
|
||||
return toast;
|
||||
};
|
||||
})();
|
||||
Reference in New Issue
Block a user