PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.1.4
MxChat – AI Chatbot & Content Generation for WordPress v3.1.4
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | js/chat-script.js +174 -802 3.2.63.1.4 View file →
@@ -1,39 +1,21 @@
1 1 jQuery(document).ready(function($) {
2 2
3 3 // Nonce refresh is deferred until first user interaction (ensureSession)
4 - // to avoid admin-ajax calls on passive page loads. The state machine below
5 - // queues callbacks so a chat-send that fires while the refresh AJAX is still
6 - // in flight waits for the fresh nonce instead of racing it with the stale
7 - // cached value (which would 403 as "Access denied" on the first message).
8 - var nonceRefreshState = 'idle'; // 'idle' | 'pending' | 'done'
9 - var nonceRefreshCallbacks = [];
4 + // to avoid admin-ajax calls on passive page loads.
5 + var nonceRefreshed = false;
10 6 function refreshNonceIfNeeded(callback) {
11 - if (typeof mxchatChat === 'undefined' || !mxchatChat.ajax_url) {
7 + if (nonceRefreshed || typeof mxchatChat === 'undefined' || !mxchatChat.ajax_url) {
12 8 if (callback) callback();
13 9 return;
14 10 }
15 - if (nonceRefreshState === 'done') {
11 + nonceRefreshed = true;
12 + $.post(mxchatChat.ajax_url, { action: 'mxchat_refresh_nonce' }, function(res) {
13 + if (res && res.success && res.data && res.data.nonce) {
14 + mxchatChat.nonce = res.data.nonce;
15 + }
16 16 if (callback) callback();
17 - return;
18 - }
19 - if (callback) nonceRefreshCallbacks.push(callback);
20 - if (nonceRefreshState === 'pending') {
21 - return;
22 - }
23 - nonceRefreshState = 'pending';
24 - $.post(mxchatChat.ajax_url, { action: 'mxchat_refresh_nonce' })
25 - .done(function(res) {
26 - if (res && res.success && res.data && res.data.nonce) {
27 - mxchatChat.nonce = res.data.nonce;
28 - }
29 - })
30 - .always(function() {
31 - nonceRefreshState = 'done';
32 - var pending = nonceRefreshCallbacks;
33 - nonceRefreshCallbacks = [];
34 - pending.forEach(function(cb) { try { cb(); } catch (e) {} });
35 - });
17 + });
36 18 }
37 19
38 20 // ====================================
39 21 // MULTI-INSTANCE MANAGEMENT SYSTEM
@@ -78,39 +60,18 @@
78 60 return Object.keys(this.instances);
79 61 },
80 62
81 63 // Session management per bot
82 - // Returns existing session ID from cookie or localStorage (with in-memory fallback),
83 - // or null if none exists. Does NOT create a new session — use ensureSession() for that.
84 64 getChatSession: function(botId) {
85 65 var cookieName = 'mxchat_session_id_' + botId;
86 - var storageKey = 'mxchat_session_id_' + botId;
87 66 var sessionId = getCookie(cookieName);
88 67
89 - // Fallback to localStorage if cookie is missing (e.g. cleared by browser/consent)
90 68 if (!sessionId) {
91 - try { sessionId = localStorage.getItem(storageKey); } catch (e) {}
69 + sessionId = generateSessionId();
70 + this.setChatSession(botId, sessionId);
92 71 }
93 72
94 - // Fallback to in-memory instance when cookie AND localStorage are both blocked
95 - // (Safari ITP, strict tracking prevention, cross-origin iframes with partitioned
96 - // storage). Without this, ensureSession() can generate and store an ID that
97 - // getChatSession() then can't read back, causing null session_ids on send.
98 - if (!sessionId && this.instances[botId] && this.instances[botId].sessionId) {
99 - sessionId = this.instances[botId].sessionId;
100 - }
101 -
102 - // Guard against stored sentinel values that indicate earlier broken writes.
103 - if (sessionId === 'null' || sessionId === 'undefined') {
104 - sessionId = null;
105 - }
106 -
107 - // Re-sync cookie from localStorage if cookie was lost
108 - if (sessionId && !getCookie(cookieName)) {
109 - document.cookie = cookieName + "=" + sessionId + "; path=/; max-age=86400; SameSite=Lax";
110 - }
111 -
112 - return sessionId || null;
73 + return sessionId;
113 74 },
114 75
115 76 // Lazy session initializer — called on first user interaction
116 77 ensureSession: function(botId) {
@@ -120,10 +81,11 @@
120 81 if (instance.sessionId) {
121 82 return instance.sessionId;
122 83 }
123 84
124 - // Check for existing session from cookie or localStorage
125 - var existingSession = this.getChatSession(botId);
85 + // Check if a cookie already exists from a prior visit
86 + var cookieName = 'mxchat_session_id_' + botId;
87 + var existingSession = getCookie(cookieName);
126 88
127 89 if (existingSession) {
128 90 instance.sessionId = existingSession;
129 91 } else {
@@ -136,10 +98,12 @@
136 98 // Now that we have a session, do the deferred work
137 99 refreshNonceIfNeeded();
138 100 trackOriginatingPage();
139 101
140 - // Note: loadChatHistory is handled by showChatContainerForBot with loader UI,
141 - // so we do NOT call it here to avoid a race condition.
102 + var chatPersistenceEnabled = typeof mxchatChat !== 'undefined' && mxchatChat.chat_persistence_toggle === 'on';
103 + if (chatPersistenceEnabled && mxchatChat.email_collection_enabled !== 'on') {
104 + loadChatHistory(botId);
105 + }
142 106
143 107 return instance.sessionId;
144 108 },
145 109
@@ -144,11 +108,9 @@
144 108 },
145 109
146 110 setChatSession: function(botId, sessionId) {
147 111 var cookieName = 'mxchat_session_id_' + botId;
148 - var storageKey = 'mxchat_session_id_' + botId;
149 112 document.cookie = cookieName + "=" + sessionId + "; path=/; max-age=86400; SameSite=Lax";
150 - try { localStorage.setItem(storageKey, sessionId); } catch (e) {}
151 113 if (this.instances[botId]) {
152 114 this.instances[botId].sessionId = sessionId;
153 115 }
154 116 },
@@ -153,10 +115,8 @@
153 115 }
154 116 },
155 117
156 118 resetChatSession: function(botId) {
157 - // Clear old session from localStorage before setting new one
158 - try { localStorage.removeItem('mxchat_session_id_' + botId); } catch (e) {}
159 119 var newSessionId = generateSessionId();
160 120 this.setChatSession(botId, newSessionId);
161 121 var $chatBox = getElement(botId, 'chat-box');
162 122 if ($chatBox.length) {
@@ -165,20 +125,8 @@
165 125 if (this.instances[botId]) {
166 126 this.instances[botId].chatHistoryLoaded = false;
167 127 this.instances[botId].processedMessageIds = new Set();
168 128 }
169 - },
170 -
171 - // Silent reset — new session ID without clearing the chat UI
172 - // Used when IP changes mid-conversation so the user doesn't see messages vanish
173 - silentResetSession: function(botId) {
174 - try { localStorage.removeItem('mxchat_session_id_' + botId); } catch (e) {}
175 - var newSessionId = generateSessionId();
176 - this.setChatSession(botId, newSessionId);
177 - if (this.instances[botId]) {
178 - this.instances[botId].sessionId = newSessionId;
179 - }
180 - return newSessionId;
181 129 }
182 130 };
183 131
184 132 // ====================================
@@ -630,28 +578,13 @@
630 578
631 579 // Get instance for session start timestamp (used when persistence is OFF)
632 580 var instance = MxChatInstances.get(botId);
633 581
634 - // Guarantee a non-null session_id before the AJAX leaves. ensureSession() is idempotent
635 - // and returns the guaranteed-present session id from the in-memory instance even when
636 - // cookie/localStorage writes are silently blocked by the browser.
637 - var sessionId = MxChatInstances.ensureSession(botId);
638 - if (!sessionId || sessionId === 'null' || sessionId === 'undefined') {
639 - // Last-resort generation to ensure we never POST a null marker.
640 - sessionId = generateSessionId();
641 - MxChatInstances.setChatSession(botId, sessionId);
642 - }
643 -
644 - // Wait for the page-cache nonce refresh to complete before firing the
645 - // chat-send AJAX. On cached pages the inline mxchatChat.nonce is stale
646 - // until refreshNonceIfNeeded() returns; constructing ajaxData inside the
647 - // callback guarantees we read the fresh value. See plan-c5457f.
648 - refreshNonceIfNeeded(function() {
649 582 // Prepare AJAX data
650 583 const ajaxData = {
651 584 action: 'mxchat_handle_chat_request',
652 585 message: message,
653 - session_id: sessionId,
586 + session_id: getChatSession(botId),
654 587 nonce: mxchatChat.nonce,
655 588 current_page_url: window.location.href,
656 589 current_page_title: document.title,
657 590 bot_id: botId,
@@ -657,14 +590,14 @@
657 590 bot_id: botId,
658 591 // Pass session start timestamp so AI context matches what user sees
659 592 session_start_timestamp: instance.sessionStartTimestamp || 0
660 593 };
661 -
594 +
662 595 // Add page context if available
663 596 if (pageContext) {
664 597 ajaxData.page_context = JSON.stringify(pageContext);
665 598 }
666 -
599 +
667 600 // CHECK FOR VISION FLAGS AND ADD THEM
668 601 if (window.mxchatVisionProcessed) {
669 602 ajaxData.vision_processed = true;
670 603 ajaxData.original_user_message = window.mxchatOriginalMessage || message;
@@ -673,9 +606,9 @@
673 606 window.mxchatVisionProcessed = false;
674 607 window.mxchatOriginalMessage = null;
675 608 window.mxchatVisionImagesCount = 0;
676 609 }
677 -
610 +
678 611 $.ajax({
679 612 url: mxchatChat.ajax_url,
680 613 type: 'POST',
681 614 dataType: 'json',
@@ -713,16 +646,23 @@
713 646 errorMessage = "An error occurred. Please try again or contact support.";
714 647 }
715 648
716 649 // Handle session reset action (IP changed, session expired, etc.)
717 - // Silent reset — keep chat UI intact, just get a new session and retry
718 650 if (response.data && response.data.action === 'reset_session') {
719 - MxChatInstances.silentResetSession(botId);
720 - // Re-send the original message with the new session (user message is already displayed)
651 + // Clear the old session and generate a new one
652 + resetChatSession(botId);
653 + // Remove the temporary loading message
654 + getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove();
655 + // Re-send the original message with the new session
721 656 var originalMessage = getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message');
722 657 if (originalMessage) {
723 658 getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message', null);
724 - var currentModel = mxchatChat.model || 'gpt-5.1-chat-latest';
659 + // Re-add the user message and thinking indicator
660 + appendMessage("user", originalMessage, '', [], false, botId);
661 + appendThinkingMessage(botId);
662 + scrollToBottom(botId);
663 + // Determine whether to use streaming
664 + const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest';
725 665 if (shouldUseStreaming(currentModel)) {
726 666 callMxChatStream(originalMessage, function(response) {
727 667 getElement(botId, 'chat-box').find('.bot-message.temporary-message').removeClass('temporary-message');
728 668 }, botId);
@@ -864,9 +804,8 @@
864 804
865 805 replaceLastMessage("bot", errorMessage, '', [], botId);
866 806 }
867 807 });
868 - }); // refreshNonceIfNeeded
869 808 }
870 809
871 810 function callMxChatStream(message, callback, botId) {
872 811 botId = botId || getMxChatBotId();
@@ -885,25 +824,12 @@
885 824
886 825 // Get instance for session start timestamp (used when persistence is OFF)
887 826 var instance = MxChatInstances.get(botId);
888 827
889 - // Guarantee a non-null session_id before the fetch. FormData.append() stringifies any
890 - // non-string value via String(), so passing `null` would POST the literal string "null"
891 - // and land in the transcripts table as a ghost session. ensureSession() always returns
892 - // a real string even when cookies/localStorage are blocked.
893 - var streamSessionId = MxChatInstances.ensureSession(botId);
894 - if (!streamSessionId || streamSessionId === 'null' || streamSessionId === 'undefined') {
895 - streamSessionId = generateSessionId();
896 - MxChatInstances.setChatSession(botId, streamSessionId);
897 - }
898 -
899 - // Wait for the page-cache nonce refresh before constructing formData (which
900 - // captures mxchatChat.nonce by value). Mirrors callMxChat's wrapping. See plan-c5457f.
901 - refreshNonceIfNeeded(function() {
902 828 const formData = new FormData();
903 829 formData.append('action', 'mxchat_stream_chat');
904 830 formData.append('message', message);
905 - formData.append('session_id', streamSessionId);
831 + formData.append('session_id', getChatSession(botId));
906 832 formData.append('nonce', mxchatChat.nonce);
907 833 formData.append('current_page_url', window.location.href);
908 834 formData.append('current_page_title', document.title);
909 835 formData.append('bot_id', botId);
@@ -1003,16 +929,8 @@
1003 929
1004 930 // Re-enable chat input when stream ends with content
1005 931 enableChatInput(botId);
1006 932
1007 - // Scroll the user's last message to the top now that the
1008 - // bot's full reply has rendered (gives max reading room).
1009 - var $chatBoxDone = getElement(botId, 'chat-box');
1010 - var $lastUserMsgDone = $chatBoxDone.find('.user-message').last();
1011 - if ($lastUserMsgDone.length) {
1012 - scrollElementToTop($lastUserMsgDone, botId);
1013 - }
1014 -
1015 933 if (callback) {
1016 934 callback(accumulatedContent);
1017 935 }
1018 936 return;
@@ -1035,16 +953,8 @@
1035 953
1036 954 // Re-enable chat input after streaming completes
1037 955 enableChatInput(botId);
1038 956
1039 - // Scroll the user's last message to the top now
1040 - // that the bot's full reply has rendered.
1041 - var $chatBoxStreamDone = getElement(botId, 'chat-box');
1042 - var $lastUserMsgStreamDone = $chatBoxStreamDone.find('.user-message').last();
1043 - if ($lastUserMsgStreamDone.length) {
1044 - scrollElementToTop($lastUserMsgStreamDone, botId);
1045 - }
1046 -
1047 957 if (callback) {
1048 958 callback(accumulatedContent);
1049 959 }
1050 960 return;
@@ -1123,9 +1033,8 @@
1123 1033 getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove();
1124 1034 callMxChat(message, callback, botId);
1125 1035 }
1126 1036 });
1127 - }); // refreshNonceIfNeeded
1128 1037 }
1129 1038
1130 1039 // Helper function to handle non-streaming responses
1131 1040 function handleNonStreamResponse(data, callback, botId) {
@@ -1164,16 +1073,21 @@
1164 1073 errorMessage = "An error occurred. Please try again or contact support.";
1165 1074 }
1166 1075
1167 1076 // Handle session reset action (IP changed, session expired, etc.)
1168 - // Silent reset — keep chat UI intact, just get a new session and retry
1169 1077 if (data.data && data.data.action === 'reset_session') {
1170 - MxChatInstances.silentResetSession(botId);
1171 - // Re-send the original message with the new session (user message is already displayed)
1078 + // Clear the old session and generate a new one
1079 + resetChatSession(botId);
1080 + // Re-send the original message with the new session
1172 1081 var originalMessage = getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message');
1173 1082 if (originalMessage) {
1174 1083 getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message', null);
1175 - var currentModel = mxchatChat.model || 'gpt-5.1-chat-latest';
1084 + // Re-add the user message and thinking indicator
1085 + appendMessage("user", originalMessage, '', [], false, botId);
1086 + appendThinkingMessage(botId);
1087 + scrollToBottom(botId);
1088 + // Determine whether to use streaming
1089 + const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest';
1176 1090 if (shouldUseStreaming(currentModel)) {
1177 1091 callMxChatStream(originalMessage, callback, botId);
1178 1092 } else {
1179 1093 callMxChat(originalMessage, callback, botId);
@@ -1354,229 +1268,9 @@
1354 1268 sendMessage(botId);
1355 1269 }
1356 1270 });
1357 1271
1358 -// Builds the list of overflow-menu items for a given bot.
1359 -// Adding a future item is one push to this array — do NOT hardcode "only download."
1360 -function mxchatGetHeaderMenuItems(botId) {
1361 - var items = [];
1362 - var settings = (typeof mxchatChat !== 'undefined') ? mxchatChat : {};
1363 -
1364 - // The `print_button_*` keys still gate this item for back-compat with
1365 - // existing user options. The action is now a transcript download, not print.
1366 - if (settings.print_button_enabled === 'on') {
1367 - items.push({
1368 - id: 'download-transcript',
1369 - label: settings.print_button_label || 'Download Transcript',
1370 - icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
1371 - action: function() {
1372 - mxchatDownloadTranscript(botId);
1373 - }
1374 - });
1375 - }
1376 -
1377 - return items;
1378 -}
1379 -
1380 -// Builds a clean markdown transcript of the current conversation and triggers
1381 -// a file download. Used by the "Download Transcript" menu item.
1382 -function mxchatDownloadTranscript(botId) {
1383 - var $chatBox = getElement(botId, 'chat-box');
1384 - if (!$chatBox || !$chatBox.length) return;
1385 -
1386 - var settings = (typeof mxchatChat !== 'undefined') ? mxchatChat : {};
1387 - var headerTitle = settings.print_header_title || 'Chat transcript';
1388 - var now = new Date();
1389 - var stamp = now.toLocaleString();
1390 -
1391 - var lines = [];
1392 - lines.push('# ' + headerTitle);
1393 - lines.push('');
1394 - lines.push('Exported: ' + stamp);
1395 - lines.push('');
1396 - lines.push('---');
1397 - lines.push('');
1398 -
1399 - $chatBox.find('.user-message, .bot-message, .agent-message').each(function() {
1400 - var $msg = $(this);
1401 - // Skip thinking placeholders and any in-flight temporary messages.
1402 - if ($msg.find('.thinking-dots').length) return;
1403 - if ($msg.hasClass('temporary-message')) return;
1404 -
1405 - var sender;
1406 - if ($msg.hasClass('user-message')) sender = 'User';
1407 - else if ($msg.hasClass('agent-message')) sender = 'Live Agent';
1408 - else sender = 'AI Agent';
1409 -
1410 - // Strip interactive UI from the cloned message so we get the conversation text.
1411 - var $clone = $msg.clone();
1412 - $clone.find('.copy-button, .message-toolbar, .mxchat-copy, button, script, style').remove();
1413 - var text = $clone.text().replace(/ /g, ' ').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
1414 - if (!text) return;
1415 -
1416 - lines.push('**' + sender + '**');
1417 - lines.push('');
1418 - lines.push(text);
1419 - lines.push('');
1420 - });
1421 -
1422 - var content = lines.join('\n');
1423 - var iso = now.toISOString().replace(/[:.]/g, '-').slice(0, 19);
1424 - var fname = 'mxchat-transcript-' + iso + '.md';
1425 - var blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
1426 - var url = URL.createObjectURL(blob);
1427 - var a = document.createElement('a');
1428 - a.href = url;
1429 - a.download = fname;
1430 - a.style.display = 'none';
1431 - document.body.appendChild(a);
1432 - a.click();
1433 - setTimeout(function() {
1434 - if (a.parentNode) a.parentNode.removeChild(a);
1435 - URL.revokeObjectURL(url);
1436 - }, 100);
1437 -}
1438 -
1439 -// Reads the bot bubble's actual computed bg+fg and writes them as CSS vars
1440 -// on the menu wrap, so the dropdown matches whatever paints the bubble —
1441 -// saved options, AI theme CSS, or the mxchat-theme add-on.
1442 -function mxchatSyncMenuColors(botId, $wrap) {
1443 - if (!$wrap || !$wrap.length) return;
1444 - var $bot = $wrap.closest('.mxchat-chatbot-wrapper').find('.bot-message').not('.temporary-message').first();
1445 - if (!$bot.length) return;
1446 - var cs = window.getComputedStyle($bot[0]);
1447 - if (cs.backgroundColor && cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== 'transparent') {
1448 - $wrap[0].style.setProperty('--mxchat-menu-bg', cs.backgroundColor);
1449 - }
1450 - // Bot text color usually lives on a child div, not .bot-message itself.
1451 - var $textChild = $bot.find('[style*="color"]').first();
1452 - var fg = ($textChild.length ? window.getComputedStyle($textChild[0]).color : cs.color);
1453 - if (fg) $wrap[0].style.setProperty('--mxchat-menu-fg', fg);
1454 -}
1455 -
1456 -// One-time per-widget init: renders menu items, wires open/close,
1457 -// outside-click, Escape, and arrow-key navigation. If no items, hides the trigger.
1458 -function mxchatInitHeaderMenu(botId) {
1459 - var $wrap = $('.mxchat-header-menu-wrap[data-bot-id="' + botId + '"]').first();
1460 - if (!$wrap.length || $wrap.data('mxchatMenuReady')) return;
1461 -
1462 - var $trigger = $wrap.find('.mxchat-menu-trigger');
1463 - var $menu = $wrap.find('.mxchat-header-menu');
1464 - var items = mxchatGetHeaderMenuItems(botId);
1465 -
1466 - // Initial color sync — covers normal page load.
1467 - mxchatSyncMenuColors(botId, $wrap);
1468 -
1469 - if (!items.length) {
1470 - $trigger.hide();
1471 - $menu.hide();
1472 - $wrap.data('mxchatMenuReady', true);
1473 - return;
1474 - }
1475 -
1476 - // Build the menu items.
1477 - $menu.empty();
1478 - items.forEach(function(item, idx) {
1479 - var $btn = $('<button>', {
1480 - type: 'button',
1481 - 'class': 'mxchat-menu-item',
1482 - 'role': 'menuitem',
1483 - 'tabindex': '-1',
1484 - 'data-menu-id': item.id,
1485 - html: '<span class="mxchat-menu-item-icon">' + item.icon + '</span>' +
1486 - '<span class="mxchat-menu-item-label"></span>'
1487 - });
1488 - $btn.find('.mxchat-menu-item-label').text(item.label);
1489 - $btn.on('click', function(e) {
1490 - e.preventDefault();
1491 - e.stopPropagation();
1492 - closeMenu();
1493 - try { item.action(); } catch (err) { /* no-op */ }
1494 - });
1495 - $menu.append($btn);
1496 - });
1497 -
1498 - function openMenu() {
1499 - // Re-sync each open in case the active theme changed since init.
1500 - mxchatSyncMenuColors(botId, $wrap);
1501 - $menu.prop('hidden', false).attr('aria-hidden', 'false').addClass('is-open');
1502 - $trigger.attr('aria-expanded', 'true');
1503 - // Focus the first item for keyboard users
1504 - setTimeout(function() {
1505 - $menu.find('.mxchat-menu-item').first().attr('tabindex', '0').trigger('focus');
1506 - }, 0);
1507 - }
1508 - function closeMenu(returnFocus) {
1509 - $menu.prop('hidden', true).attr('aria-hidden', 'true').removeClass('is-open');
1510 - $trigger.attr('aria-expanded', 'false');
1511 - $menu.find('.mxchat-menu-item').attr('tabindex', '-1');
1512 - if (returnFocus) $trigger.trigger('focus');
1513 - }
1514 -
1515 - // Toggle on trigger click — stop propagation so the .chatbot-top-bar
1516 - // click-to-collapse handler does not fire.
1517 - $trigger.on('click', function(e) {
1518 - e.preventDefault();
1519 - e.stopPropagation();
1520 - if ($menu.hasClass('is-open')) closeMenu();
1521 - else openMenu();
1522 - });
1523 -
1524 - // Don't let clicks inside the menu bubble to the top-bar collapse handler.
1525 - $menu.on('click', function(e) {
1526 - e.stopPropagation();
1527 - });
1528 -
1529 - // Outside click closes the menu.
1530 - $(document).on('click.mxchatMenu-' + botId, function(e) {
1531 - if (!$menu.hasClass('is-open')) return;
1532 - if ($wrap.has(e.target).length || $wrap.is(e.target)) return;
1533 - closeMenu();
1534 - });
1535 -
1536 - // Keyboard: Escape closes and returns focus; arrow keys move focus; Enter activates.
1537 - $menu.on('keydown', '.mxchat-menu-item', function(e) {
1538 - var $items = $menu.find('.mxchat-menu-item');
1539 - var idx = $items.index(this);
1540 - if (e.key === 'Escape') {
1541 - e.preventDefault();
1542 - closeMenu(true);
1543 - } else if (e.key === 'ArrowDown') {
1544 - e.preventDefault();
1545 - var $next = $items.eq((idx + 1) % $items.length);
1546 - $items.attr('tabindex', '-1');
1547 - $next.attr('tabindex', '0').trigger('focus');
1548 - } else if (e.key === 'ArrowUp') {
1549 - e.preventDefault();
1550 - var $prev = $items.eq((idx - 1 + $items.length) % $items.length);
1551 - $items.attr('tabindex', '-1');
1552 - $prev.attr('tabindex', '0').trigger('focus');
1553 - } else if (e.key === 'Enter' || e.key === ' ') {
1554 - e.preventDefault();
1555 - $(this).trigger('click');
1556 - }
1557 - });
1558 - $trigger.on('keydown', function(e) {
1559 - if (e.key === 'Escape' && $menu.hasClass('is-open')) {
1560 - e.preventDefault();
1561 - closeMenu(true);
1562 - } else if ((e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') && !$menu.hasClass('is-open')) {
1563 - e.preventDefault();
1564 - openMenu();
1565 - }
1566 - });
1567 -
1568 - $wrap.data('mxchatMenuReady', true);
1569 -}
1570 -
1571 -// Initialize header menus for every rendered widget on DOM ready.
1572 -$(function() {
1573 - $('.mxchat-header-menu-wrap').each(function() {
1574 - var botId = $(this).data('bot-id');
1575 - if (botId) mxchatInitHeaderMenu(botId);
1576 - });
1577 -});
1578 -
1272 +
1579 1273 function appendMessage(sender, messageText = '', messageHtml = '', images = [], isTemporary = false, botId = 'default') {
1580 1274 try {
1581 1275 // Determine styles based on sender type
1582 1276 let messageClass, bgColor, fontColor;
@@ -1614,12 +1308,17 @@
1614 1308 'margin-bottom': '1em'
1615 1309 });
1616 1310 }
1617 1311
1618 - // Process the message content - always run linkify to convert markdown
1619 - // links and format text. linkify() handles existing HTML safely via
1620 - // negative lookaheads that skip URLs already inside <a> tags.
1621 - let fullMessage = linkify(messageText);
1312 + // Process the message content based on sender
1313 + let fullMessage;
1314 + if (sender === "user") {
1315 + // For user messages, apply linkify after sanitization
1316 + fullMessage = linkify(messageText);
1317 + } else {
1318 + // For bot/agent messages, preserve HTML
1319 + fullMessage = messageText;
1320 + }
1622 1321
1623 1322 // Add images if provided
1624 1323 if (images && images.length > 0) {
1625 1324 fullMessage += '<div class="image-gallery" dir="auto">';
@@ -1668,12 +1367,8 @@
1668 1367 if (lastUserMessage.length) {
1669 1368 scrollElementToTop(lastUserMessage, botId);
1670 1369 }
1671 1370 }
1672 -
1673 - if ((sender === "bot" || sender === "agent") && !isTemporary) {
1674 - if (typeof mxchatInitHeaderMenu === 'function') mxchatInitHeaderMenu(botId);
1675 - }
1676 1371 });
1677 1372
1678 1373 if (messageText.id) {
1679 1374 var instance = MxChatInstances.get(botId);
@@ -1758,12 +1453,26 @@
1758 1453 bgColor = botMessageBgColor;
1759 1454 fontColor = botMessageFontColor;
1760 1455 }
1761 1456
1762 - // Always run linkify to convert markdown links and format text.
1763 - // linkify() already handles existing HTML (its URL patterns use negative lookaheads
1764 - // to avoid double-processing URLs that are already inside <a> tags).
1765 - var fullMessage = linkify(responseText);
1457 + // FIXED: Only linkify if response doesn't already contain HTML links or tags
1458 + // This prevents double-processing of URLs that are already formatted as HTML
1459 + var fullMessage;
1460 + if (sender === "user") {
1461 + // Always linkify user messages (they're plain text)
1462 + fullMessage = linkify(responseText);
1463 + } else {
1464 + // For bot/agent messages, check if HTML already exists
1465 + if (responseText.includes('<a href=') || responseText.includes('</a>') ||
1466 + responseText.includes('<img') || responseText.includes('<div') ||
1467 + responseText.includes('<p>') || responseText.includes('<br>')) {
1468 + // Response already has HTML, don't process it
1469 + fullMessage = responseText;
1470 + } else {
1471 + // Plain text response, apply linkify
1472 + fullMessage = linkify(responseText);
1473 + }
1474 + }
1766 1475
1767 1476 if (responseHtml) {
1768 1477 // Only add line breaks if there's actual text content before the HTML
1769 1478 if (fullMessage && fullMessage.trim()) {
@@ -1820,12 +1529,8 @@
1820 1529 }
1821 1530
1822 1531 // Re-enable chat input after response is displayed
1823 1532 enableChatInput(botId);
1824 -
1825 - if (sender === "bot" || sender === "agent") {
1826 - if (typeof mxchatInitHeaderMenu === 'function') mxchatInitHeaderMenu(botId);
1827 - }
1828 1533 } else {
1829 1534 appendMessage(sender, responseText, responseHtml, images, false, botId);
1830 1535 // Re-enable chat input after response is displayed
1831 1536 enableChatInput(botId);
@@ -1928,63 +1633,37 @@
1928 1633 // Return as a proper link without the brackets
1929 1634 return `<a href="${safeUrl}" target="${linkTarget}">${cleanUrl}</a>`;
1930 1635 });
1931 1636
1932 - // Process markdown links: [text](url) and [](url)
1933 - // Uses balanced parenthesis matching to handle URLs containing parens
1934 - // (e.g. PDF filenames with dates like (2025-08-28).pdf)
1935 - processedText = (function(input) {
1936 - var result = '';
1937 - var i = 0;
1938 - while (i < input.length) {
1939 - // Look for [ at current position
1940 - if (input[i] === '[') {
1941 - // Find closing ]
1942 - var closeBracket = input.indexOf(']', i + 1);
1943 - if (closeBracket === -1 || closeBracket + 1 >= input.length || input[closeBracket + 1] !== '(') {
1944 - result += input[i];
1945 - i++;
1946 - continue;
1947 - }
1948 - var linkText = input.substring(i + 1, closeBracket);
1949 - // Check if URL starts with http
1950 - var urlStart = closeBracket + 2;
1951 - if (!input.substring(urlStart).match(/^https?:\/\//)) {
1952 - result += input[i];
1953 - i++;
1954 - continue;
1955 - }
1956 - // Find balanced closing paren
1957 - var depth = 1;
1958 - var j = urlStart;
1959 - while (j < input.length && depth > 0) {
1960 - if (input[j] === '(') depth++;
1961 - else if (input[j] === ')') depth--;
1962 - if (depth > 0) j++;
1963 - }
1964 - if (depth !== 0) {
1965 - result += input[i];
1966 - i++;
1967 - continue;
1968 - }
1969 - var url = input.substring(urlStart, j);
1970 - var cleanUrl = url.replace(/[\].,;!?]+$/, '');
1971 - var encodedUrl = safeEncodeUrl(cleanUrl);
1972 - if (!linkText || !linkText.trim()) {
1973 - result += '<a href="' + encodedUrl + '" target="' + linkTarget + '">' + cleanUrl + '</a>';
1974 - } else {
1975 - var safeText = sanitizeUserInput(linkText);
1976 - result += '<a href="' + encodedUrl + '" target="' + linkTarget + '">' + safeText + '</a>';
1977 - }
1978 - i = j + 1; // Skip past the closing )
1979 - } else {
1980 - result += input[i];
1981 - i++;
1982 - }
1637 + // Process proper markdown links with text: [text](url)
1638 + // This MUST have non-empty text in the first brackets
1639 + const markdownLinkPattern = /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g;
1640 + processedText = processedText.replace(markdownLinkPattern, (match, text, url) => {
1641 + // Make sure we have actual text (not just whitespace)
1642 + if (!text || !text.trim()) {
1643 + // If no text, treat the URL as the text
1644 + let cleanUrl = url.replace(/[.,;!?]+$/, '');
1645 + const safeUrl = safeEncodeUrl(cleanUrl);
1646 + return `<a href="${safeUrl}" target="${linkTarget}">${cleanUrl}</a>`;
1983 1647 }
1984 - return result;
1985 - })(processedText);
1648 +
1649 + // Clean the URL
1650 + let cleanUrl = url.replace(/[\].,;!?]+$/, '');
1651 + const safeUrl = safeEncodeUrl(cleanUrl);
1652 + const safeText = sanitizeUserInput(text);
1653 + return `<a href="${safeUrl}" target="${linkTarget}">${safeText}</a>`;
1654 + });
1986 1655
1656 + // Handle empty markdown links: [](url)
1657 + // This is a specific case where there's no text
1658 + const emptyMarkdownPattern = /\[\]\((https?:\/\/[^\s)]+)\)/g;
1659 + processedText = processedText.replace(emptyMarkdownPattern, (match, url) => {
1660 + let cleanUrl = url.replace(/[.,;!?]+$/, '');
1661 + const safeUrl = safeEncodeUrl(cleanUrl);
1662 + // Use the URL itself as the link text
1663 + return `<a href="${safeUrl}" target="${linkTarget}">${cleanUrl}</a>`;
1664 + });
1665 +
1987 1666 // Process phone numbers: [text](tel:number)
1988 1667 const phonePattern = /\[([^\]]+)\]\((tel:[\d+\-\s()]+)\)/g;
1989 1668 processedText = processedText.replace(phonePattern, (match, text, phone) => {
1990 1669 const safePhone = safeEncodeUrl(phone);
@@ -2278,14 +1957,13 @@
2278 1957 requestAnimationFrame(smoothScroll);
2279 1958 }
2280 1959 }
2281 1960
2282 - function scrollElementToTop(element, botId, topOffset) {
1961 + function scrollElementToTop(element, botId) {
2283 1962 botId = botId || 'default';
2284 - topOffset = (typeof topOffset === 'number') ? topOffset : 2;
2285 1963 var chatBox = getElement(botId, 'chat-box');
2286 1964 var elementTop = element.position().top + chatBox.scrollTop();
2287 - chatBox.animate({ scrollTop: Math.max(0, elementTop - topOffset) }, 500);
1965 + chatBox.animate({ scrollTop: elementTop }, 500);
2288 1966 }
2289 1967
2290 1968 function showChatWidget(botId) {
2291 1969 botId = botId || 'default';
@@ -2512,19 +2190,11 @@
2512 2190 if (onComplete) onComplete();
2513 2191 return;
2514 2192 }
2515 2193
2516 - // Use getChatSession which returns null if no session exists (does NOT create one)
2517 2194 var sessionId = getChatSession(botId);
2518 2195 var chatPersistenceEnabled = mxchatChat.chat_persistence_toggle === 'on';
2519 2196
2520 - // No session yet — nothing to load. History will load after first message via ensureSession.
2521 - if (!sessionId) {
2522 - instance.chatHistoryLoaded = true;
2523 - if (onComplete) onComplete();
2524 - return;
2525 - }
2526 -
2527 2197 if (chatPersistenceEnabled && sessionId) {
2528 2198 $.ajax({
2529 2199 url: mxchatChat.ajax_url,
2530 2200 type: 'POST',
@@ -2535,10 +2205,10 @@
2535 2205 },
2536 2206 success: function(response) {
2537 2207 // Handle session reset (IP changed while user was away)
2538 2208 if (response.success === false && response.data && response.data.action === 'reset_session') {
2539 - // Silent reset — new session but don't clear UI
2540 - MxChatInstances.silentResetSession(botId);
2209 + // Silently reset session - user will start fresh
2210 + resetChatSession(botId);
2541 2211 instance.chatHistoryLoaded = true; // Prevent retry loop
2542 2212 if (onComplete) onComplete();
2543 2213 return;
2544 2214 }
@@ -2596,19 +2266,9 @@
2596 2266 var content = message.content;
2597 2267 content = content.replace(/\\'/g, "'").replace(/\\"/g, '"');
2598 2268 content = decodeHTMLEntities(content);
2599 2269
2600 - // Skip linkify for messages containing structured HTML
2601 - // (forms, product cards, galleries, etc.) to avoid
2602 - // markdown formatting corrupting HTML attributes
2603 - // (e.g. underscores in name="field_name" becoming <em> tags)
2604 - if (content.includes("mxchat-product-card") ||
2605 - content.includes("mxchat-image-gallery") ||
2606 - content.includes("mxchat-featured-products") ||
2607 - content.includes("<form") ||
2608 - content.includes("<input") ||
2609 - content.includes("<select") ||
2610 - content.includes("<textarea")) {
2270 + if (content.includes("mxchat-product-card") || content.includes("mxchat-image-gallery")) {
2611 2271 messageElement.html(content);
2612 2272 } else {
2613 2273 var formattedContent = linkify(content);
2614 2274 messageElement.html(formattedContent);
@@ -2835,20 +2495,14 @@
2835 2495
2836 2496 function checkPreChatDismissal(botId) {
2837 2497 botId = botId || 'default';
2838 2498 try {
2839 - var dismissedAt = localStorage.getItem('mxchat_pre_chat_dismissed_' + botId);
2840 - if (dismissedAt) {
2841 - // Re-show after 24 hours
2842 - var elapsed = Date.now() - parseInt(dismissedAt, 10);
2843 - if (elapsed < 86400000) {
2844 - getElement(botId, 'pre-chat-message').hide();
2845 - return;
2846 - }
2847 - // Expired — clear and show again
2848 - localStorage.removeItem('mxchat_pre_chat_dismissed_' + botId);
2499 + var dismissed = localStorage.getItem('mxchat_pre_chat_dismissed_' + botId);
2500 + if (!dismissed) {
2501 + getElement(botId, 'pre-chat-message').fadeIn(250);
2502 + } else {
2503 + getElement(botId, 'pre-chat-message').hide();
2849 2504 }
2850 - getElement(botId, 'pre-chat-message').fadeIn(250);
2851 2505 } catch (e) {
2852 2506 // localStorage unavailable — show the message
2853 2507 getElement(botId, 'pre-chat-message').fadeIn(250);
2854 2508 }
@@ -2857,9 +2511,9 @@
2857 2511 function handlePreChatDismissal(botId) {
2858 2512 botId = botId || 'default';
2859 2513 getElement(botId, 'pre-chat-message').fadeOut(200);
2860 2514 try {
2861 - localStorage.setItem('mxchat_pre_chat_dismissed_' + botId, String(Date.now()));
2515 + localStorage.setItem('mxchat_pre_chat_dismissed_' + botId, '1');
2862 2516 } catch (e) {
2863 2517 // localStorage unavailable — dismissal won't persist
2864 2518 }
2865 2519 }
@@ -2930,14 +2584,8 @@
2930 2584 $badge.hide(); // Hide notification when opening chat
2931 2585 disableScroll();
2932 2586 $preChat.fadeOut(250);
2933 2587
2934 - // Load chat history for returning visitors (persistence)
2935 - var chatPersistenceEnabled = typeof mxchatChat !== 'undefined' && mxchatChat.chat_persistence_toggle === 'on';
2936 - if (chatPersistenceEnabled) {
2937 - MxChatInstances.ensureSession(botId);
2938 - }
2939 -
2940 2588 // Deferred email check — only on first widget open
2941 2589 var emailBlocker = getElementDOM(botId, 'email-blocker');
2942 2590 var instance = MxChatInstances.get(botId);
2943 2591 if (emailBlocker && !instance.emailCheckDone) {
@@ -2942,12 +2590,8 @@
2942 2590 var instance = MxChatInstances.get(botId);
2943 2591 if (emailBlocker && !instance.emailCheckDone) {
2944 2592 instance.emailCheckDone = true;
2945 2593 resolveEmailState(botId);
2946 - } else if (!emailBlocker) {
2947 - // No email collection — still route through showChatContainerForBot
2948 - // so the loader is shown while chat history loads
2949 - showChatContainerForBot(botId);
2950 2594 }
2951 2595 } else {
2952 2596 $chatbot.removeClass('visible').addClass('hidden');
2953 2597 $(this).removeClass('hidden');
@@ -2966,9 +2610,11 @@
2966 2610
2967 2611 $(document).on('click', '.close-pre-chat-message', function(e) {
2968 2612 e.stopPropagation(); // Prevent triggering the parent .pre-chat-message click
2969 2613 var botId = getBotIdFromElement(this);
2970 - handlePreChatDismissal(botId);
2614 + getElement(botId, 'pre-chat-message').fadeOut(200, function() {
2615 + $(this).remove();
2616 + });
2971 2617 });
2972 2618
2973 2619
2974 2620 // PDF upload button handlers - use class selector
@@ -3009,10 +2655,8 @@
3009 2655 const sendBtn = document.getElementById('send-button');
3010 2656 const originalBtnContent = uploadBtn.innerHTML;
3011 2657
3012 2658 try {
3013 - // Wait for page-cache nonce refresh before reading mxchatChat.nonce. See plan-c5457f.
3014 - await new Promise(function(resolve) { refreshNonceIfNeeded(resolve); });
3015 2659 const formData = new FormData();
3016 2660 formData.append('action', 'mxchat_upload_pdf');
3017 2661 formData.append('pdf_file', file);
3018 2662 formData.append('session_id', sessionId);
@@ -3076,10 +2720,8 @@
3076 2720 const sendBtn = document.getElementById('send-button');
3077 2721 const originalBtnContent = uploadBtn.innerHTML;
3078 2722
3079 2723 try {
3080 - // Wait for page-cache nonce refresh before reading mxchatChat.nonce. See plan-c5457f.
3081 - await new Promise(function(resolve) { refreshNonceIfNeeded(resolve); });
3082 2724 const formData = new FormData();
3083 2725 formData.append('action', 'mxchat_upload_word');
3084 2726 formData.append('word_file', file);
3085 2727 formData.append('session_id', sessionId);
@@ -3173,59 +2815,8 @@
3173 2815 });
3174 2816
3175 2817
3176 2818 // ====================================
3177 -// INIT LOADER & CHAT CONTAINER HELPERS
3178 -// ====================================
3179 -// These must be outside the email collection block so they're always available
3180 -// (used by persistence loading even when email collection is off)
3181 -
3182 -function showInitLoader(botId) {
3183 - var loader = getElementDOM(botId, 'mxchat-init-loader');
3184 - if (loader) loader.style.display = 'flex';
3185 -}
3186 -
3187 -function hideInitLoader(botId) {
3188 - var loader = getElementDOM(botId, 'mxchat-init-loader');
3189 - if (loader) loader.style.display = 'none';
3190 -}
3191 -
3192 -function showEmailFormForBot(botId) {
3193 - hideInitLoader(botId);
3194 - var emailBlocker = getElementDOM(botId, 'email-blocker');
3195 - var chatContainer = getElementDOM(botId, 'chat-container');
3196 - if (emailBlocker) emailBlocker.style.display = 'flex';
3197 - if (chatContainer) chatContainer.style.display = 'none';
3198 -}
3199 -
3200 -function showChatContainerForBot(botId) {
3201 - var emailBlocker = getElementDOM(botId, 'email-blocker');
3202 - var chatContainer = getElementDOM(botId, 'chat-container');
3203 - if (emailBlocker) emailBlocker.style.display = 'none';
3204 -
3205 - var instance = MxChatInstances.get(botId);
3206 - var chatPersistenceEnabled = mxchatChat.chat_persistence_toggle === 'on';
3207 -
3208 - // If persistence is on and history hasn't loaded yet, show loader
3209 - // while history loads to prevent flash of empty chat
3210 - if (chatPersistenceEnabled && !instance.chatHistoryLoaded) {
3211 - if (chatContainer) chatContainer.style.display = 'none';
3212 - showInitLoader(botId);
3213 - loadChatHistory(botId, function() {
3214 - hideInitLoader(botId);
3215 - if (chatContainer) chatContainer.style.display = 'flex';
3216 - scrollToBottom(botId, true);
3217 - });
3218 - } else {
3219 - hideInitLoader(botId);
3220 - if (chatContainer) chatContainer.style.display = 'flex';
3221 - if (typeof loadChatHistory === 'function') {
3222 - loadChatHistory(botId);
3223 - }
3224 - }
3225 -}
3226 -
3227 -// ====================================
3228 2819 // EMAIL COLLECTION SETUP - MULTI-INSTANCE VERSION
3229 2820 // ====================================
3230 2821 // Only run email collection setup if it's enabled
3231 2822 if (mxchatChat && mxchatChat.email_collection_enabled === 'on') {
@@ -3261,8 +2852,40 @@
3261 2852 `;
3262 2853 document.head.appendChild(style);
3263 2854 }
3264 2855
2856 + // Helper functions for email collection (multi-instance aware)
2857 + function showEmailFormForBot(botId) {
2858 + var emailBlocker = getElementDOM(botId, 'email-blocker');
2859 + var chatContainer = getElementDOM(botId, 'chat-container');
2860 + if (emailBlocker) emailBlocker.style.display = 'flex';
2861 + if (chatContainer) chatContainer.style.display = 'none';
2862 + }
2863 +
2864 + function showChatContainerForBot(botId) {
2865 + var emailBlocker = getElementDOM(botId, 'email-blocker');
2866 + var chatContainer = getElementDOM(botId, 'chat-container');
2867 + if (emailBlocker) emailBlocker.style.display = 'none';
2868 +
2869 + var instance = MxChatInstances.get(botId);
2870 + var chatPersistenceEnabled = mxchatChat.chat_persistence_toggle === 'on';
2871 +
2872 + // If persistence is on and history hasn't loaded yet, keep container
2873 + // hidden until history loads to prevent flash of empty chat
2874 + if (chatPersistenceEnabled && !instance.chatHistoryLoaded) {
2875 + if (chatContainer) chatContainer.style.display = 'none';
2876 + loadChatHistory(botId, function() {
2877 + if (chatContainer) chatContainer.style.display = 'flex';
2878 + scrollToBottom(botId, true);
2879 + });
2880 + } else {
2881 + if (chatContainer) chatContainer.style.display = 'flex';
2882 + if (typeof loadChatHistory === 'function') {
2883 + loadChatHistory(botId);
2884 + }
2885 + }
2886 + }
2887 +
3265 2888 function isValidEmailAddress(email) {
3266 2889 const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
3267 2890 return emailRegex.test(email.trim()) && email.length <= 254;
3268 2891 }
@@ -3398,16 +3021,15 @@
3398 3021 }
3399 3022 }
3400 3023
3401 3024 function checkSessionAndEmailForBot(botId) {
3402 - const sessionId = MxChatInstances.ensureSession(botId);
3025 + const sessionId = getChatSession(botId);
3403 3026
3404 - // Hide both panels while we check — show loader instead
3027 + // Hide both panels while we check — prevents flash of wrong state
3405 3028 var emailBlocker = getElementDOM(botId, 'email-blocker');
3406 3029 var chatContainer = getElementDOM(botId, 'chat-container');
3407 3030 if (emailBlocker) emailBlocker.style.display = 'none';
3408 3031 if (chatContainer) chatContainer.style.display = 'none';
3409 - showInitLoader(botId);
3410 3032
3411 3033 fetch(mxchatChat.ajax_url, {
3412 3034 method: 'POST',
3413 3035 headers: {
@@ -3456,9 +3078,9 @@
3456 3078 var emailInput = getElementDOM(botId, 'user-email');
3457 3079 var nameInput = getElementDOM(botId, 'user-name');
3458 3080 var userEmail = emailInput ? emailInput.value.trim() : '';
3459 3081 var userName = nameInput ? nameInput.value.trim() : '';
3460 - var sessionId = MxChatInstances.ensureSession(botId);
3082 + var sessionId = getChatSession(botId);
3461 3083
3462 3084 // Validate email
3463 3085 if (!userEmail) {
3464 3086 showEmailError(botId, 'Please enter your email address.');
@@ -3587,8 +3209,9 @@
3587 3209 $('.mxchat-chatbot-wrapper').each(function() {
3588 3210 var botId = $(this).data('bot-id') || 'default';
3589 3211 var emailBlocker = getElementDOM(botId, 'email-blocker');
3590 3212
3213 + // Only check if email blocker exists for this bot
3591 3214 if (emailBlocker) {
3592 3215 if (isEmbeddedBot(botId)) {
3593 3216 // Embedded bots are always visible — check now
3594 3217 resolveEmailState(botId);
@@ -3593,15 +3216,8 @@
3593 3216 // Embedded bots are always visible — check now
3594 3217 resolveEmailState(botId);
3595 3218 }
3596 3219 // Floating bots: handled in the widget open handler
3597 - } else if (isEmbeddedBot(botId)) {
3598 - // Embedded bot, no email collection — load history with loader
3599 - var chatPersistenceEnabled = typeof mxchatChat !== 'undefined' && mxchatChat.chat_persistence_toggle === 'on';
3600 - if (chatPersistenceEnabled) {
3601 - MxChatInstances.ensureSession(botId);
3602 - showChatContainerForBot(botId);
3603 - }
3604 3220 }
3605 3221 });
3606 3222 }
3607 3223
@@ -3611,17 +3227,11 @@
3611 3227 var $chatbot = getElement(botId, 'floating-chatbot');
3612 3228 if ($chatbot.hasClass('hidden')) {
3613 3229 $chatbot.removeClass('hidden').addClass('visible');
3614 3230 getElement(botId, 'floating-chatbot-button').addClass('hidden');
3615 - handlePreChatDismissal(botId);
3231 + $(this).fadeOut(250); // Hide pre-chat message
3616 3232 disableScroll(); // Disable scroll when chatbot opens
3617 3233
3618 - // Load chat history for returning visitors (persistence)
3619 - var chatPersistenceEnabled = typeof mxchatChat !== 'undefined' && mxchatChat.chat_persistence_toggle === 'on';
3620 - if (chatPersistenceEnabled) {
3621 - MxChatInstances.ensureSession(botId);
3622 - }
3623 -
3624 3234 // Deferred email check — only on first widget open
3625 3235 var emailBlocker = getElementDOM(botId, 'email-blocker');
3626 3236 var instance = MxChatInstances.get(botId);
3627 3237 if (emailBlocker && !instance.emailCheckDone) {
@@ -3626,17 +3236,38 @@
3626 3236 var instance = MxChatInstances.get(botId);
3627 3237 if (emailBlocker && !instance.emailCheckDone) {
3628 3238 instance.emailCheckDone = true;
3629 3239 resolveEmailState(botId);
3630 - } else if (!emailBlocker) {
3631 - showChatContainerForBot(botId);
3632 3240 }
3633 3241 }
3634 3242 });
3635 3243
3636 - // Legacy duplicate close handler removed — handled by single event delegation above
3244 + // Dismiss pre-chat message via close button - handled by event delegation above at line ~2376
3245 + // This is a fallback for legacy support
3246 + $(document).on('click', '.close-pre-chat-message', function() {
3247 + var botId = getBotIdFromElement(this);
3248 + var $preChat = getElement(botId, 'pre-chat-message');
3249 + $preChat.fadeOut(200); // Hide the message
3637 3250
3251 + // Send an AJAX request to set the transient flag for 24 hours
3252 + $.ajax({
3253 + url: mxchatChat.ajax_url,
3254 + type: 'POST',
3255 + data: {
3256 + action: 'mxchat_dismiss_pre_chat_message',
3257 + _ajax_nonce: mxchatChat.nonce
3258 + },
3259 + success: function() {
3260 + // Ensure the message is hidden after dismissal
3261 + $preChat.hide();
3262 + },
3263 + error: function() {
3264 + // Error dismissing pre-chat message - silently continue
3265 + }
3266 + });
3267 + });
3638 3268
3269 +
3639 3270 function hasQuickQuestions(botId) {
3640 3271 botId = botId || 'default';
3641 3272 var questionsContainer = getElementDOM(botId, 'mxchat-popular-questions');
3642 3273 if (!questionsContainer) return false;
@@ -3829,265 +3460,6 @@
3829 3460 }, 2000);
3830 3461 });
3831 3462 }
3832 3463 }
3833 -});
3834 -
3835 -// ============================================================================
3836 -// SATISFACTION RATING (v3.2.6)
3837 -// ============================================================================
3838 -// Per-session 👍/👎 prompt that appears in the chat-box after 60s of user
3839 -// inactivity following a bot reply. One prompt per session, deduped via
3840 -// localStorage. Disabled site-wide when mxchatChat.satisfaction_rating_enabled
3841 -// is exactly false (default ON).
3842 -jQuery(function($) {
3843 - if (typeof mxchatChat === 'undefined') return;
3844 - if (mxchatChat.satisfaction_rating_enabled === false || mxchatChat.satisfaction_rating_enabled === 'off') return;
3845 -
3846 - // wp_localize_script stringifies ints, so accept both number and numeric string.
3847 - var idleRaw = mxchatChat.satisfaction_rating_idle_seconds;
3848 - var idleSeconds = (typeof idleRaw === 'number') ? idleRaw : parseInt(idleRaw, 10);
3849 - if (!isFinite(idleSeconds)) idleSeconds = 60;
3850 - if (idleSeconds < 5) idleSeconds = 5;
3851 - if (idleSeconds > 600) idleSeconds = 600;
3852 - var IDLE_MS = idleSeconds * 1000;
3853 - var MIN_BOT_REPLIES = 2;
3854 - var ratingState = {};
3855 -
3856 - function getState(botId) {
3857 - if (!ratingState[botId]) {
3858 - ratingState[botId] = { idleTimer: null, botReplies: 0, promptShown: false, dismissed: false };
3859 - }
3860 - return ratingState[botId];
3861 - }
3862 -
3863 - function getSessionId(botId) {
3864 - if (typeof MxChatInstances !== 'undefined' && MxChatInstances.getChatSession) {
3865 - return MxChatInstances.getChatSession(botId);
3866 - }
3867 - return null;
3868 - }
3869 -
3870 - function isAlreadyRated(sessionId) {
3871 - if (!sessionId) return false;
3872 - try { return localStorage.getItem('mxchat_rated:' + sessionId) === '1'; } catch (e) { return false; }
3873 - }
3874 -
3875 - function markRated(sessionId) {
3876 - if (!sessionId) return;
3877 - try { localStorage.setItem('mxchat_rated:' + sessionId, '1'); } catch (e) {}
3878 - }
3879 -
3880 - function esc(s) {
3881 - return String(s == null ? '' : s)
3882 - .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
3883 - .replace(/"/g, '&quot;').replace(/'/g, '&#039;');
3884 - }
3885 -
3886 - // Mirror shouldSkipInlineColors so rating bubbles defer to AI-theme CSS.
3887 - function ratingSkipInlineColors(botId) {
3888 - if (mxchatChat.skip_inline_colors) return true;
3889 - var botAssignments = mxchatChat.bot_theme_assignments || {};
3890 - return botAssignments.hasOwnProperty(botId);
3891 - }
3892 -
3893 - function botBubbleStyleAttr(botId) {
3894 - if (ratingSkipInlineColors(botId)) return '';
3895 - var bg = mxchatChat.bot_message_bg_color;
3896 - var fg = mxchatChat.bot_message_font_color;
3897 - if (!bg && !fg) return '';
3898 - return ' style="background-color: ' + esc(bg || '') + '; color: ' + esc(fg || '') + ';"';
3899 - }
3900 -
3901 - function copy(key) {
3902 - var c = mxchatChat.satisfaction_rating_copy || {};
3903 - var d = {
3904 - question: 'Was this helpful?',
3905 - helpful: 'Helpful',
3906 - not_helpful: 'Not helpful',
3907 - dismiss: 'Dismiss',
3908 - thanks: 'Thanks! Anything we should improve? (optional)',
3909 - placeholder: 'Tell us what could be better…',
3910 - send: 'Send',
3911 - skip: 'Skip',
3912 - saved: 'Thanks for the feedback.'
3913 - };
3914 - return c[key] || d[key];
3915 - }
3916 -
3917 - function thumbUpSvg() {
3918 - return '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M7.493 18.75c-.425 0-.82-.236-.975-.632A7.48 7.48 0 0 1 6 15.375c0-1.75.599-3.358 1.602-4.634.151-.192.373-.309.6-.397.473-.183.89-.514 1.212-.924a9.042 9.042 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75A.75.75 0 0 1 15 2a2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H14.23c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23h-.777Z"/><path d="M2.331 10.977a11.969 11.969 0 0 0-.831 4.398 12 12 0 0 0 .52 3.507c.26.85 1.084 1.368 1.973 1.368H4.9c.445 0 .72-.498.523-.898a8.963 8.963 0 0 1-.924-3.977c0-1.708.476-3.305 1.302-4.666.245-.403-.028-.959-.5-.959H4.25c-.832 0-1.612.453-1.918 1.227Z"/></svg>';
3919 - }
3920 - function thumbDownSvg() {
3921 - return '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M15.73 5.25h1.035A7.465 7.465 0 0 1 18 9.375a7.465 7.465 0 0 1-1.235 4.125h-.148c-.806 0-1.534.446-2.031 1.08a9.04 9.04 0 0 1-2.861 2.4c-.723.384-1.35.956-1.653 1.715a4.498 4.498 0 0 0-.322 1.672V21a.75.75 0 0 1-.75.75 2.25 2.25 0 0 1-2.25-2.25c0-1.152.26-2.243.723-3.218.266-.558-.107-1.282-.725-1.282H3.622c-1.026 0-1.945-.694-2.054-1.715A12.137 12.137 0 0 1 1.5 12c0-2.848.992-5.464 2.649-7.521C4.537 3.997 5.136 3.75 5.754 3.75h4.541c.483 0 .964.078 1.423.23l3.114 1.04c.46.152.94.23 1.423.23Z"/><path d="M21.669 13.023c.536-1.362.831-2.845.831-4.398 0-1.22-.182-2.398-.52-3.507-.26-.85-1.084-1.368-1.973-1.368H19.1c-.445 0-.72.498-.523.898.591 1.2.924 2.55.924 3.977a8.958 8.958 0 0 1-1.302 4.666c-.245.403.028.959.5.959h1.053c.832 0 1.612-.453 1.918-1.227Z"/></svg>';
3922 - }
3923 -
3924 - function buildPromptHtml(botId) {
3925 - var styleAttr = botBubbleStyleAttr(botId);
3926 - return ''
3927 - + '<div class="bot-message mxchat-rating-bot-bubble"' + styleAttr + '>'
3928 - + '<div class="mxchat-rating-prompt" data-bot-id="' + esc(botId) + '" role="group" aria-label="' + esc(copy('question')) + '">'
3929 - + '<div class="mxchat-rating-question">' + esc(copy('question')) + '</div>'
3930 - + '<div class="mxchat-rating-actions">'
3931 - + '<span class="mxchat-rating-buttons">'
3932 - + '<button type="button" class="mxchat-rating-btn" data-rating="1" aria-label="' + esc(copy('helpful')) + '">' + thumbUpSvg() + '</button>'
3933 - + '<button type="button" class="mxchat-rating-btn" data-rating="-1" aria-label="' + esc(copy('not_helpful')) + '">' + thumbDownSvg() + '</button>'
3934 - + '</span>'
3935 - + '<button type="button" class="mxchat-rating-dismiss" aria-label="' + esc(copy('dismiss')) + '">×</button>'
3936 - + '</div>'
3937 - + '</div>'
3938 - + '</div>';
3939 - }
3940 -
3941 - function buildFeedbackHtml(botId, rating) {
3942 - var styleAttr = botBubbleStyleAttr(botId);
3943 - return ''
3944 - + '<div class="bot-message mxchat-rating-bot-bubble"' + styleAttr + '>'
3945 - + '<div class="mxchat-rating-feedback" data-bot-id="' + esc(botId) + '" data-rating="' + esc(String(rating)) + '">'
3946 - + '<div class="mxchat-rating-feedback-label">' + esc(copy('thanks')) + '</div>'
3947 - + '<textarea class="mxchat-rating-feedback-input" maxlength="500" placeholder="' + esc(copy('placeholder')) + '" rows="2"></textarea>'
3948 - + '<div class="mxchat-rating-feedback-actions">'
3949 - + '<button type="button" class="mxchat-rating-skip">' + esc(copy('skip')) + '</button>'
3950 - + '<button type="button" class="mxchat-rating-submit">' + esc(copy('send')) + '</button>'
3951 - + '</div>'
3952 - + '</div>'
3953 - + '</div>';
3954 - }
3955 -
3956 - function buildSavedHtml(botId) {
3957 - var styleAttr = botBubbleStyleAttr(botId);
3958 - return ''
3959 - + '<div class="bot-message mxchat-rating-bot-bubble"' + styleAttr + '>'
3960 - + '<div class="mxchat-rating-saved">' + esc(copy('saved')) + '</div>'
3961 - + '</div>';
3962 - }
3963 -
3964 - function getChatBoxByBotId(botId) {
3965 - var $byId = $('#chat-box-' + botId);
3966 - if ($byId.length) return $byId.first();
3967 - return $('.chat-box').first();
3968 - }
3969 -
3970 - function scrollChatBoxToBottom($chatBox) {
3971 - if (!$chatBox || !$chatBox.length) return;
3972 - $chatBox.scrollTop($chatBox[0].scrollHeight);
3973 - }
3974 -
3975 - function showPrompt(botId) {
3976 - var s = getState(botId);
3977 - if (s.promptShown || s.dismissed) return;
3978 - var sessionId = getSessionId(botId);
3979 - if (!sessionId) return;
3980 - if (isAlreadyRated(sessionId)) { s.promptShown = true; return; }
3981 - var $chatBox = getChatBoxByBotId(botId);
3982 - if (!$chatBox.length) return;
3983 - if ($chatBox.find('.mxchat-rating-prompt').length) { s.promptShown = true; return; }
3984 - $chatBox.append(buildPromptHtml(botId));
3985 - s.promptShown = true;
3986 - scrollChatBoxToBottom($chatBox);
3987 - }
3988 -
3989 - function submitRating(botId, rating, feedback) {
3990 - var sessionId = getSessionId(botId);
3991 - if (!sessionId) return;
3992 - $.post(mxchatChat.ajax_url, {
3993 - action: 'mxchat_save_rating',
3994 - session_id: sessionId,
3995 - bot_id: botId,
3996 - rating: rating,
3997 - feedback: feedback || ''
3998 - });
3999 - markRated(sessionId);
4000 - }
4001 -
4002 - function onBotReply(botId) {
4003 - var s = getState(botId);
4004 - s.botReplies += 1;
4005 - if (s.promptShown || s.dismissed) return;
4006 - var sessionId = getSessionId(botId);
4007 - if (sessionId && isAlreadyRated(sessionId)) { s.promptShown = true; return; }
4008 - if (s.botReplies < MIN_BOT_REPLIES) return;
4009 - if (s.idleTimer) clearTimeout(s.idleTimer);
4010 - s.idleTimer = setTimeout(function() { showPrompt(botId); }, IDLE_MS);
4011 - }
4012 -
4013 - function onUserMessage(botId) {
4014 - var s = getState(botId);
4015 - if (s.idleTimer) { clearTimeout(s.idleTimer); s.idleTimer = null; }
4016 - }
4017 -
4018 - function botIdFromChatBox(el) {
4019 - var id = el && el.id ? el.id : '';
4020 - return id.indexOf('chat-box-') === 0 ? id.substring('chat-box-'.length) : 'default';
4021 - }
4022 -
4023 - function setupObserver(chatBox) {
4024 - var botId = botIdFromChatBox(chatBox);
4025 - try {
4026 - var observer = new MutationObserver(function(mutations) {
4027 - mutations.forEach(function(m) {
4028 - for (var i = 0; i < m.addedNodes.length; i++) {
4029 - var node = m.addedNodes[i];
4030 - if (!node || node.nodeType !== 1) continue;
4031 - var $n = $(node);
4032 - if ($n.hasClass('mxchat-rating-bot-bubble') || $n.hasClass('mxchat-rating-prompt') || $n.hasClass('mxchat-rating-feedback') || $n.hasClass('mxchat-rating-saved')) continue;
4033 - if ($n.hasClass('bot-message')) onBotReply(botId); // count at insert time — streaming providers append with .temporary-message first, then remove later (childList observer can't see attr changes)
4034 - else if ($n.hasClass('user-message')) onUserMessage(botId);
4035 - }
4036 - });
4037 - });
4038 - observer.observe(chatBox, { childList: true });
4039 - } catch (e) { /* noop */ }
4040 - }
4041 -
4042 - $('.chat-box').each(function() { setupObserver(this); });
4043 -
4044 - $(document).on('click', '.mxchat-rating-btn', function(e) {
4045 - e.preventDefault();
4046 - var $btn = $(this);
4047 - var $prompt = $btn.closest('.mxchat-rating-prompt');
4048 - var $wrap = $btn.closest('.mxchat-rating-bot-bubble');
4049 - var botId = $prompt.data('bot-id') || 'default';
4050 - var rating = parseInt($btn.attr('data-rating'), 10);
4051 - if (rating !== 1 && rating !== -1) return;
4052 - submitRating(botId, rating, '');
4053 - ($wrap.length ? $wrap : $prompt).replaceWith(buildFeedbackHtml(botId, rating));
4054 - scrollChatBoxToBottom(getChatBoxByBotId(botId));
4055 - });
4056 -
4057 - $(document).on('click', '.mxchat-rating-dismiss', function(e) {
4058 - e.preventDefault();
4059 - var $prompt = $(this).closest('.mxchat-rating-prompt');
4060 - var $wrap = $(this).closest('.mxchat-rating-bot-bubble');
4061 - var botId = $prompt.data('bot-id') || 'default';
4062 - var s = getState(botId);
4063 - s.dismissed = true;
4064 - markRated(getSessionId(botId));
4065 - ($wrap.length ? $wrap : $prompt).remove();
4066 - });
4067 -
4068 - function closeFeedback($fb) {
4069 - var botId = $fb.data('bot-id') || 'default';
4070 - var $wrap = $fb.closest('.mxchat-rating-bot-bubble');
4071 - ($wrap.length ? $wrap : $fb).replaceWith(buildSavedHtml(botId));
4072 - scrollChatBoxToBottom(getChatBoxByBotId(botId));
4073 - }
4074 -
4075 - $(document).on('click', '.mxchat-rating-skip', function(e) {
4076 - e.preventDefault();
4077 - closeFeedback($(this).closest('.mxchat-rating-feedback'));
4078 - });
4079 -
4080 - $(document).on('click', '.mxchat-rating-submit', function(e) {
4081 - e.preventDefault();
4082 - var $fb = $(this).closest('.mxchat-rating-feedback');
4083 - var botId = $fb.data('bot-id') || 'default';
4084 - var rating = parseInt($fb.attr('data-rating'), 10);
4085 - if (rating !== 1 && rating !== -1) { closeFeedback($fb); return; }
4086 - var text = String($fb.find('.mxchat-rating-feedback-input').val() || '').trim();
4087 - if (text !== '') {
4088 - submitRating(botId, rating, text);
4089 - }
4090 - closeFeedback($fb);
4091 - });
4092 3464 });
4093 3465