diff --git a/resources/js/admin/autoact.js b/resources/js/admin/autoact.js new file mode 100644 index 0000000..4730fcb --- /dev/null +++ b/resources/js/admin/autoact.js @@ -0,0 +1,87 @@ +// 随机事件后台管理页事件代理,替代 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); + } + }); +} diff --git a/resources/js/app.js b/resources/js/app.js index e59d6a0..ade837d 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -1 +1,5 @@ import './bootstrap'; +import { bindAdminAutoactControls } from './admin/autoact.js'; + +// 后台共用入口只注册轻量事件代理,具体页面通过 data-* 属性决定是否响应。 +bindAdminAutoactControls(); diff --git a/resources/views/admin/autoact/index.blade.php b/resources/views/admin/autoact/index.blade.php index 6f69c15..884acf1 100644 --- a/resources/views/admin/autoact/index.blade.php +++ b/resources/views/admin/autoact/index.blade.php @@ -98,7 +98,8 @@ {{ $event->jjb_change > 0 ? '+' : '' }}{{ $event->jjb_change }} - @@ -124,30 +125,4 @@ - @endsection