Components

Message Scroller

A scroll container for chat transcripts that anchors turns, follows streamed replies, restores prepended history, and jumps to messages.

Source code

Click to see the source code for this component on GitHub. Feel free to copy it and adjust it for your own use.

Installation

Add CSS

Add this to your main CSS file or import it in your project:

@keyframes ms-anim-fade {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes ms-anim-slide-up {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
@keyframes ms-anim-slide-side {
  from {
    opacity: 0;
    transform: translateX(18px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}
@keyframes ms-anim-pop {
  from {
    opacity: 0;
    transform: translateY(6px) scale(0.94);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
@keyframes ms-anim-spring-bounce {
  0% {
    opacity: 0;
    transform: translateY(12px) scale(0.96);
  }
  60% {
    opacity: 1;
    transform: translateY(-2px) scale(1.01);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
@keyframes ms-anim-blur-fade {
  from {
    opacity: 0;
    filter: blur(4px);
    transform: translateY(6px);
  }
  to {
    opacity: 1;
    filter: blur(0);
    transform: translateY(0);
  }
}
@keyframes ms-anim-scale-fade {
  from {
    opacity: 0;
    transform: scale(0.98);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.ms-anim-fade {
  animation: ms-anim-fade 0.26s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.ms-anim-slide-up {
  animation: ms-anim-slide-up 0.26s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.ms-anim-slide-side {
  animation: ms-anim-slide-side 0.3s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.ms-anim-pop {
  animation: ms-anim-pop 0.28s cubic-bezier(0.34, 1.56, 0.64, 1) both;
}
.ms-anim-spring-bounce {
  animation: ms-anim-spring-bounce 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) both;
}
.ms-anim-blur-fade {
  animation: ms-anim-blur-fade 0.3s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.ms-anim-scale-fade {
  animation: ms-anim-scale-fade 0.24s cubic-bezier(0.16, 1, 0.3, 1) both;
}

@media (prefers-reduced-motion: reduce) {
  [class*="ms-anim-"] {
    animation: none;
  }
}

MessageScroller

A great streaming chat scroller has to juggle a lot at once: pin to the live edge while a reply streams, but never fight a reader who scrolls up; anchor each new turn near the top with a peek of the previous exchange; preserve position when older history loads above; and expose commands to jump anywhere in the thread. MessageScroller owns those hard parts so your message list doesn't have to.

It does not own your messages, AI state, transport, or model — it is a headless scroll container you compose around your own rows.

Usage

New Chat

How can I help you today?
Morning, shadcn!
What are we working on today? Press send to start a new conversation
I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.
Demo is read only. Press send to send messages.

The provider must have a constrained height (or a height-bounded parent) so the viewport can scroll.

Anatomy

vue

Message Scroller Anatomy.vue

<template>
  <UiMessageScrollerProvider auto-scroll default-scroll-position="last-anchor">
    <UiMessageScroller>
      <UiMessageScrollerViewport>
        <UiMessageScrollerContent>
          <UiMessageScrollerItem
            v-for="message in messages"
            :key="message.id"
            :message-id="message.id"
            :scroll-anchor="message.role === 'user'"
          >
            <!-- Message / Bubble / Marker goes here -->
          </UiMessageScrollerItem>
        </UiMessageScrollerContent>
      </UiMessageScrollerViewport>
      <UiMessageScrollerButton direction="end" />
    </UiMessageScroller>
  </UiMessageScrollerProvider>
</template>

Examples

Anchoring Turns

A turn is the part of the conversation that starts a new exchange — usually the user's message and the assistant reply that follows. An anchor is the row the viewport should treat as the start of that turn. Mark that row with scrollAnchor. When a new anchor is appended, the viewport moves it near the top and keeps a peek of the previous item above it, so the new turn does not feel detached from its context.

<template>
  <UiMessageScrollerItem :message-id="message.id" :scroll-anchor="message.role === 'user'">
    <!-- ... -->
  </UiMessageScrollerItem>
</template>

Scroll anchors are not tied to message role. You can turn any row into an anchor: a user message, a system marker, a handoff event, or anything else that starts a meaningful turn.

Anchoring Turns

Choose which role settles near the top edge.
No anchored messages yet
Send the first message to see the selected role anchor.
Toggle the anchor role, then send messages to compare where turns settle.

Group Chat

In a group chat, the turn boundary is often the message that asks the model to respond, or a marker like "Marcus joined the chat". Typing indicators and history controls usually should not anchor. Because anchoring is role-independent, you can anchor a marker just as easily as a message.

Group Chat

A group chat with several participants and an assistant. The Marker is marked as a turn.
@mary, the astrophage line keeps matching Venus energy output. Can you check my math?
Mary (Agent)
Yes. Confirmed. The curve points to a microorganism harvesting stellar energy and breeding near carbon dioxide. If @rocky agrees, this is the clue we need.
ping @rocky

This will create a marker and make it the anchor

When a user joins, a marker is created. scrollAnchor on the marker marks it as the next turn

Keeping Context Visible

When a new turn starts, it should still feel like part of the same continuous thread. scrollPreviousItemPeek keeps a slice of the previous item visible above the anchor, so the reader keeps their context instead of feeling like the conversation restarted on a blank page.

Keeping Context Visible

New turns keep part of the previous reply in view.

I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.

That's the classic streaming scroll problem. Wrap your message list in `MessageScroller` and turn on `autoScroll` — the viewport pins to the bottom as tokens arrive, so users always see the latest text land in place.

The important part: it only auto-scrolls while the reader is already at the bottom. The moment they scroll up to read something earlier, auto-scroll backs off and their position is preserved. You get smooth streaming without fighting the user's intent.

Okay, but when someone sends a new message the view still feels jarring — like the whole conversation reloads from the top.
64px
Adjust the slider and send. Observe the previous message peek

Following the Live Edge

When the reader is at the live edge, autoScroll keeps streamed replies in view as they grow. Scrolling away from the live edge — by wheel, touch, keyboard, or dragging the scrollbar — releases the view, so new chunks arrive without moving the reader. autoScroll composes with turn anchoring: when a new turn anchors near the top, the view stays put while the reply streams into the room below it.

Streaming Messages

Auto-scroll follows the live edge of the conversation.
Ready to Stream
Press send to stream a scripted launch summary.
I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.
Streaming is simulated. `autoScroll` is enabled.

Opening Saved Threads

Reopening a saved thread at the absolute end often drops the reader in without enough context. A better default is "last-anchor": show the last meaningful turn, like the user's latest message, with the reply below it.

Opening Position

Choose where a saved transcript opens.

This is the first message the user sent in the conversation.

Workspace creation rose 8%, but first invite completion only rose 2%.

This is the last message the user sent in the conversation.

Start with the invite step. Teams are creating workspaces but waiting to add collaborators.

Recommended follow-up:

1. Compare invite drop-off by account size. 2. Check whether users who skip invites still return within 24 hours. 3. Review the empty-state copy on the first project screen. 4. Segment activation by template, since template users may not need invites right away.

If that pattern holds, the next experiment should make collaboration useful earlier instead of prompting for invites harder.

Toggle the defaultScrollPosition to see where the transcript starts when you open the thread

Loading Earlier Messages

Loading earlier messages should not move the conversation the reader is already looking at. When older rows are prepended above the current transcript, UiMessageScrollerViewport preserves the visible row so the reader stays in the same place while history loads above them. This is enabled by default through preserveScrollOnPrepend.

Load History

Prepended messages keep your place.

Only the export queue worker changed. The deploy moved large CSV jobs onto the shared retry policy, which made each failed attempt hold a worker slot longer than before.

The app deploy did not include checkout, pricing, or billing API changes.

Do we need to roll back?

Not yet. Queue depth is recovering after we reduced retry concurrency, and the oldest pending job is now under five minutes old.

Keep rollback ready if the queue starts climbing again, but the current trend points toward recovery.

Keep watching for customer-visible issues.

I will watch the queue and support tags for another 15 minutes. I am tracking export failures, delayed download requests, and any support thread that mentions missing reports.

If those stay quiet through the next batch window, we can close this as an internal degradation.

End of Conversation

Restore earlier messages while keeping your place.

Click Load History to load the entire conversation

Animating New Messages

A common chat pattern is to animate the user's message when it is sent, then let the assistant reply stream into a regular row below it. Keep messageId and scrollAnchor on the animated item and use transform and opacity for the entrance — avoid animating height, margin, or padding, which can fight the scroller's positioning.

Animation

Choose how user messages are animated when they are added to the conversation.
No Messages Yet
Click the button below to send the first message.
Select an animation then click send to see it in action.

Jumping to Messages

Search results, permalinks, outline items, and toolbar buttons often need to drive the transcript from outside the message list. Use useMessageScroller for those controls — the composable reads from UiMessageScrollerProvider, so it works in any component inside the provider.

<script setup lang="ts">
  const { scrollToMessage, scrollToEnd, scrollToStart } = useMessageScroller();
</script>

Commands

Drive the transcript from outside.

We're seeing activation dip after workspace creation. Can you help me find the likely step?

The sharpest drop is between creating the workspace and inviting the first teammate.

Workspace creation is still healthy, but the invite step is where users pause. That suggests the product is asking for collaboration before the user has enough confidence in the workspace.

What should I compare before we change the onboarding flow?

Compare three cohorts:

1. Users who choose a template before inviting teammates. 2. Users who start from a blank workspace. 3. Users who skip invites and return within 24 hours.

If template users invite faster, the fix is probably better first-run guidance rather than a louder invite prompt.

Can you turn that into an experiment?

Yes. Create a variant that shows a short checklist after workspace creation:

- Pick a template. - Add one project detail. - Invite a teammate when the workspace has context.

Measure first invite completion, 24-hour return rate, and whether teams create a second project.

What's the risk if we delay the invite prompt?

The main risk is reducing team creation for accounts that already know who they want to invite.

To protect that path, keep the invite action visible in the header and only change the primary empty-state guidance. That gives confident teams a direct route without forcing uncertain users through the invite step too early.

Use the controls to jump to any message in the conversation.

Tracking the Reader's Position

Use useMessageScrollerVisibility to track the reader's position — a table-of-contents or jump menu that highlights the current anchored turn. currentAnchorId answers "where am I" and stays set after that anchor scrolls above the viewport; visibleMessageIds answers "what is on screen", in document order.

Transcript Outline

Track the current anchored turn.

Review the incident handoff and tell me what to read first.

Start with the summary and the impact section. The regression affected the upload queue, but the recovery path completed for every queued job.

What was the customer impact?

Impact was limited to delayed processing.

No records were dropped, and the reconciliation worker confirmed each retry batch. Support saw confusion from two customers, but there were no checkout or billing errors.

What actions are open?

Keep the retry window enabled until the next deploy, then add a queue-depth alert as the long-term fix.

The alert should fire on sustained queue growth, not a single short spike.

Give me the follow-up checklist.

After that, compare the queue recovery graph with the deploy timeline so the handoff shows exactly when processing returned to baseline. That makes it easier for support and engineering to answer the same customer questions without re-reading the whole incident thread.

I would also add a short owner note beside each follow-up item. The checklist is small, but ownership keeps the retry-window decision, alert tuning, and support macro from drifting into separate follow-up conversations.

Keep the retry window enabled until the next deploy, then add a queue-depth alert as the long-term fix.

The alert should fire on sustained queue growth, not a single short spike.

Open the outline to jump between anchored turns as you read.

Reading Scroll State

Use useMessageScrollerScrollable when you need scroll state in JavaScript, such as a status indicator or a custom "jump to latest" control. It reports which edges the viewport can still scroll toward.

Scroll Status

Where the reader can scroll to based on current scroll position.

Review scroll checkpoint 1.

Checkpoint 2 is synced. The scrollable hook updates as the viewport moves.

When the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 3.

Checkpoint 4 is synced. The scrollable hook updates as the viewport moves.

When the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 5.

Checkpoint 6 is synced. The scrollable hook updates as the viewport moves.

When the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 7.

Checkpoint 8 is synced. The scrollable hook updates as the viewport moves.

When the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 9.

Checkpoint 10 is synced. The scrollable hook updates as the viewport moves.

When the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.

At the latest message, the footer should switch again and only point them back up.

Review scroll checkpoint 11.

Checkpoint 12 is synced. The scrollable hook updates as the viewport moves.

When the reader is at the first message, the footer should only point them down. Once they move into the middle of the transcript, it should explain that both directions are available.

At the latest message, the footer should switch again and only point them back up.

All messages fit in the viewport.
Scroll the transcript to see the footer update.

API Reference

All Message Scroller parts render a <div> by default, except MessageScrollerButton, which renders a Button.

MessageScrollerProvider

Owns the scroll state and behavior. Descendants read from it with useMessageScroller, useMessageScrollerScrollable, and useMessageScrollerVisibility.

PropTypeDefaultDescription
autoScrollbooleanfalseFollow the live edge while the reader is pinned to the bottom.
defaultScrollPosition"start" | "end" | "last-anchor""end"Opening position for the transcript.
scrollEdgeThresholdnumber8Distance in px from an edge before it is considered scrollable.
scrollPreviousItemPeeknumber64Amount in px of the previous turn kept visible when anchoring.
scrollMarginnumber0Extra offset in px applied when scrolling to an element.

MessageScroller

The scroll region's outer wrapper. Needs a constrained height (or a height-bounded parent) so its viewport can scroll.

PropTypeDefaultDescription
classHTMLAttributes["class"]-Additional classes to apply to the root element.

MessageScrollerViewport

The scrollable region. Renders as a role="region", aria-label="Messages", focusable (tabindex="0") native scroll container.

PropTypeDefaultDescription
preserveScrollOnPrependbooleantrueKeep the current view when messages are added above.
classHTMLAttributes["class"]-Additional classes to apply to the viewport.

MessageScrollerContent

Renders as role="log" with aria-relevant="additions" so assistive tech announces new rows.

PropTypeDefaultDescription
classHTMLAttributes["class"]-Additional classes to apply to the content element.
spacerClassHTMLAttributes["class"]-Additional classes to apply to the trailing spacer.

MessageScrollerItem

PropTypeDefaultDescription
messageIdstring-Stable id used for anchoring, visibility, and jumps.
scrollAnchorbooleanfalseMarks this row as the start of a turn.
classHTMLAttributes["class"]-Additional classes to apply to the item.

MessageScrollerButton

Exposes data-active for styling and becomes inert with tabindex="-1" when there is nothing to scroll toward.

PropTypeDefaultDescription
direction"start" | "end""end"Direction the button scrolls toward.
behaviorScrollBehavior"smooth"Scroll behavior for the jump.
variantButtonVariants["variant"]"secondary"The button variant.
sizeButtonVariants["size"]"icon-sm"The button size.
classHTMLAttributes["class"]-Additional classes to apply.

Composables

useMessageScroller()

const { scrollToMessage, scrollToEnd, scrollToStart } = useMessageScroller();
  • scrollToMessage(id, options?) — scroll to the item with the matching messageId. Returns true if handled (queued if the item is not mounted yet), false if the id is missing after rows have mounted.
  • scrollToEnd(options?) / scrollToStart(options?) — scroll to the live edge or the top.

useMessageScrollerVisibility()

const visibility = useMessageScrollerVisibility();
// visibility.value.currentAnchorId, visibility.value.visibleMessageIds

Tracking only runs while something subscribes, and rows need a messageId to participate.

useMessageScrollerScrollable()

const scrollable = useMessageScrollerScrollable();
// scrollable.value.start, scrollable.value.end

Reports which edges the viewport can still scroll toward. For styling the scroller itself, prefer the data-scrollable attribute.