.task
[ ] El span de time al cargar mas mensajes suele repetirse
/*
inicialmente los mnesajes cargan correctamente y encuentra y sabe cual es el primer mensaje de un hilo para agregar la información del usuario, pero el problema sucede al hacer scroll, como los mensajes tienen que invertirse para cargan en el orden correcto supongo, sucede esto:
hilo de mensajes del mismo usuario:
mensaje 1 - se supone que este es el primer mensaje donde se tiene que colocar la información del usuario
mensaje 2
mensaje 3
mensaje 4
mensaje 5 - pero en realidad se suele colocar aqui
listaMensajes.addEventListener('scroll', async e => {
if (e.target.scrollTop === 0 && puedeDesplazar) {
puedeDesplazar = false;
setTimeout(() => (puedeDesplazar = true), 2000);
currentPage++;
const data = await enviarAjax('obtenerChatColab', {conversacion_id, page: currentPage});
if (!data?.success) {
return console.error('Error al obtener más mensajes.');
}
let mensajes = data.data.mensajes;
// Reverse the messages to process from oldest to newest
mensajes.reverse();
const remitentesUnicos = [...new Set(mensajes.map(m => m.remitente))];
const userInfos = await obtenerInfoUsuarios(remitentesUnicos);
let fechaAnterior = null;
// Get the sender of the first message currently displayed
const primerMensajeMostrado = listaMensajes.querySelector('.messageBlock');
let prevEmisor = null;
if (primerMensajeMostrado) {
const primerMensajeElem = primerMensajeMostrado.querySelector('.mensajeText');
if (primerMensajeElem) {
prevEmisor = primerMensajeElem.getAttribute('data-emisor') || null;
}
}
// Process messages from oldest to newest
for (let i = 0; i < mensajes.length; i++) {
const mensaje = mensajes[i];
// Determine if this message starts a new thread
const esNuevoHilo = mensaje.remitente !== prevEmisor;
const userInfo = userInfos.get(mensaje.remitente);
agregarMensajeAlChat(
mensaje.mensaje,
mensaje.clase,
mensaje.fecha,
listaMensajes,
fechaAnterior,
true, // insertAtTop = true
mensaje.adjunto,
null,
mensaje.remitente,
esNuevoHilo,
userInfo,
'Colab'
);
fechaAnterior = new Date(mensaje.fecha);
// Update prevEmisor after processing the message
prevEmisor = mensaje.remitente;
}
// Adjust the scroll to maintain position after loading
if (listaMensajes.firstChild) {
listaMensajes.firstChild.scrollIntoView();
}
}
});
function crearElemento(tag, clase, atributos = {}) {
const elem = document.createElement(tag);
if (Array.isArray(clase)) clase.forEach(c => elem.classList.add(c));
else if (clase) elem.classList.add(clase);
code
for (const [key, value] of Object.entries(atributos)) {
if (key === 'textContent') {
elem.textContent = value;
} else if (value !== undefined) {
elem.setAttribute(key, value);
}
}
return elem;
}
The issue you're experiencing stems from the way messages are processed and inserted when loading more messages upon scrolling. Specifically, when you reverse the messages and process them from oldest to newest, the logic for determining the esNuevoHilo (whether a message starts a new thread) becomes flawed because of incorrect prevEmisor (previous sender) tracking. This results in the first message of a thread not being correctly identified, and thus, the user information gets placed on the wrong message.
Here's how to fix the problem:
Remove the reversal of messages.
Since messages from the server are already ordered from oldest to newest, reversing them isn't necessary and leads to incorrect processing order when inserting at the top.
diff
- mensajes.reverse();
Process messages from last to first (newest to oldest).
Modify your loop to iterate from the last message to the first. By doing this and inserting each message at the top, you maintain the correct chronological order in the DOM.
diff
- for (let i = 0; i < mensajes.length; i++) {
+ for (let i = mensajes.length - 1; i >= 0; i--) {
const mensaje = mensajes[i];
//... rest of your code
Initialize prevEmisor to null before the loop.
This ensures that the comparison starts correctly without unintended carry-over from prior iterations or the initial displayed messages.
diff
- let prevEmisor = null;
Update prevEmisor after processing each message.
This allows you to correctly determine if the current message starts a new thread based solely on the messages being processed.
javascript
for (let i = mensajes.length - 1; i >= 0; i--) {
const mensaje = mensajes[i];
// Determine if this message starts a new thread
const esNuevoHilo = mensaje.remitente !== prevEmisor;
const userInfo = userInfos.get(mensaje.remitente);
agregarMensajeAlChat(
mensaje.mensaje,
mensaje.clase,
mensaje.fecha,
listaMensajes,
fechaAnterior,
true, // insertAtTop = true
mensaje.adjunto,
null,
mensaje.remitente,
esNuevoHilo,
userInfo,
'Colab'
);
fechaAnterior = new Date(mensaje.fecha);
// Update prevEmisor after processing the message
prevEmisor = mensaje.remitente;
}
Adjust the logic in agregarMensajeAlChat if necessary.
Ensure that the function correctly handles the isFirstMessageOfThread flag and adds user information accordingly.
Explanation:
By processing the messages from last to first and inserting each at the top, you maintain the correct chronological order in the message list. The prevEmisor variable is updated after each message is processed, ensuring that esNuevoHilo accurately reflects whether the current message is the start of a new thread based on the sender.
This approach also avoids the complexities and potential errors introduced when trying to compare the sender of the newly loaded messages with the first message currently displayed. Instead, each batch of messages loaded upon scrolling is processed in isolation, which simplifies the logic and reduces the chances of incorrect threading.
Updated manejarScrollColab function:
javascript
async function manejarScrollColab(conversacion, contenedor = null) {
const listaMensajes = (contenedor || document).querySelector('.listaMensajes');
let puedeDesplazar = true,
currentPage = 1,
conversacion_id = conversacion;
listaMensajes.addEventListener('scroll', async e => {
if (e.target.scrollTop === 0 && puedeDesplazar) {
puedeDesplazar = false;
setTimeout(() => (puedeDesplazar = true), 2000);
currentPage++;
const data = await enviarAjax('obtenerChatColab', {conversacion_id, page: currentPage});
if (!data?.success) {
return console.error('Error al obtener más mensajes.');
}
let mensajes = data.data.mensajes;
const remitentesUnicos = [...new Set(mensajes.map(m => m.remitente))];
const userInfos = await obtenerInfoUsuarios(remitentesUnicos);
let fechaAnterior = null;
let prevEmisor = null;
// Process messages from last to first
for (let i = mensajes.length - 1; i >= 0; i--) {
const mensaje = mensajes[i];
// Determine if this message starts a new thread
const esNuevoHilo = mensaje.remitente !== prevEmisor;
const userInfo = userInfos.get(mensaje.remitente);
agregarMensajeAlChat(
mensaje.mensaje,
mensaje.clase,
mensaje.fecha,
listaMensajes,
fechaAnterior,
true, // insertAtTop = true
mensaje.adjunto,
null,
mensaje.remitente,
esNuevoHilo,
userInfo,
'Colab'
);
fechaAnterior = new Date(mensaje.fecha);
// Update prevEmisor after processing the message
prevEmisor = mensaje.remitente;
}
// Adjust the scroll to maintain position after loading
if (listaMensajes.firstChild) {
listaMensajes.firstChild.scrollIntoView();
}
}
});
}
By implementing these changes, the time spans should no longer repeat, and the user information will be correctly associated with the first message of each thread, even after loading more messages on scroll.