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>
(function () {
const BOTTOM_THRESHOLD = 80; // px del fondo = "está al fondo"
let isAtBottom = true;
let newMsgCount = 0;
let lastMsgCount = 0;
let msgsEl = null;
let observer = null;
var msgsEl = null;
var isAtBottom = true;
var newMsgCount = 0;
var lastCount = 0;
var observer = null;
var vpInited = false;
/* ── Helpers ── */
function countMsgs() {
return msgsEl ? msgsEl.querySelectorAll(':scope > div').length : 0;
}
function checkBottom() {
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() {
const badge = document.getElementById('new-msg-badge');
const count = document.getElementById('new-msg-count');
var badge = document.getElementById('new-msg-badge');
var count = document.getElementById('new-msg-count');
if (!badge) return;
if (newMsgCount > 0 && !isAtBottom) {
if (count) count.textContent = newMsgCount;
badge.classList.remove('hidden');
badge.classList.add('flex');
} else {
badge.classList.add('hidden');
badge.classList.remove('flex');
}
}
/* ── Inicializar ── */
function countMsgs() {
return msgsEl ? msgsEl.children.length : 0;
}
function init() {
msgsEl = document.getElementById('pub-messages');
if (!msgsEl) return;
var el = document.getElementById('pub-messages');
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', () => {
msgsEl.addEventListener('scroll', function () {
isAtBottom = checkBottom();
if (isAtBottom) {
newMsgCount = 0;
updateBadge();
}
if (isAtBottom) { newMsgCount = 0; updateBadge(); }
}, { passive: true });
// Detectar mensajes nuevos sin hacer scroll invasivo
if (observer) observer.disconnect();
observer = new MutationObserver(() => {
const current = countMsgs();
const diff = current - lastMsgCount;
lastMsgCount = current;
observer = new MutationObserver(function () {
var current = countMsgs();
var diff = current - lastCount;
lastCount = current;
if (diff <= 0) return;
if (isAtBottom) {
scrollBottom(false);
} else {
newMsgCount += diff;
updateBadge();
}
if (isAtBottom) { scrollBottom(); }
else { newMsgCount += diff; updateBadge(); }
});
observer.observe(msgsEl, { childList: true });
// Badge: clic → bajar
const btn = document.getElementById('new-msg-badge-btn');
if (btn && !btn._scrollBound) {
btn._scrollBound = true;
btn.addEventListener('click', () => {
newMsgCount = 0;
isAtBottom = true;
scrollBottom(true);
var btn = document.getElementById('new-msg-badge-btn');
if (btn && !btn._bound) {
btn._bound = true;
btn.addEventListener('click', function () {
isAtBottom = true; newMsgCount = 0;
msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: 'smooth' });
updateBadge();
});
}
scrollBottom();
}
/* ── scroll-chat: emitido por PHP al enviar/click botón ── */
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 ── */
/* Ajustar altura al teclado virtual (una sola vez) */
function initViewport() {
const root = document.getElementById('chat-root');
if (!root || !window.visualViewport) return;
const update = () => {
if (window.innerWidth < 640) root.style.height = window.visualViewport.height + 'px';
if (isAtBottom && msgsEl) scrollBottom(false);
};
if (vpInited || !window.visualViewport) return;
vpInited = true;
var root = document.getElementById('chat-root');
if (!root) return;
function update() {
if (window.innerWidth < 640) {
root.style.height = window.visualViewport.height + 'px';
}
}
window.visualViewport.addEventListener('resize', update);
update();
}
document.addEventListener('DOMContentLoaded', () => { init(); initViewport(); });
document.addEventListener('livewire:load', () => { init(); initViewport(); });
// Re-init después de cada actualización de Livewire (por si el DOM se reinicia)
document.addEventListener('livewire:update', () => { setTimeout(init, 50); });
/* Bajar al fondo cuando el componente emite scroll-chat */
window.addEventListener('scroll-chat', function () {
isAtBottom = true; newMsgCount = 0; updateBadge(); scrollBottom();
});
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>
</body>
@@ -603,81 +603,3 @@
</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>