This commit is contained in:
Mekan1206 committed 2026-08-16 20:35:33 +05:00
1 parent bd92137fdc
commit 62249b18b3
1 file changed
+145 -232
+145 -232
View File
@@ -22,154 +22,95 @@
}; };
// ========================================================================= // =========================================================================
// 1. AUDIO MANAGER (Fixed Preloader & Clean Floating Sound Toggle) // 1. NOTIFICATION MANAGER (Visual Toast UI)
// ========================================================================= // =========================================================================
const SOUND_URL = "/assets/panel/audio/sound.mp3"; const notifiedIds = new Set();
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;
fallbackAudio.preload = "auto";
const soundedIds = new Set();
let inboxReady = false; let inboxReady = false;
let toastContainer = null;
function preloadSoundBuffer() { function initToastContainer() {
fetch(SOUND_URL, { cache: "force-cache" }) if (toastContainer) return;
.then((res) => { toastContainer = document.createElement("div");
if (!res.ok) throw new Error("Audio download error"); toastContainer.className = "mm-chat-toast-container";
return res.arrayBuffer(); toastContainer.style.cssText = `
})
.then((bytes) => {
if (audioCtx) {
return audioCtx.decodeAudioData(bytes);
}
})
.then((buffer) => {
if (buffer) soundBuffer = buffer;
})
.catch(() => { });
}
preloadSoundBuffer();
function unlockAudio() {
if (!audioCtx && AudioContextClass) {
audioCtx = new AudioContextClass();
preloadSoundBuffer();
}
if (audioCtx && audioCtx.state === "suspended") {
audioCtx.resume();
}
fallbackAudio.volume = 0.01;
const playPromise = fallbackAudio.play();
if (playPromise !== undefined) {
playPromise
.then(() => {
fallbackAudio.pause();
fallbackAudio.currentTime = 0;
fallbackAudio.volume = 1;
isAudioUnlocked = true;
updateSoundButtonUI();
})
.catch(() => { });
} else {
isAudioUnlocked = true;
updateSoundButtonUI();
}
}
function playNotifySound() {
if (!isAudioUnlocked) return;
if (audioCtx && audioCtx.state === "running" && soundBuffer) {
try {
const source = audioCtx.createBufferSource();
source.buffer = soundBuffer;
source.connect(audioCtx.destination);
source.start(0);
return;
} catch (e) { }
}
try {
fallbackAudio.currentTime = 0;
fallbackAudio.volume = 1;
fallbackAudio.play().catch(() => { });
} catch (e) { }
}
function playIncomingSound(message) {
const key = messageKey(message);
if (!key || soundedIds.has(key)) {
return;
}
soundedIds.add(key);
playNotifySound();
}
// Inject a floating non-intrusive sound toggle inside the chat pane
function initSoundButton() {
if (soundButtonEl) return;
soundButtonEl = document.createElement("button");
soundButtonEl.type = "button";
soundButtonEl.id = "mm-chat-sound-toggle";
soundButtonEl.style.cssText = `
position: absolute; position: absolute;
top: 12px; top: 15px;
right: 12px; left: 50%;
z-index: 999; transform: translateX(-50%);
padding: 5px 12px; z-index: 9999;
font-size: 12px; display: flex;
font-weight: 500; flex-direction: column;
border-radius: 6px; gap: 8px;
border: 1px solid #cbd5e1; pointer-events: none;
background-color: #ffffff; width: 90%;
color: #334155; max-width: 320px;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
transition: all 0.2s ease;
`; `;
soundButtonEl.addEventListener("click", (e) => {
e.stopPropagation();
e.preventDefault();
unlockAudio();
playNotifySound();
});
// Append to messages panel container safely without touching flex layout
const chatPane = messagesEl ? messagesEl.parentElement : document.body; const chatPane = messagesEl ? messagesEl.parentElement : document.body;
if (chatPane) { if (chatPane) {
if (getComputedStyle(chatPane).position === "static") { if (getComputedStyle(chatPane).position === "static") {
chatPane.style.position = "relative"; chatPane.style.position = "relative";
} }
chatPane.appendChild(soundButtonEl); chatPane.appendChild(toastContainer);
} }
updateSoundButtonUI();
} }
function updateSoundButtonUI() { function showNotification(title, text, conversationId) {
if (!soundButtonEl) return; initToastContainer();
if (isAudioUnlocked) { const toast = document.createElement("div");
soundButtonEl.innerHTML = "🔊 Sound On"; toast.style.cssText = `
soundButtonEl.style.backgroundColor = "#f0fdf4"; background-color: #1e293b;
soundButtonEl.style.borderColor = "#86efac"; color: #f8fafc;
soundButtonEl.style.color = "#166534"; padding: 12px 16px;
} else { border-radius: 8px;
soundButtonEl.innerHTML = "🔇 Enable Sound"; font-size: 13px;
soundButtonEl.style.backgroundColor = "#fef2f2"; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
soundButtonEl.style.borderColor = "#fca5a5"; pointer-events: auto;
soundButtonEl.style.color = "#991b1b"; cursor: pointer;
opacity: 0;
transform: translateY(-10px);
transition: all 0.3s ease;
border: 1px solid #334155;
`;
toast.innerHTML = `
<div style="font-weight: 600; margin-bottom: 2px;">${title}</div>
<div style="opacity: 0.8; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${text}</div>
`;
toast.addEventListener("click", () => {
if (conversationId) openConversation(conversationId);
toast.remove();
});
toastContainer.appendChild(toast);
// Animate in
requestAnimationFrame(() => {
toast.style.opacity = "1";
toast.style.transform = "translateY(0)";
});
// Auto-remove after 4 seconds
setTimeout(() => {
toast.style.opacity = "0";
toast.style.transform = "translateY(-10px)";
setTimeout(() => toast.remove(), 300);
}, 4000);
}
function notifyIncoming(message, conversation) {
const key = messageKey(message);
if (!key || notifiedIds.has(key)) return;
notifiedIds.add(key);
// Skip toast if they are actively looking at this exact chat thread
if (state.activeId === message.conversation_id && document.visibilityState === "visible") {
return;
} }
const senderName = (conversation && conversation.user && conversation.user.name) || "New Message";
showNotification(senderName, preview(message.body), message.conversation_id);
} }
// ========================================================================= // =========================================================================
@@ -205,10 +146,7 @@
} }
function updateUnreadBadge() { function updateUnreadBadge() {
const total = state.conversations.reduce( const total = state.conversations.reduce((sum, conv) => sum + (conv.unread_count || 0), 0);
(sum, conversation) => sum + (conversation.unread_count || 0),
0
);
unreadEl.textContent = String(total); unreadEl.textContent = String(total);
unreadEl.hidden = total < 1; unreadEl.hidden = total < 1;
} }
@@ -221,9 +159,7 @@
const button = document.createElement("button"); const button = document.createElement("button");
button.type = "button"; button.type = "button";
button.className = "mm-chat__item"; button.className = "mm-chat__item";
if (conversation.id === state.activeId) { if (conversation.id === state.activeId) button.classList.add("is-active");
button.classList.add("is-active");
}
const name = (conversation.user && conversation.user.name) || `#${conversation.id}`; const name = (conversation.user && conversation.user.name) || `#${conversation.id}`;
const phone = conversation.user && conversation.user.phone_number; const phone = conversation.user && conversation.user.phone_number;
@@ -247,27 +183,23 @@
button.querySelector(".mm-chat__item-name").textContent = name; button.querySelector(".mm-chat__item-name").textContent = name;
button.querySelector(".mm-chat__item-time").textContent = time; button.querySelector(".mm-chat__item-time").textContent = time;
button.querySelector(".mm-chat__item-sub").textContent = subtitle; button.querySelector(".mm-chat__item-sub").textContent = subtitle;
if (phone) { if (phone) button.querySelector(".mm-chat__item-phone").textContent = String(phone);
button.querySelector(".mm-chat__item-phone").textContent = String(phone);
}
button.querySelector(".mm-chat__item-preview").textContent = last ? preview(last.body) : ""; button.querySelector(".mm-chat__item-preview").textContent = last ? preview(last.body) : "";
const unread = button.querySelector(".mm-chat__item-unread"); const unread = button.querySelector(".mm-chat__item-unread");
if (unread) { if (unread) unread.textContent = String(conversation.unread_count);
unread.textContent = String(conversation.unread_count);
}
button.addEventListener("click", () => openConversation(conversation.id)); button.addEventListener("click", () => openConversation(conversation.id));
listEl.appendChild(button); listEl.appendChild(button);
}); });
updateUnreadBadge(); updateUnreadBadge();
} }
function isOutgoing(message, conversation) { function isOutgoing(message, conversation) {
if (!message) return false; if (!message) return false;
if (message.tempId || message.is_outgoing || message.sender_type === "admin" || message.sender_type === "operator") { if (message.tempId || String(message.id).startsWith("temp-")) return true;
return true; if (message.is_outgoing || message.sender_type === "admin" || message.sender_type === "operator") return true;
}
const otherId = conversation && conversation.user && conversation.user.id; const otherId = conversation && conversation.user && conversation.user.id;
if (!otherId) return true; if (!otherId) return true;
return String(message.user?.id) !== String(otherId); return String(message.user?.id) !== String(otherId);
@@ -285,6 +217,29 @@
return payload; return payload;
} }
// Double message fix core: explicitly handles temp messages
function addOrUpdateMessage(message) {
if (!message || !message.id) return false;
// 1. If it's a real server message, scrub out any optimistic duplicates based on body
if (!String(message.id).startsWith("temp-")) {
const tempIdx = state.messages.findIndex(m => m.tempId && m.body === message.body);
if (tempIdx !== -1) {
state.messages.splice(tempIdx, 1);
}
}
// 2. Add or update by ID
const existingIdx = state.messages.findIndex(m => String(m.id) === String(message.id));
if (existingIdx !== -1) {
state.messages[existingIdx] = message;
return false;
}
state.messages.push(message);
return true;
}
function renderMessages() { function renderMessages() {
const conversation = state.conversations.find((item) => item.id === state.activeId); const conversation = state.conversations.find((item) => item.id === state.activeId);
messagesEl.innerHTML = ""; messagesEl.innerHTML = "";
@@ -306,6 +261,7 @@
const meta = document.createElement("span"); const meta = document.createElement("span");
meta.className = "mm-chat__meta"; meta.className = "mm-chat__meta";
meta.textContent = formatTime(message.created_at); meta.textContent = formatTime(message.created_at);
bubble.appendChild(body); bubble.appendChild(body);
bubble.appendChild(meta); bubble.appendChild(meta);
messagesEl.appendChild(bubble); messagesEl.appendChild(bubble);
@@ -324,24 +280,18 @@
const prev = previous.find((item) => item.id === conversation.id); const prev = previous.find((item) => item.id === conversation.id);
const last = conversation.last_message; const last = conversation.last_message;
const lastChanged = Boolean(last) && messageKey(last) !== messageKey(prev && prev.last_message); const lastChanged = Boolean(last) && messageKey(last) !== messageKey(prev && prev.last_message);
const unreadUp = (conversation.unread_count || 0) > ((prev && prev.unread_count) || 0);
if (lastChanged && !isOutgoing(last, conversation)) { if (lastChanged && !isOutgoing(last, conversation)) {
playIncomingSound(last); notifyIncoming(last, conversation);
} else if (unreadUp) {
playNotifySound();
} }
}); });
} else { } else {
inboxReady = true; inboxReady = true;
state.conversations.forEach((conversation) => { state.conversations.forEach((conversation) => {
const key = messageKey(conversation.last_message); const key = messageKey(conversation.last_message);
if (key) { if (key) notifiedIds.add(key);
soundedIds.add(key);
}
}); });
} }
renderInbox(); renderInbox();
} }
@@ -349,10 +299,7 @@
if (state.loadingMessages) return; if (state.loadingMessages) return;
state.loadingMessages = true; state.loadingMessages = true;
const url = reset const url = reset ? `${config.messagesUrl}/${conversationId}/messages?perPage=50` : state.nextPageUrl;
? `${config.messagesUrl}/${conversationId}/messages?perPage=50`
: state.nextPageUrl;
if (!url) { if (!url) {
state.loadingMessages = false; state.loadingMessages = false;
return; return;
@@ -364,11 +311,14 @@
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url; state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
if (reset) { if (reset) {
state.messages = items; state.messages = [];
items.forEach(addOrUpdateMessage);
} else { } else {
state.messages = items.concat(state.messages); const oldMessages = state.messages;
state.messages = [];
items.forEach(addOrUpdateMessage);
oldMessages.forEach(addOrUpdateMessage);
} }
renderMessages(); renderMessages();
} finally { } finally {
state.loadingMessages = false; state.loadingMessages = false;
@@ -392,21 +342,21 @@
function setComposer(conversation) { function setComposer(conversation) {
const canReply = Boolean(conversation && conversation.can_reply); const canReply = Boolean(conversation && conversation.can_reply);
formEl.hidden = !canReply; formEl.hidden = !canReply;
if (viewOnlyEl) { if (viewOnlyEl) viewOnlyEl.hidden = canReply || !conversation;
viewOnlyEl.hidden = canReply || !conversation;
}
} }
async function openConversation(conversationId) { async function openConversation(conversationId) {
unlockAudio();
state.activeId = conversationId; state.activeId = conversationId;
const conversation = state.conversations.find((item) => item.id === conversationId); const conversation = state.conversations.find((item) => item.id === conversationId);
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`; const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
const phone = conversation && conversation.user && conversation.user.phone_number; const phone = conversation && conversation.user && conversation.user.phone_number;
const subtitle = conversation && conversation.channel && conversation.channel.name const subtitle = conversation && conversation.channel && conversation.channel.name
? conversation.channel.name ? conversation.channel.name
: (config.strings && config.strings.support) || "Support"; : (config.strings && config.strings.support) || "Support";
headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`; headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`;
setComposer(conversation); setComposer(conversation);
renderInbox(); renderInbox();
await loadMessages(conversationId, true); await loadMessages(conversationId, true);
@@ -416,7 +366,7 @@
async function sendMessage(event) { async function sendMessage(event) {
event.preventDefault(); event.preventDefault();
unlockAudio();
const body = (inputEl.value || "").trim(); const body = (inputEl.value || "").trim();
const conversation = state.conversations.find((item) => item.id === state.activeId); const conversation = state.conversations.find((item) => item.id === state.activeId);
if (!body || !state.activeId || !conversation || conversation.can_reply === false) return; if (!body || !state.activeId || !conversation || conversation.can_reply === false) return;
@@ -434,32 +384,31 @@
sender_type: "admin" sender_type: "admin"
}; };
state.messages.push(optimisticMsg); addOrUpdateMessage(optimisticMsg);
renderMessages(); renderMessages();
try { try {
const payload = await request( const payload = await request(`${config.messagesUrl}/${state.activeId}/messages`, {
`${config.messagesUrl}/${state.activeId}/messages`, method: "POST",
{ headers: headers(true),
method: "POST", body: JSON.stringify({ body }),
headers: headers(true), });
body: JSON.stringify({ body }),
}
);
const serverMsg = payload.data; const serverMsg = payload.data;
if (serverMsg && serverMsg.id) { if (serverMsg && serverMsg.id) {
soundedIds.add(messageKey(serverMsg)); notifiedIds.add(messageKey(serverMsg)); // Prevent self-notifying
const idx = state.messages.findIndex((m) => m.id === tempId || m.tempId === tempId);
if (idx !== -1) { // **CRITICAL FIX**: Explicitly delete the temporary message by its exact tempId
state.messages[idx] = serverMsg; state.messages = state.messages.filter(m => m.tempId !== tempId);
} else {
state.messages.push(serverMsg); addOrUpdateMessage(serverMsg);
} state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
renderMessages(); renderMessages();
} }
await loadInbox(); await loadInbox();
} catch (err) { } catch (err) {
state.messages = state.messages.filter((m) => m.id !== tempId && m.tempId !== tempId); // Revert message on network failure
state.messages = state.messages.filter(m => m.tempId !== tempId);
renderMessages(); renderMessages();
} finally { } finally {
sendEl.disabled = false; sendEl.disabled = false;
@@ -474,24 +423,15 @@
const conversation = state.conversations.find((item) => item.id === message.conversation_id); const conversation = state.conversations.find((item) => item.id === message.conversation_id);
if (!isOutgoing(message, conversation)) { if (!isOutgoing(message, conversation)) {
playIncomingSound(message); notifyIncoming(message, conversation);
} }
if (state.activeId === message.conversation_id) { if (state.activeId === message.conversation_id) {
// Deduplicate by message ID or text body matching optimistic message addOrUpdateMessage(message);
const existingIdx = state.messages.findIndex( state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
(item) => String(item.id) === String(message.id) || (item.tempId && item.body === message.body)
);
if (existingIdx !== -1) {
state.messages[existingIdx] = message;
} else {
state.messages.push(message);
}
renderMessages(); renderMessages();
markRead(message.conversation_id, true); markRead(message.conversation_id, true);
} }
loadInbox(); loadInbox();
} }
@@ -508,13 +448,8 @@
const pageHost = window.location.hostname; const pageHost = window.location.hostname;
if (!isLoopbackHost(pageHost)) { if (!isLoopbackHost(pageHost)) {
const https = window.location.protocol === "https:"; const https = window.location.protocol === "https:";
return { return { host: pageHost, port: https ? 443 : 80, forceTLS: https };
host: pageHost,
port: https ? 443 : 80,
forceTLS: https,
};
} }
return { return {
host: pusher.host || "127.0.0.1", host: pusher.host || "127.0.0.1",
port: pusher.port || 8080, port: pusher.port || 8080,
@@ -560,29 +495,23 @@
async function mergeActiveMessages() { async function mergeActiveMessages() {
if (!state.activeId || state.loadingMessages) return false; if (!state.activeId || state.loadingMessages) return false;
const payload = await request( const payload = await request(`${config.messagesUrl}/${state.activeId}/messages?perPage=50`, { headers: headers() });
`${config.messagesUrl}/${state.activeId}/messages?perPage=50`,
{ headers: headers() }
);
const items = (payload.data || []).slice().reverse(); const items = (payload.data || []).slice().reverse();
const known = new Set(state.messages.map((item) => String(item.id)));
let added = false; let added = false;
items.forEach((message) => { items.forEach((message) => {
if (!known.has(String(message.id))) { const isNew = addOrUpdateMessage(message);
state.messages.push(message); if (isNew) {
added = true; added = true;
const conversation = state.conversations.find((i) => i.id === state.activeId); const conversation = state.conversations.find((i) => i.id === state.activeId);
if (!isOutgoing(message, conversation)) { if (!isOutgoing(message, conversation)) {
playIncomingSound(message); notifyIncoming(message, conversation);
} }
} }
}); });
if (added) { if (added) {
state.messages.sort( state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
(a, b) => new Date(a.created_at) - new Date(b.created_at)
);
renderMessages(); renderMessages();
} }
@@ -607,23 +536,7 @@
} }
}); });
// Global listeners to unlock audio on first interaction
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 // Initialize
initSoundButton();
loadInbox(); loadInbox();
bootEcho(); bootEcho();