diff --git a/public/assets/panel/js/chat.js b/public/assets/panel/js/chat.js index 1df0784..79ea49e 100644 --- a/public/assets/panel/js/chat.js +++ b/public/assets/panel/js/chat.js @@ -1,4 +1,6 @@ (function () { + "use strict"; + const config = window.MM_CHAT || {}; const listEl = document.getElementById("mm-chat-list"); const emptyInboxEl = document.getElementById("mm-chat-empty-inbox"); @@ -20,13 +22,14 @@ }; // ========================================================================= - // 1. AUDIO MANAGER (Cached Audio Buffer, Zero Network Spam, Autoplay-Safe) + // 1. AUDIO MANAGER (RAM Buffer + Sound Toggle) // ========================================================================= const SOUND_URL = "/assets/panel/audio/sound.mp3"; const AudioContextClass = window.AudioContext || window.webkitAudioContext; let audioCtx = null; let soundBuffer = null; let isAudioUnlocked = false; + let soundButtonEl = null; const fallbackAudio = document.getElementById("mm-chat-sound") || new Audio(SOUND_URL); fallbackAudio.src = SOUND_URL; @@ -35,7 +38,7 @@ const soundedIds = new Set(); let inboxReady = false; - // Pre-load audio once into memory buffer + // Preload audio file ONCE into memory buffer function preloadSoundBuffer() { fetch(SOUND_URL, { cache: "force-cache" }) .then((res) => { @@ -56,8 +59,6 @@ preloadSoundBuffer(); function unlockAudio() { - if (isAudioUnlocked) return; - if (!audioCtx && AudioContextClass) { audioCtx = new AudioContextClass(); preloadSoundBuffer(); @@ -67,8 +68,7 @@ audioCtx.resume(); } - // Warm up HTML Audio element - fallbackAudio.volume = 0; + fallbackAudio.volume = 0.01; const playPromise = fallbackAudio.play(); if (playPromise !== undefined) { playPromise @@ -77,22 +77,19 @@ fallbackAudio.currentTime = 0; fallbackAudio.volume = 1; isAudioUnlocked = true; - removeUnlockListeners(); + updateSoundButtonUI(); }) .catch(() => { }); + } else { + isAudioUnlocked = true; + updateSoundButtonUI(); } } - function removeUnlockListeners() { - ["pointerdown", "keydown", "touchstart", "click"].forEach((eventName) => { - document.removeEventListener(eventName, unlockAudio, { capture: true }); - }); - } - function playNotifySound() { if (!isAudioUnlocked) return; - // 1. Play from cached RAM buffer (No network request made) + // 1. Play from Web Audio API RAM buffer if (audioCtx && audioCtx.state === "running" && soundBuffer) { try { const source = audioCtx.createBufferSource(); @@ -120,6 +117,60 @@ playNotifySound(); } + // Create & inject "Enable Sound" button into header + function initSoundButton() { + if (!headEl || soundButtonEl) return; + + soundButtonEl = document.createElement("button"); + soundButtonEl.type = "button"; + soundButtonEl.id = "mm-chat-sound-toggle"; + soundButtonEl.style.cssText = ` + margin-left: auto; + padding: 4px 10px; + font-size: 12px; + border-radius: 4px; + border: 1px solid #ccc; + background-color: #f8f9fa; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 5px; + `; + + soundButtonEl.addEventListener("click", (e) => { + e.stopPropagation(); + unlockAudio(); + playNotifySound(); // Plays test sound on click + }); + + updateSoundButtonUI(); + + // Place header in container flex if not already + if (headEl.parentElement) { + headEl.parentElement.style.display = "flex"; + headEl.parentElement.style.alignItems = "center"; + headEl.parentElement.appendChild(soundButtonEl); + } + } + + function updateSoundButtonUI() { + if (!soundButtonEl) return; + if (isAudioUnlocked) { + soundButtonEl.innerHTML = "🔊 Sound On"; + soundButtonEl.style.backgroundColor = "#e6fffa"; + soundButtonEl.style.borderColor = "#319795"; + soundButtonEl.style.color = "#234e52"; + } else { + soundButtonEl.innerHTML = "🔇 Enable Sound"; + soundButtonEl.style.backgroundColor = "#fff5f5"; + soundButtonEl.style.borderColor = "#feb2b2"; + soundButtonEl.style.color = "#9b2c2c"; + } + } + + // ========================================================================= + // 2. CHAT LOGIC & HELPERS + // ========================================================================= function headers(json) { const next = { Accept: "application/json", @@ -366,7 +417,6 @@ sendEl.disabled = true; inputEl.value = ""; - // Render optimistic message locally const tempId = "temp-" + Date.now(); const optimisticMsg = { id: tempId, @@ -392,7 +442,6 @@ const serverMsg = payload.data; if (serverMsg && serverMsg.id) { soundedIds.add(messageKey(serverMsg)); - // Replace optimistic message with actual server message const idx = state.messages.findIndex((m) => m.id === tempId || m.tempId === tempId); if (idx !== -1) { state.messages[idx] = serverMsg; @@ -403,7 +452,6 @@ } await loadInbox(); } catch (err) { - // Remove optimistic message on error state.messages = state.messages.filter((m) => m.id !== tempId && m.tempId !== tempId); renderMessages(); } finally { @@ -412,31 +460,24 @@ } } - // ========================================================================= - // 2. INCOMING / WEBSOCKET DEDUPLICATION HANDLER - // ========================================================================= function upsertIncoming(payload) { const message = normalizeIncoming(payload); if (!message || !message.conversation_id) return; const conversation = state.conversations.find((item) => item.id === message.conversation_id); - // Play sound ONLY for client messages if (!isOutgoing(message, conversation)) { playIncomingSound(message); } if (state.activeId === message.conversation_id) { - // Check if message is already rendered (or is an optimistic local message) const existingIdx = state.messages.findIndex( (item) => String(item.id) === String(message.id) || (item.tempId && item.body === message.body) ); if (existingIdx !== -1) { - // Update existing message instead of duplicating state.messages[existingIdx] = message; } else { - // Append new message from client state.messages.push(message); } renderMessages(); @@ -540,6 +581,7 @@ return added; } + // Event Listeners formEl.addEventListener("submit", sendMessage); inputEl.addEventListener("keydown", (event) => { if (event.key === "Enter" && !event.shiftKey) { @@ -557,11 +599,23 @@ } }); - // Passive listeners to unlock audio on initial admin click/keypress - ["pointerdown", "keydown", "touchstart", "click"].forEach((eventName) => { - document.addEventListener(eventName, unlockAudio, { capture: true, passive: true }); + // Global listeners to unlock audio on first page click + const userGestureEvents = ["click", "pointerdown", "keydown", "touchstart"]; + function handleInitialGesture() { + unlockAudio(); + if (isAudioUnlocked) { + userGestureEvents.forEach((eventName) => { + document.removeEventListener(eventName, handleInitialGesture, true); + }); + } + } + + userGestureEvents.forEach((eventName) => { + document.addEventListener(eventName, handleInitialGesture, { capture: true, passive: true }); }); + // Initialize + initSoundButton(); loadInbox(); bootEcho();