caddydash/frontend/js/common.js
2025-06-22 17:23:41 +08:00

59 lines
No EOL
2.4 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.

// js/common.js - 存放共享模块
const theme = {
init: (toggleElement) => {
const storedTheme = localStorage.getItem('theme');
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const currentTheme = storedTheme || (systemPrefersDark ? 'dark' : 'light');
theme.apply(currentTheme);
if (toggleElement) {
toggleElement.addEventListener('change', (e) => theme.apply(e.target.checked ? 'dark' : 'light'));
}
},
apply: (themeName) => {
document.documentElement.dataset.theme = themeName;
localStorage.setItem('theme', themeName);
const themeToggleInput = document.getElementById('theme-toggle-input');
if (themeToggleInput) {
themeToggleInput.checked = themeName === 'dark';
}
}
};
function hideToast(toastElement) {
if (!toastElement) return;
toastElement.classList.remove('show');
toastElement.addEventListener('transitionend', () => toastElement.remove(), { once: true });
}
const toast = {
show: (message, type = 'info', duration = 3000) => {
const toastContainer = document.getElementById('toast-container');
if (!toastContainer) return;
const icons = { success: 'fa-check-circle', error: 'fa-times-circle', info: 'fa-info-circle' };
const iconClass = icons[type] || 'fa-info-circle';
const toastElement = document.createElement('div');
toastElement.className = `toast ${type}`;
toastElement.innerHTML = `<i class="toast-icon fa-solid ${iconClass}"></i><p class="toast-message">${message}</p><button class="toast-close" data-toast-close>×</button>`;
toastContainer.appendChild(toastElement);
requestAnimationFrame(() => toastElement.classList.add('show'));
const timeoutId = setTimeout(() => hideToast(toastElement), duration);
toastElement.querySelector('[data-toast-close]').addEventListener('click', () => {
clearTimeout(timeoutId);
hideToast(toastElement);
});
}
};
function activateNav(pageId) {
const navLinks = document.querySelectorAll('.sidebar-nav a');
navLinks.forEach(link => {
link.classList.remove('active');
if (link.dataset.navId === pageId) {
link.classList.add('active');
}
});
}
// 导出模块
export { theme, toast, activateNav };