// 随机事件后台管理页事件代理,替代 Blade 内联 toggleEvent 函数。 let adminAutoactControlsBound = false; /** * 读取后台 layout 注入的 CSRF token。 * * @returns {string} */ function getCsrfToken() { return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; } /** * 根据接口返回状态更新随机事件行和按钮样式。 * * @param {HTMLButtonElement} button 状态切换按钮 * @param {boolean} enabled 是否启用 * @returns {void} */ function updateAutoactToggleState(button, enabled) { button.textContent = enabled ? "启用" : "禁用"; button.className = enabled ? "text-xs px-2 py-1 rounded bg-green-100 text-green-700 cursor-pointer" : "text-xs px-2 py-1 rounded bg-gray-200 text-gray-500 cursor-pointer"; // 行透明度是当前页面唯一的视觉状态,切换时必须和按钮文本保持同步。 button.closest("tr")?.classList.toggle("opacity-40", !enabled); } /** * 切换随机事件启用状态。 * * @param {HTMLButtonElement} button 状态切换按钮 * @returns {Promise} */ async function toggleAutoactEvent(button) { const toggleUrl = button.getAttribute("data-autoact-toggle-url") || ""; if (!toggleUrl || button.disabled) { return; } button.disabled = true; try { const response = await fetch(toggleUrl, { method: "POST", headers: { "X-CSRF-TOKEN": getCsrfToken(), "Content-Type": "application/json", "Accept": "application/json", }, }); const data = await response.json(); if (data?.status === "success") { updateAutoactToggleState(button, Boolean(data.enabled)); } } finally { button.disabled = false; } } /** * 绑定随机事件管理页按钮事件。 * * @returns {void} */ export function bindAdminAutoactControls() { if (adminAutoactControlsBound || typeof document === "undefined") { return; } adminAutoactControlsBound = true; document.addEventListener("click", (event) => { if (!(event.target instanceof Element)) { return; } const toggleButton = event.target.closest("[data-autoact-toggle-url]"); if (toggleButton instanceof HTMLButtonElement) { event.preventDefault(); void toggleAutoactEvent(toggleButton); } }); document.addEventListener("submit", (event) => { if (!(event.target instanceof HTMLFormElement)) { return; } const confirmMessage = event.target.getAttribute("data-autoact-delete-confirm"); if (confirmMessage && !window.confirm(confirmMessage)) { event.preventDefault(); } }); }