Day 2:Streaming Chat UI — Smart Auto-Scroll & Client Cancellation
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Day 2: Streaming Chat UI — Smart Auto-Scroll & Client Cancellation
1. First-Principles: The "Forced Scroll" UX Disaster
In naive streaming chat implementations, developers attach an unconditional scroll trigger on every received token:
// NAIVE ANTI-PATTERN - ANNOYS USERS!
function onToken(delta) {
messageDiv.innerText += delta;
chatContainer.scrollTop = chatContainer.scrollHeight; // FORCED JUMP!
}
If the assistant is generating a 600-word response and the user scrolls up to review a previous terminal command, the next token arriving violently rips the scroll position back to the bottom, making it impossible to read or copy earlier messages.
2. The Smart Auto-Scroll Algorithm
A production chat client records whether the user was already at the bottom before appending the new token:
Formula:
3. Client Cancellation with AbortController
When a user clicks "Stop Generating", the client must not simply hide the UI; it must terminate the underlying network connection:
const abortController = new AbortController();
fetch('/v1/chat/stream', {
method: 'POST',
body: JSON.stringify(payload),
signal: abortController.signal
});
// When user clicks "Stop Generating":
stopButton.onclick = () => {
abortController.abort(); // Disconnects TCP socket immediately
};
This triggers ASGI http.disconnect on the FastAPI server, halting upstream token generation and saving money.
In Simple English: Smart Auto-Scroll & Hit-Stop Cancellation (AbortController)
Look at the scroll formula (scrollHeight - scrollTop - clientHeight) <= 40:
scrollHeight= full height of the chat conversation.scrollTop + clientHeight= bottom edge of what is visible on screen right now!- Why Smart Auto-Scroll Matters: If the user scrolls UP to copy a line of code while the AI is still typing below, don't force-snap them back down! Auto-scroll ONLY when they are already within
40pxof the bottom! AbortControllerStop Button: Callscontroller.abort()to slam shut the network socket immediately, triggering backend generator cancellation and saving tokens!