# Message scroller

> A chat transcript that follows new messages, with sticky day pills, a New messages divider and a Jump to latest button with a count.

- Kind: ui · Category: Layout and media · Interactivity: script
- Install: `npx shadcn@latest add @haze/message-scroller`
- File: `src/components/haze/ui/message-scroller.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/message-scroller

## Use when
- A transcript or log grows while the reader may be reading older rows, such as an assistant chat
- Messages arrive live and the view should stay put if the reader scrolled up
- Older rows load above the current ones and the visible position must not jump

## Avoid when
- The whole page is the conversation and scrolls with the window. Use chat-thread.
- The content is a static long article with a table of contents. Use scroll-area or toc-progress.

## Alternatives
- [chat-thread](https://hazeui.com/ui/chat-thread.md)
- [scroll-area](https://hazeui.com/ui/scroll-area.md)
- [log-viewer](https://hazeui.com/ui/log-viewer.md)
- [scroll-progress](https://hazeui.com/ui/scroll-progress.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Id of the scroll region. The end marker is <id>-end and the jump link points at it. |
| height | `string` | "h-72" | no | Height utility class of the scroll region. |
| label | `string` | "Conversation" | no | Accessible name of the scroll region. |
| jumpLabel | `string` | "Jump to latest" | no | Text of the jump control. |
| newLabel | `string` | "new" | no | Word after the unread count on the jump button, such as "2 new". |
| unreadLabel | `string` | "New messages" | no | Text of the divider the script inserts above the first unread row when messages arrive while the reader is scrolled up. |
| announceLabel | `string` | "new messages below" | no | Screen-reader text after the count when messages arrive while the reader is scrolled up. |
| live | `boolean` | true | no | While the reader follows the end, announce new rows in the polite status line ("2 new messages"), debounced to about one second. |
| liveOne | `string` | "new message" | no | Singular text after the count in the following announcement. |
| liveMany | `string` | "new messages" | no | Plural text after the count in the following announcement. |
| class | `string` |  | no | Extra classes on the wrapper. |
| default slot | `rows` |  | no | One direct child per message. Append or prepend direct children to update the transcript. To group by day, wrap a day in a [data-ms-day] element whose first child is a [data-ms-date] pill; the pill sticks to the top while that day scrolls. A [data-ms-unread] child marks a New messages divider (a flex row with a span), and the script adds one itself for rows that arrive while scrolled up. |
| earlier slot | `node` |  | no | Optional control pinned to the top of the scroll, such as a Load earlier button. |

## Accessibility
- The scroller is a focusable region with a label, not role="log": a live log would read every row aloud, including the ones the reader scrolled up to see. Rows keep their own sender text.
- A polite status line announces only the count of new messages. Scrolled up: "2 new messages below". Following the end (live, on by default): "2 new messages", debounced to about one second so a burst is one line, never repeated when identical in a row, and cleared a few seconds later. Set live to false when the rows announce themselves.
- Without script the region scrolls normally and a Jump to latest link points at the end marker. With script the link becomes a button shown only when the reader is away from the end.
- When the jump button hides itself after use, focus moves to the scroll region so keyboard users keep their place.
- The date pills and the divider are plain text, readable in order. The divider fades out about two seconds after the reader is back at the end; the Jump to latest button rises in and its count reads "3 new".
- Smooth scrolling is replaced by an instant jump under prefers-reduced-motion.
- Key Tab: Focus the scroll region, then the Jump to latest control.
- Key Arrow Up / Down, Page Up / Down, Home / End: Scroll the focused region.
- Key Enter: On Jump to latest: scroll to the newest message and resume following.

## Agent prompts

### Install and use

Install the Haze UI component "Message scroller" with `npx shadcn@latest add @haze/message-scroller`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import MessageScroller from "@/components/haze/ui/message-scroller.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/message-scroller.md

### Customize with real content

Adapt the Haze message-scroller ui for our product. Replace the demo values of these props with our real content: id, height, label, jumpLabel, newLabel, unreadLabel, announceLabel, live, liveOne, liveMany, class, default slot, earlier slot. Keep the layout, the heading level rules and these accessibility details: The scroller is a focusable region with a label, not role="log": a live log would read every row aloud, including the ones the reader scrolled up to see. Rows keep their own sender text. A polite status line announces only the count of new messages. Scrolled up: "2 new messages below". Following the end (live, on by default): "2 new messages", debounced to about one second so a burst is one line, never repeated when identical in a row, and cleared a few seconds later. Set live to false when the rows announce themselves. Without script the region scrolls normally and a Jump to latest link points at the end marker. With script the link becomes a button shown only when the reader is away from the end. When the jump button hides itself after use, focus moves to the scroll region so keyboard users keep their place. The date pills and the divider are plain text, readable in order. The divider fades out about two seconds after the reader is back at the end; the Jump to latest button rises in and its count reads "3 new". Smooth scrolling is replaced by an instant jump under prefers-reduced-motion. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using message-scroller, check it fits: use it when a transcript or log grows while the reader may be reading older rows, such as an assistant chat; messages arrive live and the view should stay put if the reader scrolled up; older rows load above the current ones and the visible position must not jump. Avoid it when the whole page is the conversation and scrolls with the window. use chat-thread.; the content is a static long article with a table of contents. use scroll-area or toc-progress.. Alternatives: @haze/chat-thread, @haze/scroll-area, @haze/log-viewer, @haze/scroll-progress.

## Example requests that should lead here
- Add a fixed-height chat transcript that follows new messages and shows a Jump to latest button with an unread count
- Build a scrolling message list where loading older messages does not shift what I am reading

## Source

```astro
---
import { ArrowDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  /** Required. The scroll region gets this id; the end marker is `<id>-end`, the live status `<id>-status`. */
  id: string;
  /** Height utility class for the scroll region. The region scrolls inside it. */
  height?: string;
  /** Accessible name of the scroll region. */
  label?: string;
  /** Text of the jump control: "Jump to latest". */
  jumpLabel?: string;
  /** Word after the unread count on the jump button and in the announcement: "2 new". */
  newLabel?: string;
  /** Text of the divider the script inserts above the first unread message when rows arrive while the reader is scrolled up. */
  unreadLabel?: string;
  /** Screen-reader text when new messages arrive while the reader is scrolled up: "{count} {announceLabel}". */
  announceLabel?: string;
  /** While the reader follows the end, announce new rows politely ("2 new messages"), debounced to one line per burst. Default true. */
  live?: boolean;
  /** Singular text after the count of the following-the-end announcement. */
  liveOne?: string;
  /** Plural text after the count of the following-the-end announcement. */
  liveMany?: string;
  class?: string;
}

const {
  id,
  height = "h-72",
  label = "Conversation",
  jumpLabel = "Jump to latest",
  newLabel = "new",
  unreadLabel = "New messages",
  announceLabel = "new messages below",
  live = true,
  liveOne = "new message",
  liveMany = "new messages",
  class: className,
} = Astro.props;
const hasEarlier = Astro.slots.has("earlier");
// Optional structure inside the default slot, styled from here so callers only add data attributes:
// a [data-ms-day] group holds a [data-ms-date] pill that sticks while the day's rows scroll under it,
// and a [data-ms-unread] row is the "New messages" divider.
const dayClasses =
  "[&_[data-ms-day]]:flex [&_[data-ms-day]]:flex-col [&_[data-ms-day]]:gap-3 [&_[data-ms-date]]:sticky [&_[data-ms-date]]:top-2 [&_[data-ms-date]]:z-10 [&_[data-ms-date]]:w-fit [&_[data-ms-date]]:self-center [&_[data-ms-date]]:rounded-full [&_[data-ms-date]]:border [&_[data-ms-date]]:border-border [&_[data-ms-date]]:bg-popover [&_[data-ms-date]]:px-2.5 [&_[data-ms-date]]:text-[0.6875rem]/5 [&_[data-ms-date]]:font-medium [&_[data-ms-date]]:text-muted-foreground";
const unreadClasses =
  "[&_[data-ms-unread]]:flex [&_[data-ms-unread]]:items-center [&_[data-ms-unread]]:gap-3 [&_[data-ms-unread]]:text-[0.6875rem]/5 [&_[data-ms-unread]]:font-medium [&_[data-ms-unread]]:text-foreground [&_[data-ms-unread]]:before:h-px [&_[data-ms-unread]]:before:flex-1 [&_[data-ms-unread]]:before:bg-border [&_[data-ms-unread]]:before:content-[''] [&_[data-ms-unread]]:after:h-px [&_[data-ms-unread]]:after:flex-1 [&_[data-ms-unread]]:after:bg-border [&_[data-ms-unread]]:after:content-['']";
---

<div
  data-haze-message-scroller
  data-announce={announceLabel}
  data-new={newLabel}
  data-unread-label={unreadLabel}
  data-live={live ? "true" : "false"}
  data-live-one={liveOne}
  data-live-many={liveMany}
  class={cn("relative", className)}
>
  <div
    id={id}
    data-ms-viewport
    role="region"
    aria-label={label}
    tabindex="0"
    style="overflow-anchor: none"
    class={cn(
      "overflow-y-auto overscroll-contain rounded-xl border border-border bg-card focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
      height,
    )}
  >
    {hasEarlier && <div data-ms-earlier class="flex justify-center px-3 pt-3"><slot name="earlier" /></div>}
    <div data-ms-content class={cn("flex flex-col gap-3 p-3", dayClasses, unreadClasses)}>
      <slot />
    </div>
    <div id={`${id}-end`} data-ms-end tabindex="-1" class="h-px"></div>
  </div>
  <a
    href={`#${id}-end`}
    data-ms-jump
    class="absolute right-3 bottom-3 inline-flex h-8 items-center gap-1.5 rounded-full border border-border bg-popover px-3 text-[0.8125rem]/5 font-medium text-foreground shadow-float transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75 motion-safe:animate-rise motion-reduce:active:scale-100"
  >
    <ArrowDown aria-hidden="true" class="size-3.5" />
    <span>{jumpLabel}</span>
    <span data-ms-count hidden class="rounded-full bg-primary px-1.5 text-xs/4 font-medium text-primary-foreground tabular-nums"></span>
  </a>
  <p id={`${id}-status`} data-ms-status role="status" class="sr-only"></p>
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    root.setAttribute("data-enhanced", "");
    const viewport = root.querySelector<HTMLElement>("[data-ms-viewport]");
    const content = root.querySelector<HTMLElement>("[data-ms-content]");
    const jump = root.querySelector<HTMLElement>("[data-ms-jump]");
    const count = root.querySelector<HTMLElement>("[data-ms-count]");
    const status = root.querySelector<HTMLElement>("[data-ms-status]");
    if (!viewport || !content || !jump || !count || !status) return;
    const announce = root.getAttribute("data-announce") ?? "";
    const newWord = root.getAttribute("data-new") ?? "";
    const unreadLabel = root.getAttribute("data-unread-label") ?? "New messages";
    const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
    let dividerTimer = 0;
    const live = root.getAttribute("data-live") !== "false";
    const liveOne = root.getAttribute("data-live-one") ?? "new message";
    const liveMany = root.getAttribute("data-live-many") ?? "new messages";
    const NEAR = 48;
    let awayShown = false;
    let pending = 0;
    let lastLive = "";
    let liveTimer = 0;
    let clearTimer = 0;
    let following = true;
    let gliding = false;
    let unread = 0;
    let lastHeight = viewport.scrollHeight;

    const distance = () => viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
    const toBottom = () => { viewport.scrollTop = viewport.scrollHeight; };
    const setStatus = (text: string) => { if (status.textContent !== text) status.textContent = text; };
    const render = () => {
      const away = !following;
      jump.hidden = !away;
      count.hidden = unread === 0;
      const label = unread + " " + newWord;
      if (count.textContent !== label) count.textContent = label;
      if (away) {
        awayShown = true;
        pending = 0;
        window.clearTimeout(liveTimer);
        window.clearTimeout(clearTimer);
        lastLive = "";
        setStatus(unread > 0 ? unread + " " + announce : "");
      } else if (awayShown) {
        awayShown = false;
        setStatus("");
      }
    };
    // While following the end: one debounced polite line for a burst of new rows.
    const announceLive = (added: number) => {
      if (!live) return;
      pending += added;
      window.clearTimeout(liveTimer);
      liveTimer = window.setTimeout(() => {
        const text = pending + " " + (pending === 1 ? liveOne : liveMany);
        pending = 0;
        if (text === lastLive) return;
        lastLive = text;
        setStatus(text);
        // Empty the line afterwards so the same text can be announced again later.
        window.clearTimeout(clearTimer);
        clearTimer = window.setTimeout(() => { lastLive = ""; if (!awayShown) setStatus(""); }, 4000);
      }, 1000);
    };

    // The unread divider stays while the reader catches up, then fades once they have been at the end for a moment.
    const retireDividers = () => {
      window.clearTimeout(dividerTimer);
      dividerTimer = window.setTimeout(() => {
        if (!following) return;
        content.querySelectorAll<HTMLElement>(":scope > [data-ms-unread], :scope > [data-ms-day] > [data-ms-unread]").forEach((divider) => {
          if (reducedMotion.matches) { divider.remove(); return; }
          divider.classList.add("opacity-0", "transition-opacity", "duration-200", "ease-snappy");
          window.setTimeout(() => divider.remove(), 220);
        });
      }, 2000);
    };
    const insertDivider = (before: Element) => {
      // A divider left from earlier is stale: move it to the first row the reader has not seen.
      const existing = content.querySelector<HTMLElement>("[data-ms-unread]");
      if (existing) {
        if (existing.nextElementSibling !== before) { existing.classList.remove("opacity-0"); before.before(existing); }
        return;
      }
      const divider = document.createElement("div");
      divider.setAttribute("data-ms-unread", "");
      const text = document.createElement("span");
      text.textContent = unreadLabel;
      divider.append(text);
      before.before(divider);
    };

    viewport.addEventListener("scroll", () => {
      const near = distance() <= NEAR;
      if (gliding) {
        if (near) gliding = false;
        else return;
      }
      following = near;
      if (near) { unread = 0; retireDividers(); } else window.clearTimeout(dividerTimer);
      render();
      lastHeight = viewport.scrollHeight;
    }, { passive: true });
    // Reader input cancels a smooth jump in progress.
    for (const type of ["wheel", "touchstart", "keydown"]) {
      viewport.addEventListener(type, () => { gliding = false; }, { passive: true });
    }

    const mutations = new MutationObserver((records) => {
      let added = 0;
      let prepended = false;
      let firstNew: Element | undefined;
      for (const record of records) {
        for (const node of record.addedNodes) {
          if (node.nodeType !== 1 || (node as Element).hasAttribute("data-ms-unread")) continue;
          added++;
          firstNew ??= node as Element;
          if (record.nextSibling) prepended = true;
        }
      }
      if (!added) return;
      if (following) {
        toBottom();
        announceLive(added);
      } else if (prepended) {
        // Rows added above the reader: keep what they are looking at where it is.
        viewport.scrollTop += viewport.scrollHeight - lastHeight;
      } else {
        if (unread === 0 && firstNew) insertDivider(firstNew);
        unread += added;
        render();
      }
      lastHeight = viewport.scrollHeight;
    });
    mutations.observe(content, { childList: true });

    // Rows that grow in place (streamed text, images) keep following too.
    if ("ResizeObserver" in window) {
      new ResizeObserver(() => {
        if (following) toBottom();
        lastHeight = viewport.scrollHeight;
      }).observe(content);
    }

    jump.addEventListener("click", (event) => {
      event.preventDefault();
      const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
      following = true;
      gliding = !reduce;
      unread = 0;
      retireDividers();
      viewport.scrollTo({ top: viewport.scrollHeight, behavior: reduce ? "auto" : "smooth" });
      // The button hides itself; keep keyboard focus inside the component.
      viewport.focus({ preventScroll: true });
      render();
    });

    toBottom();
    lastHeight = viewport.scrollHeight;
    render();
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-message-scroller]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-message-scroller-listener")) {
    document.documentElement.setAttribute("data-haze-message-scroller-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
