This commit is contained in:
Mekan1206
2026-08-16 20:35:33 +05:00
parent bd92137fdc
commit 62249b18b3

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 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();
const notifiedIds = new Set();
let inboxReady = false;
let toastContainer = null;
function preloadSoundBuffer() {
fetch(SOUND_URL, { cache: "force-cache" })
.then((res) => {
if (!res.ok) throw new Error("Audio download error");
return res.arrayBuffer();
})
.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 = `
function initToastContainer() {
if (toastContainer) return;
toastContainer = document.createElement("div");
toastContainer.className = "mm-chat-toast-container";
toastContainer.style.cssText = `
position: absolute;
top: 12px;
right: 12px;
z-index: 999;
padding: 5px 12px;
font-size: 12px;
font-weight: 500;
border-radius: 6px;
border: 1px solid #cbd5e1;
background-color: #ffffff;
color: #334155;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
transition: all 0.2s ease;
top: 15px;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
display: flex;
flex-direction: column;
gap: 8px;
pointer-events: none;
width: 90%;
max-width: 320px;
`;
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;
if (chatPane) {
if (getComputedStyle(chatPane).position === "static") {
chatPane.style.position = "relative";
}
chatPane.appendChild(soundButtonEl);
chatPane.appendChild(toastContainer);
}
updateSoundButtonUI();
}
function updateSoundButtonUI() {
if (!soundButtonEl) return;
if (isAudioUnlocked) {
soundButtonEl.innerHTML = "🔊 Sound On";
soundButtonEl.style.backgroundColor = "#f0fdf4";
soundButtonEl.style.borderColor = "#86efac";
soundButtonEl.style.color = "#166534";
} else {
soundButtonEl.innerHTML = "🔇 Enable Sound";
soundButtonEl.style.backgroundColor = "#fef2f2";
soundButtonEl.style.borderColor = "#fca5a5";
soundButtonEl.style.color = "#991b1b";
function showNotification(title, text, conversationId) {
initToastContainer();
const toast = document.createElement("div");
toast.style.cssText = `
background-color: #1e293b;
color: #f8fafc;
padding: 12px 16px;
border-radius: 8px;
font-size: 13px;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
pointer-events: auto;
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() {
const total = state.conversations.reduce(
(sum, conversation) => sum + (conversation.unread_count || 0),
0
);
const total = state.conversations.reduce((sum, conv) => sum + (conv.unread_count || 0), 0);
unreadEl.textContent = String(total);
unreadEl.hidden = total < 1;
}
@@ -221,9 +159,7 @@
const button = document.createElement("button");
button.type = "button";
button.className = "mm-chat__item";
if (conversation.id === state.activeId) {
button.classList.add("is-active");
}
if (conversation.id === state.activeId) button.classList.add("is-active");
const name = (conversation.user && conversation.user.name) || `#${conversation.id}`;
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-time").textContent = time;
button.querySelector(".mm-chat__item-sub").textContent = subtitle;
if (phone) {
button.querySelector(".mm-chat__item-phone").textContent = String(phone);
}
if (phone) button.querySelector(".mm-chat__item-phone").textContent = String(phone);
button.querySelector(".mm-chat__item-preview").textContent = last ? preview(last.body) : "";
const unread = button.querySelector(".mm-chat__item-unread");
if (unread) {
unread.textContent = String(conversation.unread_count);
}
if (unread) unread.textContent = String(conversation.unread_count);
button.addEventListener("click", () => openConversation(conversation.id));
listEl.appendChild(button);
});
updateUnreadBadge();
}
function isOutgoing(message, conversation) {
if (!message) return false;
if (message.tempId || message.is_outgoing || message.sender_type === "admin" || message.sender_type === "operator") {
return true;
}
if (message.tempId || String(message.id).startsWith("temp-")) return true;
if (message.is_outgoing || message.sender_type === "admin" || message.sender_type === "operator") return true;
const otherId = conversation && conversation.user && conversation.user.id;
if (!otherId) return true;
return String(message.user?.id) !== String(otherId);
@@ -285,6 +217,29 @@
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() {
const conversation = state.conversations.find((item) => item.id === state.activeId);
messagesEl.innerHTML = "";
@@ -306,6 +261,7 @@
const meta = document.createElement("span");
meta.className = "mm-chat__meta";
meta.textContent = formatTime(message.created_at);
bubble.appendChild(body);
bubble.appendChild(meta);
messagesEl.appendChild(bubble);
@@ -324,24 +280,18 @@
const prev = previous.find((item) => item.id === conversation.id);
const last = conversation.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)) {
playIncomingSound(last);
} else if (unreadUp) {
playNotifySound();
notifyIncoming(last, conversation);
}
});
} else {
inboxReady = true;
state.conversations.forEach((conversation) => {
const key = messageKey(conversation.last_message);
if (key) {
soundedIds.add(key);
}
if (key) notifiedIds.add(key);
});
}
renderInbox();
}
@@ -349,10 +299,7 @@
if (state.loadingMessages) return;
state.loadingMessages = true;
const url = reset
? `${config.messagesUrl}/${conversationId}/messages?perPage=50`
: state.nextPageUrl;
const url = reset ? `${config.messagesUrl}/${conversationId}/messages?perPage=50` : state.nextPageUrl;
if (!url) {
state.loadingMessages = false;
return;
@@ -364,11 +311,14 @@
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
if (reset) {
state.messages = items;
state.messages = [];
items.forEach(addOrUpdateMessage);
} else {
state.messages = items.concat(state.messages);
const oldMessages = state.messages;
state.messages = [];
items.forEach(addOrUpdateMessage);
oldMessages.forEach(addOrUpdateMessage);
}
renderMessages();
} finally {
state.loadingMessages = false;
@@ -392,21 +342,21 @@
function setComposer(conversation) {
const canReply = Boolean(conversation && conversation.can_reply);
formEl.hidden = !canReply;
if (viewOnlyEl) {
viewOnlyEl.hidden = canReply || !conversation;
}
if (viewOnlyEl) viewOnlyEl.hidden = canReply || !conversation;
}
async function openConversation(conversationId) {
unlockAudio();
state.activeId = conversationId;
const conversation = state.conversations.find((item) => item.id === conversationId);
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
const phone = conversation && conversation.user && conversation.user.phone_number;
const subtitle = conversation && conversation.channel && conversation.channel.name
? conversation.channel.name
: (config.strings && config.strings.support) || "Support";
headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`;
setComposer(conversation);
renderInbox();
await loadMessages(conversationId, true);
@@ -416,7 +366,7 @@
async function sendMessage(event) {
event.preventDefault();
unlockAudio();
const body = (inputEl.value || "").trim();
const conversation = state.conversations.find((item) => item.id === state.activeId);
if (!body || !state.activeId || !conversation || conversation.can_reply === false) return;
@@ -434,32 +384,31 @@
sender_type: "admin"
};
state.messages.push(optimisticMsg);
addOrUpdateMessage(optimisticMsg);
renderMessages();
try {
const payload = await request(
`${config.messagesUrl}/${state.activeId}/messages`,
{
method: "POST",
headers: headers(true),
body: JSON.stringify({ body }),
}
);
const payload = await request(`${config.messagesUrl}/${state.activeId}/messages`, {
method: "POST",
headers: headers(true),
body: JSON.stringify({ body }),
});
const serverMsg = payload.data;
if (serverMsg && serverMsg.id) {
soundedIds.add(messageKey(serverMsg));
const idx = state.messages.findIndex((m) => m.id === tempId || m.tempId === tempId);
if (idx !== -1) {
state.messages[idx] = serverMsg;
} else {
state.messages.push(serverMsg);
}
notifiedIds.add(messageKey(serverMsg)); // Prevent self-notifying
// **CRITICAL FIX**: Explicitly delete the temporary message by its exact tempId
state.messages = state.messages.filter(m => m.tempId !== tempId);
addOrUpdateMessage(serverMsg);
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
renderMessages();
}
await loadInbox();
} 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();
} finally {
sendEl.disabled = false;
@@ -474,24 +423,15 @@
const conversation = state.conversations.find((item) => item.id === message.conversation_id);
if (!isOutgoing(message, conversation)) {
playIncomingSound(message);
notifyIncoming(message, conversation);
}
if (state.activeId === message.conversation_id) {
// Deduplicate by message ID or text body matching optimistic message
const existingIdx = state.messages.findIndex(
(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);
}
addOrUpdateMessage(message);
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
renderMessages();
markRead(message.conversation_id, true);
}
loadInbox();
}
@@ -508,13 +448,8 @@
const pageHost = window.location.hostname;
if (!isLoopbackHost(pageHost)) {
const https = window.location.protocol === "https:";
return {
host: pageHost,
port: https ? 443 : 80,
forceTLS: https,
};
return { host: pageHost, port: https ? 443 : 80, forceTLS: https };
}
return {
host: pusher.host || "127.0.0.1",
port: pusher.port || 8080,
@@ -560,29 +495,23 @@
async function mergeActiveMessages() {
if (!state.activeId || state.loadingMessages) return false;
const payload = await request(
`${config.messagesUrl}/${state.activeId}/messages?perPage=50`,
{ headers: headers() }
);
const payload = await request(`${config.messagesUrl}/${state.activeId}/messages?perPage=50`, { headers: headers() });
const items = (payload.data || []).slice().reverse();
const known = new Set(state.messages.map((item) => String(item.id)));
let added = false;
items.forEach((message) => {
if (!known.has(String(message.id))) {
state.messages.push(message);
const isNew = addOrUpdateMessage(message);
if (isNew) {
added = true;
const conversation = state.conversations.find((i) => i.id === state.activeId);
if (!isOutgoing(message, conversation)) {
playIncomingSound(message);
notifyIncoming(message, conversation);
}
}
});
if (added) {
state.messages.sort(
(a, b) => new Date(a.created_at) - new Date(b.created_at)
);
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
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
initSoundButton();
loadInbox();
bootEcho();