Как предотвратить автоматическую прокрутку во время потоковой передачи, когда пользователь вручную прокручивает вверх?Jquery

Программирование на jquery
Ответить
Anonymous
 Как предотвратить автоматическую прокрутку во время потоковой передачи, когда пользователь вручную прокручивает вверх?

Сообщение Anonymous »

Я создаю интерфейс чата, в котором ответы ИИ передаются частями (аналогично ChatGPT). Текущая реализация автоматически прокручивается вниз по мере поступления каждого фрагмента, что работает хорошо. Однако, если пользователь пытается прокрутить вверх, чтобы прочитать предыдущий контент, пока поток все еще поступает, автоматическая прокрутка заставляет его вернуться вниз, что делает невозможным чтение предыдущих сообщений.
Что мне нужно, так это то, что когда пользователь вручную прокручивает вверх во время потоковой передачи, я хочу приостановить функцию автоматической прокрутки. Когда они прокрутят обратно вниз, автоматическая прокрутка должна возобновиться.
Вот мой текущий код управления потоковой передачей и прокруткой:

Код: Выделить всё

// Streaming function that processes chunks
function sendStreamingRequest(question, country, conversationHistory) {
console.log('🚀 Starting STREAMING request...');

// Create AbortController for this request
currentController = new AbortController();

// Add assistant message placeholder to chat
const chatMessages = document.getElementById('chat-messages');
const assistantMessageDiv = document.createElement('div');
assistantMessageDiv.className = 'message assistant';
assistantMessageDiv.innerHTML = `



`;
chatMessages.appendChild(assistantMessageDiv);

// Scroll to bottom initially
setTimeout(() => {
chatMessages.scrollTop = chatMessages.scrollHeight;
document.getElementById('chat-container').scrollTop = document.getElementById('chat-container').scrollHeight;
}, 100);

fetch(STREAMING_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': chat_ajax.nonce
},
body: JSON.stringify(requestBody),
signal: currentController.signal
})
.then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let accumulatedText = '';
let chunkCount = 0;

function readStream() {
return reader.read().then(({ done, value }) => {
if (done) {
console.log('Streaming complete!');
isStreaming = false;
$('#chatgpt-submit, #chatgpt-submit-bottom').removeClass('loading').prop('disabled', false);
return;
}

chunkCount++;
let chunk = decoder.decode(value);
accumulatedText += chunk;

// Update message content
const formattedText = formatResponseForDisplay(accumulatedText);
const sanitizedText = DOMPurify.sanitize(formattedText, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'span', 'button'],
ALLOWED_ATTR: ['href', 'target', 'class', 'data-language', 'title'],
ALLOW_DATA_ATTR: true
});
assistantMessageDiv.querySelector('.message-content').innerHTML = sanitizedText + '';

// PROBLEM: This forces scroll on every chunk
requestAnimationFrame(() => {
// Scroll the chat messages container to absolute bottom
chatMessages.scrollTop = chatMessages.scrollHeight;

// Scroll the main chat container to absolute bottom
const chatContainer = document.getElementById('chat-container');
chatContainer.scrollTop = chatContainer.scrollHeight;

// Scroll to the streaming cursor
const cursor = assistantMessageDiv.querySelector('.streaming-cursor');
if (cursor) {
cursor.scrollIntoView({ behavior: 'instant', block: 'nearest' });
}

// Force scroll the page to show the bottom input if it exists
const bottomInput = document.getElementById('input-container-bottom');
if (bottomInput && bottomInput.style.display !== 'none') {
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: 'instant'
});
}
});

return readStream();
});
}

return readStream();
})
.catch(error =>  {
console.error('Streaming error occurred:', error);
});
}
Структура HTML/CSS:

Код: Выделить всё













#chat-container {
width: 100%;
max-width: 600px;
margin-top: 30px;
overflow-y: auto;
flex: 1;
padding-bottom: 20px;
min-height: 0;
}

#chat-messages {
display: flex;
flex-direction: column;
gap: 16px;
}

.message {
padding: 12px 16px;
border-radius: 18px;
line-height: 1.4;
position: relative;
}

/* Mobile adjustments */
@media screen and (max-width: 600px) {
#chat-container {
flex: 1;
min-height: 0;
margin-bottom: 0;
padding-bottom: 10px;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
}

Проблема: блок requestAnimationFrame принудительно прокручивает каждый полученный фрагмент. Когда пользователь вручную прокручивает вверх, чтобы прочитать предыдущий контент, его немедленно перетаскивают обратно вниз.
Что я ищу:
  • Способ определить, когда пользователь вручную прокрутил нижнюю часть
  • Чистый способ приостановить автоматическую прокрутку, когда он это сделает
  • Возобновить автоматическая прокрутка, когда они возвращаются вниз.
  • Обработка сценариев прокрутки как на настольном компьютере, так и на мобильных устройствах.


Подробнее здесь: https://stackoverflow.com/questions/798 ... scrolls-up
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Jquery»