fix: scroll chat — eliminar script duplicado, usar Livewire.hook oficial

- Eliminado script de scroll en public-chat.blade.php (conflictaba con el del layout)
- Reescrito script en chat-publico.blade.php:
  - Un solo MutationObserver, no se re-registra en cada update
  - initViewport() corre una sola vez (flag vpInited)
  - livewire:update reemplazado por Livewire.hook('message.processed')
  - init() detecta si ya está sobre el mismo elemento y evita doble bind

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro
2026-07-19 22:17:03 +00:00
co-authored by Claude Sonnet 4.6
parent 7cc696e04a
commit da9e5a0f68
2 changed files with 65 additions and 143 deletions
+65 -65
View File
@@ -105,107 +105,107 @@
<script> <script>
(function () { (function () {
const BOTTOM_THRESHOLD = 80; // px del fondo = "está al fondo" var msgsEl = null;
let isAtBottom = true; var isAtBottom = true;
let newMsgCount = 0; var newMsgCount = 0;
let lastMsgCount = 0; var lastCount = 0;
let msgsEl = null; var observer = null;
let observer = null; var vpInited = false;
/* ── Helpers ── */
function countMsgs() {
return msgsEl ? msgsEl.querySelectorAll(':scope > div').length : 0;
}
function checkBottom() { function checkBottom() {
if (!msgsEl) return true; if (!msgsEl) return true;
return (msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight) <= BOTTOM_THRESHOLD; return (msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight) <= 100;
} }
function scrollBottom(smooth) {
if (msgsEl) msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: smooth ? 'smooth' : 'instant' }); function scrollBottom() {
if (msgsEl) msgsEl.scrollTop = msgsEl.scrollHeight;
} }
function updateBadge() { function updateBadge() {
const badge = document.getElementById('new-msg-badge'); var badge = document.getElementById('new-msg-badge');
const count = document.getElementById('new-msg-count'); var count = document.getElementById('new-msg-count');
if (!badge) return; if (!badge) return;
if (newMsgCount > 0 && !isAtBottom) { if (newMsgCount > 0 && !isAtBottom) {
if (count) count.textContent = newMsgCount; if (count) count.textContent = newMsgCount;
badge.classList.remove('hidden'); badge.classList.remove('hidden');
badge.classList.add('flex');
} else { } else {
badge.classList.add('hidden'); badge.classList.add('hidden');
badge.classList.remove('flex');
} }
} }
/* ── Inicializar ── */ function countMsgs() {
return msgsEl ? msgsEl.children.length : 0;
}
function init() { function init() {
msgsEl = document.getElementById('pub-messages'); var el = document.getElementById('pub-messages');
if (!msgsEl) return; if (!el || el === msgsEl) return; // ya inicializado sobre el mismo elemento
lastMsgCount = countMsgs(); msgsEl = el;
lastCount = countMsgs();
// Rastrear posición de scroll msgsEl.addEventListener('scroll', function () {
msgsEl.addEventListener('scroll', () => {
isAtBottom = checkBottom(); isAtBottom = checkBottom();
if (isAtBottom) { if (isAtBottom) { newMsgCount = 0; updateBadge(); }
newMsgCount = 0;
updateBadge();
}
}, { passive: true }); }, { passive: true });
// Detectar mensajes nuevos sin hacer scroll invasivo
if (observer) observer.disconnect(); if (observer) observer.disconnect();
observer = new MutationObserver(() => { observer = new MutationObserver(function () {
const current = countMsgs(); var current = countMsgs();
const diff = current - lastMsgCount; var diff = current - lastCount;
lastMsgCount = current; lastCount = current;
if (diff <= 0) return; if (diff <= 0) return;
if (isAtBottom) { scrollBottom(); }
if (isAtBottom) { else { newMsgCount += diff; updateBadge(); }
scrollBottom(false);
} else {
newMsgCount += diff;
updateBadge();
}
}); });
observer.observe(msgsEl, { childList: true }); observer.observe(msgsEl, { childList: true });
// Badge: clic → bajar var btn = document.getElementById('new-msg-badge-btn');
const btn = document.getElementById('new-msg-badge-btn'); if (btn && !btn._bound) {
if (btn && !btn._scrollBound) { btn._bound = true;
btn._scrollBound = true; btn.addEventListener('click', function () {
btn.addEventListener('click', () => { isAtBottom = true; newMsgCount = 0;
newMsgCount = 0; msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: 'smooth' });
isAtBottom = true;
scrollBottom(true);
updateBadge(); updateBadge();
}); });
} }
scrollBottom();
} }
/* ── scroll-chat: emitido por PHP al enviar/click botón ── */ /* Ajustar altura al teclado virtual (una sola vez) */
window.addEventListener('scroll-chat', () => {
// El usuario acaba de interactuar → siempre bajar
isAtBottom = true;
newMsgCount = 0;
updateBadge();
scrollBottom(false);
});
/* ── Ajuste de altura cuando aparece el teclado en móvil ── */
function initViewport() { function initViewport() {
const root = document.getElementById('chat-root'); if (vpInited || !window.visualViewport) return;
if (!root || !window.visualViewport) return; vpInited = true;
const update = () => { var root = document.getElementById('chat-root');
if (window.innerWidth < 640) root.style.height = window.visualViewport.height + 'px'; if (!root) return;
if (isAtBottom && msgsEl) scrollBottom(false); function update() {
}; if (window.innerWidth < 640) {
root.style.height = window.visualViewport.height + 'px';
}
}
window.visualViewport.addEventListener('resize', update); window.visualViewport.addEventListener('resize', update);
update(); update();
} }
document.addEventListener('DOMContentLoaded', () => { init(); initViewport(); }); /* Bajar al fondo cuando el componente emite scroll-chat */
document.addEventListener('livewire:load', () => { init(); initViewport(); }); window.addEventListener('scroll-chat', function () {
// Re-init después de cada actualización de Livewire (por si el DOM se reinicia) isAtBottom = true; newMsgCount = 0; updateBadge(); scrollBottom();
document.addEventListener('livewire:update', () => { setTimeout(init, 50); }); });
document.addEventListener('DOMContentLoaded', function () { init(); initViewport(); });
/* livewire:load: Livewire terminó de arrancar — re-init por si el DOM cambió */
document.addEventListener('livewire:load', function () {
init();
initViewport();
/* Usar hook oficial para scroll después de cada update */
Livewire.hook('message.processed', function () {
if (isAtBottom) scrollBottom();
});
});
})(); })();
</script> </script>
</body> </body>
@@ -603,81 +603,3 @@
</div> </div>
<script>
(function () {
var container, badge, badgeBtn, countEl;
var userScrolledUp = false;
var newMsgCount = 0;
var debounceTimer = null;
function atBottom() {
return container.scrollHeight - container.scrollTop - container.clientHeight < 120;
}
function scrollToBottom() {
container.scrollTop = container.scrollHeight;
}
function showBadge(n) {
if (!badge || !countEl) return;
countEl.textContent = n;
badge.classList.remove('hidden');
badge.classList.add('flex');
}
function hideBadge() {
if (!badge) return;
badge.classList.add('hidden');
badge.classList.remove('flex');
newMsgCount = 0;
}
function onUpdate() {
if (!userScrolledUp) {
scrollToBottom();
} else {
newMsgCount++;
showBadge(newMsgCount);
}
}
function debouncedUpdate() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(onUpdate, 80);
}
document.addEventListener('livewire:load', function () {
container = document.getElementById('pub-messages');
badge = document.getElementById('new-msg-badge');
badgeBtn = document.getElementById('new-msg-badge-btn');
countEl = document.getElementById('new-msg-count');
if (!container) return;
// Scroll inicial
scrollToBottom();
// Click en badge baja al fondo
if (badgeBtn) {
badgeBtn.addEventListener('click', function () {
container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
hideBadge();
});
}
// Detectar scroll manual del usuario
container.addEventListener('scroll', function () {
if (atBottom()) {
userScrolledUp = false;
hideBadge();
} else {
userScrolledUp = true;
}
}, { passive: true });
// Hook oficial Livewire 2: se ejecuta después de cada update del componente
Livewire.hook('message.processed', function (message, component) {
debouncedUpdate();
});
});
})();
</script>