feat: smart scroll — keep position when reading, badge for new messages
- Add pollMensajes() so wire:poll no longer force-scrolls to bottom - MutationObserver detects new DOM nodes: auto-scrolls only if user is already at the bottom (within 80px threshold) - Floating '↓ N mensaje nuevo' badge appears when new bot messages arrive while user is scrolled up; tap badge to jump to bottom - scroll-chat event (emitted on button clicks/sends) still forces scroll since the user just took an action Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
a5bac9cee7
commit
26953c9dd5
@@ -1225,7 +1225,7 @@ class PublicChat extends Component
|
|||||||
$this->mensajes = ChatMessage::where('conversation_id', $this->convId)
|
$this->mensajes = ChatMessage::where('conversation_id', $this->convId)
|
||||||
->orderBy('id')
|
->orderBy('id')
|
||||||
->get()
|
->get()
|
||||||
->map(fn($m) => [
|
->map(fn ($m) => [
|
||||||
'tipo' => $m->tipo,
|
'tipo' => $m->tipo,
|
||||||
'tipo_ui' => $m->tipo_ui ?? 'text',
|
'tipo_ui' => $m->tipo_ui ?? 'text',
|
||||||
'contenido' => $m->contenido,
|
'contenido' => $m->contenido,
|
||||||
@@ -1237,6 +1237,27 @@ class PublicChat extends Component
|
|||||||
$this->dispatchBrowserEvent('scroll-chat');
|
$this->dispatchBrowserEvent('scroll-chat');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Llamado por wire:poll — igual que cargarMensajes pero sin forzar scroll
|
||||||
|
public function pollMensajes(): void
|
||||||
|
{
|
||||||
|
if (! $this->convId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->mensajes = ChatMessage::where('conversation_id', $this->convId)
|
||||||
|
->orderBy('id')
|
||||||
|
->get()
|
||||||
|
->map(fn ($m) => [
|
||||||
|
'tipo' => $m->tipo,
|
||||||
|
'tipo_ui' => $m->tipo_ui ?? 'text',
|
||||||
|
'contenido' => $m->contenido,
|
||||||
|
'payload' => $m->payload ?? [],
|
||||||
|
'created_at' => $m->created_at->format('H:i'),
|
||||||
|
])
|
||||||
|
->toArray();
|
||||||
|
// No dispatches scroll-chat — el MutationObserver del JS maneja el badge
|
||||||
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────
|
||||||
// Helpers
|
// Helpers
|
||||||
// ─────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -104,30 +104,109 @@
|
|||||||
@livewireScripts
|
@livewireScripts
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
/* Ajusta altura del chat cuando aparece el teclado en móvil */
|
(function () {
|
||||||
function initViewportFix() {
|
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;
|
||||||
|
|
||||||
|
/* ── 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;
|
||||||
|
}
|
||||||
|
function scrollBottom(smooth) {
|
||||||
|
if (msgsEl) msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: smooth ? 'smooth' : 'instant' });
|
||||||
|
}
|
||||||
|
function updateBadge() {
|
||||||
|
const badge = document.getElementById('new-msg-badge');
|
||||||
|
const count = document.getElementById('new-msg-count');
|
||||||
|
if (!badge) return;
|
||||||
|
if (newMsgCount > 0 && !isAtBottom) {
|
||||||
|
if (count) count.textContent = newMsgCount;
|
||||||
|
badge.classList.remove('hidden');
|
||||||
|
} else {
|
||||||
|
badge.classList.add('hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Inicializar ── */
|
||||||
|
function init() {
|
||||||
|
msgsEl = document.getElementById('pub-messages');
|
||||||
|
if (!msgsEl) return;
|
||||||
|
|
||||||
|
lastMsgCount = countMsgs();
|
||||||
|
|
||||||
|
// Rastrear posición de scroll
|
||||||
|
msgsEl.addEventListener('scroll', () => {
|
||||||
|
isAtBottom = checkBottom();
|
||||||
|
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;
|
||||||
|
if (diff <= 0) return;
|
||||||
|
|
||||||
|
if (isAtBottom) {
|
||||||
|
scrollBottom(false);
|
||||||
|
} 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);
|
||||||
|
updateBadge();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── 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 ── */
|
||||||
|
function initViewport() {
|
||||||
const root = document.getElementById('chat-root');
|
const root = document.getElementById('chat-root');
|
||||||
if (!root || !window.visualViewport) return;
|
if (!root || !window.visualViewport) return;
|
||||||
|
|
||||||
const update = () => {
|
const update = () => {
|
||||||
const vh = window.visualViewport.height;
|
if (window.innerWidth < 640) root.style.height = window.visualViewport.height + 'px';
|
||||||
// En móvil: ajustamos #chat-root a la altura visual real
|
if (isAtBottom && msgsEl) scrollBottom(false);
|
||||||
if (window.innerWidth < 640) {
|
|
||||||
root.style.height = vh + 'px';
|
|
||||||
}
|
|
||||||
// Scroll al fondo siempre que cambie el viewport
|
|
||||||
const msgs = document.getElementById('pub-messages');
|
|
||||||
if (msgs) {
|
|
||||||
requestAnimationFrame(() => { msgs.scrollTop = msgs.scrollHeight; });
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
window.visualViewport.addEventListener('resize', update);
|
window.visualViewport.addEventListener('resize', update);
|
||||||
update();
|
update();
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', initViewportFix);
|
document.addEventListener('DOMContentLoaded', () => { init(); initViewport(); });
|
||||||
document.addEventListener('livewire:load', initViewportFix);
|
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); });
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -154,12 +154,8 @@
|
|||||||
|
|
||||||
{{-- ══ PASO 3: Interfaz de chat ══ --}}
|
{{-- ══ PASO 3: Interfaz de chat ══ --}}
|
||||||
@else
|
@else
|
||||||
<div class="flex-1 flex flex-col min-h-0 bg-[#0b141a]"
|
<div class="flex-1 flex flex-col min-h-0 bg-[#0b141a] relative"
|
||||||
x-data="{ uploading: false }"
|
x-data="{ uploading: false }">
|
||||||
x-on:scroll-chat.window="$nextTick(() => {
|
|
||||||
const el = document.getElementById('pub-messages');
|
|
||||||
if (el) el.scrollTop = el.scrollHeight;
|
|
||||||
})">
|
|
||||||
|
|
||||||
{{-- Header --}}
|
{{-- Header --}}
|
||||||
<div class="bg-[#202c33] shadow-md flex-shrink-0 safe-top safe-left safe-right">
|
<div class="bg-[#202c33] shadow-md flex-shrink-0 safe-top safe-left safe-right">
|
||||||
@@ -196,10 +192,22 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{{-- Badge: nuevos mensajes mientras se lee el historial --}}
|
||||||
|
<div id="new-msg-badge" class="hidden absolute left-0 right-0 flex justify-center z-20 pointer-events-none"
|
||||||
|
style="bottom:80px;">
|
||||||
|
<button id="new-msg-badge-btn"
|
||||||
|
class="pointer-events-auto flex items-center gap-2 bg-[#00a884] text-white text-xs font-semibold px-4 py-2 rounded-full shadow-xl active:bg-[#06cf9c] transition">
|
||||||
|
<svg class="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5 12 21m0 0-7.5-7.5M12 21V3" />
|
||||||
|
</svg>
|
||||||
|
<span id="new-msg-count">1</span> mensaje nuevo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{{-- Mensajes --}}
|
{{-- Mensajes --}}
|
||||||
<div class="flex-1 min-h-0 overflow-y-auto px-3 py-4 space-y-3 ios-scroll"
|
<div class="flex-1 min-h-0 overflow-y-auto px-3 py-4 space-y-3 ios-scroll"
|
||||||
id="pub-messages"
|
id="pub-messages"
|
||||||
wire:poll.3000ms="cargarMensajes"
|
wire:poll.3000ms="pollMensajes"
|
||||||
style="overscroll-behavior-y:contain;-webkit-overflow-scrolling:touch;">
|
style="overscroll-behavior-y:contain;-webkit-overflow-scrolling:touch;">
|
||||||
|
|
||||||
@forelse($mensajes as $msg)
|
@forelse($mensajes as $msg)
|
||||||
|
|||||||
Reference in New Issue
Block a user