Files
Mekan1206 62249b18b3 WIP
2026-08-16 20:35:33 +05:00

559 lines
18 KiB
JavaScript

(function () {
"use strict";
const config = window.MM_CHAT || {};
const listEl = document.getElementById("mm-chat-list");
const emptyInboxEl = document.getElementById("mm-chat-empty-inbox");
const messagesEl = document.getElementById("mm-chat-messages");
const headEl = document.getElementById("mm-chat-thread-head");
const formEl = document.getElementById("mm-chat-form");
const viewOnlyEl = document.getElementById("mm-chat-view-only");
const inputEl = document.getElementById("mm-chat-input");
const sendEl = document.getElementById("mm-chat-send");
const unreadEl = document.getElementById("mm-chat-unread");
const state = {
conversations: [],
activeId: null,
messages: [],
nextPageUrl: null,
loadingMessages: false,
echo: null,
};
// =========================================================================
// 1. NOTIFICATION MANAGER (Visual Toast UI)
// =========================================================================
const notifiedIds = new Set();
let inboxReady = false;
let toastContainer = null;
function initToastContainer() {
if (toastContainer) return;
toastContainer = document.createElement("div");
toastContainer.className = "mm-chat-toast-container";
toastContainer.style.cssText = `
position: absolute;
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;
`;
const chatPane = messagesEl ? messagesEl.parentElement : document.body;
if (chatPane) {
if (getComputedStyle(chatPane).position === "static") {
chatPane.style.position = "relative";
}
chatPane.appendChild(toastContainer);
}
}
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);
}
// =========================================================================
// 2. CHAT HELPERS & RENDERING
// =========================================================================
function headers(json) {
const next = {
Accept: "application/json",
"X-CSRF-TOKEN": config.csrf,
"X-Requested-With": "XMLHttpRequest",
};
if (json) next["Content-Type"] = "application/json";
return next;
}
async function request(url, options) {
const response = await fetch(url, options);
if (!response.ok) throw new Error("Chat request failed");
return response.json();
}
function formatTime(value) {
if (!value) return "";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "";
const pad = (n) => String(n).padStart(2, "0");
return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${pad(date.getFullYear())}`;
}
function preview(body) {
if (!body) return "";
return body.length > 80 ? `${body.slice(0, 80)}…` : body;
}
function updateUnreadBadge() {
const total = state.conversations.reduce((sum, conv) => sum + (conv.unread_count || 0), 0);
unreadEl.textContent = String(total);
unreadEl.hidden = total < 1;
}
function renderInbox() {
listEl.innerHTML = "";
emptyInboxEl.hidden = state.conversations.length > 0;
state.conversations.forEach((conversation) => {
const button = document.createElement("button");
button.type = "button";
button.className = "mm-chat__item";
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;
const last = conversation.last_message;
const time = last ? formatTime(last.created_at) : "";
const subtitle = conversation.channel && conversation.channel.name
? conversation.channel.name
: (config.strings && config.strings.support) || "Support";
button.innerHTML = `
<div class="mm-chat__item-row">
<span class="mm-chat__item-name"></span>
<span class="mm-chat__item-time"></span>
</div>
<div class="mm-chat__item-sub"></div>
${phone ? '<div class="mm-chat__item-phone"></div>' : ""}
<div class="mm-chat__item-preview"></div>
${conversation.unread_count ? '<span class="mm-chat__item-unread"></span>' : ""}
`;
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);
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);
button.addEventListener("click", () => openConversation(conversation.id));
listEl.appendChild(button);
});
updateUnreadBadge();
}
function isOutgoing(message, conversation) {
if (!message) return false;
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);
}
function messageKey(message) {
return message && message.id != null ? String(message.id) : "";
}
function normalizeIncoming(payload) {
if (!payload || typeof payload !== "object") return payload;
if (payload.conversation_id && payload.id) return payload;
if (payload.message && payload.message.id) return payload.message;
if (payload.data && payload.data.id) return payload.data;
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 = "";
if (!state.messages.length) {
const empty = document.createElement("p");
empty.className = "mm-chat__empty";
empty.textContent = config.strings.noMessages;
messagesEl.appendChild(empty);
return;
}
state.messages.forEach((message) => {
const bubble = document.createElement("div");
bubble.className = `mm-chat__bubble ${isOutgoing(message, conversation) ? "mm-chat__bubble--out" : "mm-chat__bubble--in"
}`;
const body = document.createElement("div");
body.textContent = message.body;
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);
});
messagesEl.scrollTop = messagesEl.scrollHeight;
}
async function loadInbox() {
const payload = await request(config.conversationsUrl, { headers: headers() });
const previous = state.conversations;
state.conversations = payload.data || [];
if (inboxReady) {
state.conversations.forEach((conversation) => {
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);
if (lastChanged && !isOutgoing(last, conversation)) {
notifyIncoming(last, conversation);
}
});
} else {
inboxReady = true;
state.conversations.forEach((conversation) => {
const key = messageKey(conversation.last_message);
if (key) notifiedIds.add(key);
});
}
renderInbox();
}
async function loadMessages(conversationId, reset) {
if (state.loadingMessages) return;
state.loadingMessages = true;
const url = reset ? `${config.messagesUrl}/${conversationId}/messages?perPage=50` : state.nextPageUrl;
if (!url) {
state.loadingMessages = false;
return;
}
try {
const payload = await request(url, { headers: headers() });
const items = (payload.data || []).slice().reverse();
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
if (reset) {
state.messages = [];
items.forEach(addOrUpdateMessage);
} else {
const oldMessages = state.messages;
state.messages = [];
items.forEach(addOrUpdateMessage);
oldMessages.forEach(addOrUpdateMessage);
}
renderMessages();
} finally {
state.loadingMessages = false;
}
}
async function markRead(conversationId, force) {
if (!conversationId || conversationId !== state.activeId) return;
const conversation = state.conversations.find((item) => item.id === conversationId);
if (!conversation || (!force && !conversation.unread_count)) return;
await request(`${config.messagesUrl}/${conversationId}/read`, {
method: "POST",
headers: headers(true),
});
conversation.unread_count = 0;
renderInbox();
}
function setComposer(conversation) {
const canReply = Boolean(conversation && conversation.can_reply);
formEl.hidden = !canReply;
if (viewOnlyEl) viewOnlyEl.hidden = canReply || !conversation;
}
async function openConversation(conversationId) {
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);
await markRead(conversationId, true);
subscribeThread(conversationId);
}
async function sendMessage(event) {
event.preventDefault();
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;
sendEl.disabled = true;
inputEl.value = "";
const tempId = "temp-" + Date.now();
const optimisticMsg = {
id: tempId,
tempId: tempId,
conversation_id: state.activeId,
body: body,
created_at: new Date().toISOString(),
sender_type: "admin"
};
addOrUpdateMessage(optimisticMsg);
renderMessages();
try {
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) {
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) {
// Revert message on network failure
state.messages = state.messages.filter(m => m.tempId !== tempId);
renderMessages();
} finally {
sendEl.disabled = false;
inputEl.focus();
}
}
function upsertIncoming(payload) {
const message = normalizeIncoming(payload);
if (!message || !message.conversation_id) return;
const conversation = state.conversations.find((item) => item.id === message.conversation_id);
if (!isOutgoing(message, conversation)) {
notifyIncoming(message, conversation);
}
if (state.activeId === message.conversation_id) {
addOrUpdateMessage(message);
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
renderMessages();
markRead(message.conversation_id, true);
}
loadInbox();
}
function subscribeThread(conversationId) {
if (!state.echo) return;
state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming);
}
function isLoopbackHost(host) {
return !host || host === "127.0.0.1" || host === "localhost" || host === "0.0.0.0" || host === "::1";
}
function echoEndpoint(pusher) {
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: pusher.host || "127.0.0.1",
port: pusher.port || 8080,
forceTLS: (pusher.scheme || "http") === "https",
};
}
function bootEcho() {
const pusher = config.pusher || {};
const EchoClass = window.Echo;
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) return;
const endpoint = echoEndpoint(pusher);
try {
state.echo = new EchoClass({
broadcaster: "reverb",
key: pusher.key,
wsHost: endpoint.host,
wsPort: endpoint.port,
wssPort: endpoint.port,
forceTLS: endpoint.forceTLS,
enabledTransports: ["ws", "wss"],
disableStats: true,
cluster: "mt1",
csrfToken: config.csrf,
authEndpoint: config.broadcastAuthPath || config.broadcastAuth || "/panel/broadcasting/auth",
auth: {
headers: {
"X-CSRF-TOKEN": config.csrf,
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
},
},
});
state.echo.private(config.inboxChannel || "chat.support").listen(".message.sent", upsertIncoming);
} catch (err) {
state.echo = null;
}
}
async function mergeActiveMessages() {
if (!state.activeId || state.loadingMessages) return false;
const payload = await request(`${config.messagesUrl}/${state.activeId}/messages?perPage=50`, { headers: headers() });
const items = (payload.data || []).slice().reverse();
let added = false;
items.forEach((message) => {
const isNew = addOrUpdateMessage(message);
if (isNew) {
added = true;
const conversation = state.conversations.find((i) => i.id === state.activeId);
if (!isOutgoing(message, conversation)) {
notifyIncoming(message, conversation);
}
}
});
if (added) {
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
renderMessages();
}
return added;
}
// Event Listeners
formEl.addEventListener("submit", sendMessage);
inputEl.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
formEl.requestSubmit();
}
});
messagesEl.addEventListener("scroll", () => {
if (messagesEl.scrollTop < 40 && state.nextPageUrl && state.activeId) {
const previousHeight = messagesEl.scrollHeight;
loadMessages(state.activeId, false).then(() => {
messagesEl.scrollTop = messagesEl.scrollHeight - previousHeight;
});
}
});
// Initialize
loadInbox();
bootEcho();
setInterval(() => {
loadInbox().then(async () => {
if (!state.activeId) return;
const added = await mergeActiveMessages();
const conversation = state.conversations.find((item) => item.id === state.activeId);
if (added || (conversation && conversation.unread_count > 0)) {
await markRead(state.activeId, true);
}
});
}, 4000);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && state.activeId) {
markRead(state.activeId);
}
});
})();