feat(webui): scroll the chat transcript with MessageScroller

The transcript scrolled itself with a watcher that set
`scrollTop = scrollHeight` on every new message and streamed token, reaching
into ScrollArea's internals through `[data-slot="scroll-area-viewport"]` to find
the element that actually scrolls.

That follows the tail and nothing else. It has no notion of the reader having
scrolled away, so every streamed token yanked them back, and no way down for
someone who had deliberately scrolled up.

shadcn-vue's MessageScroller is the component for exactly this, so the surface
is composed from it instead: the provider owns autoscroll, the viewport reports
its edges, the content is a `role="log"` region, and the item carries the scroll
anchor. It buys the part the watcher could not express: once the reader
scrolls, autoscroll stops rather than fighting them, and a "Scroll to end"
button appears.

Verified in the browser: at the tail the root reports `data-scrollable="start"`
and the button is inert; after a wheel scroll it reports `data-scrollable="end"`,
autoscroll disengages, and the button is visible at opacity 1 and reachable. A
programmatic scrollTop does not count as intent, which is right: autoscroll
reclaims the tail unless a person asked for something else.
This commit is contained in:
sam committed 2026-09-20 20:08:00 +10:00
1 parent b9daa01b4b
commit db20d12f6d
11 files changed
+1434 -72

No files matched your search

+53 -58
View File
@@ -1,21 +1,31 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { computed } from "vue";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import ChatBubble from "./ChatBubble.vue";
import ChatEmptyState from "./ChatEmptyState.vue";
import { messages, sendMessage, streamingTurn, type ChatMessage } from "./state";
/**
* The conversation: the messages so far, the turn still arriving, and what the
* panel says before either exists. It scrolls itself to the newest line, so a
* streamed answer stays in view as it grows.
* panel says before either exists.
*
* The scroller follows the tail, and stops following the moment the reader
* scrolls up rather than yanking them back on every streamed token. That is
* what MessageScroller is for, so it is used rather than re-derived: an
* earlier version set scrollTop from a watcher, which has neither the
* "reader scrolled away" state nor a way back down.
*/
const emit = defineEmits<{ prompt: [text: string] }>();
const scroller = ref<{ $el: HTMLElement } | null>(null);
function parts(message: ChatMessage) {
const from = message.from ?? message.From ?? "";
// Anything this browser's composer did not send is Archie's answer.
@@ -27,61 +37,46 @@ function parts(message: ChatMessage) {
}
const bubbles = computed(() => messages.value.map(parts));
// ScrollArea renders its own scrollable element, so the way to follow the tail
// is to reach into the component for it. Asking the wrapper instead would set
// scrollTop on a box that does not scroll.
function viewport(): HTMLElement | null {
return scroller.value?.$el?.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]') ?? null;
}
// Auto scroll to the bottom on a new message or a streamed token. flush: 'post'
// measures after the new content is in the DOM; measuring before that reads the
// height the transcript is about to replace.
watch(
[messages, streamingTurn],
() => {
const el = viewport();
if (el) el.scrollTop = el.scrollHeight;
},
{ flush: "post" },
);
</script>
<template>
<ScrollArea ref="scroller" class="min-h-0 flex-1">
<div class="grid content-start gap-4 p-4">
<ChatEmptyState v-if="!bubbles.length && !streamingTurn" @prompt="emit('prompt', $event)" />
<MessageScrollerProvider auto-scroll default-scroll-position="end">
<MessageScroller class="min-h-0 flex-1">
<MessageScrollerViewport>
<MessageScrollerContent class="gap-4 p-4">
<ChatEmptyState v-if="!bubbles.length && !streamingTurn" @prompt="emit('prompt', $event)" />
<template v-else>
<ChatBubble
v-for="(bubble, i) in bubbles"
:key="i"
:text="bubble.text"
:tools="bubble.tools"
:assistant="bubble.assistant"
/>
<template v-else>
<MessageScrollerItem v-for="(bubble, i) in bubbles" :key="i" :message-id="`m${i}`">
<ChatBubble :text="bubble.text" :tools="bubble.tools" :assistant="bubble.assistant" />
</MessageScrollerItem>
<!-- The live turn is a bubble like any other, so what arrives is
rendered by the same rules as what was already there. -->
<ChatBubble
v-if="streamingTurn"
:text="streamingTurn.text || '…'"
:tools="streamingTurn.tools"
assistant
streaming
>
<Button
v-if="streamingTurn.isError && streamingTurn.turn"
variant="outline"
size="sm"
class="mt-2"
@click="sendMessage({ turn: streamingTurn.turn })"
>
Retry
</Button>
</ChatBubble>
</template>
</div>
</ScrollArea>
<!-- The live turn is a bubble like any other, so what arrives is
rendered by the same rules as what was already there. It is the
scroll anchor while it streams. -->
<MessageScrollerItem v-if="streamingTurn" message-id="streaming" scroll-anchor>
<ChatBubble
:text="streamingTurn.text || '…'"
:tools="streamingTurn.tools"
assistant
streaming
>
<Button
v-if="streamingTurn.isError && streamingTurn.turn"
variant="outline"
size="sm"
class="mt-2"
@click="sendMessage({ turn: streamingTurn.turn })"
>
Retry
</Button>
</ChatBubble>
</MessageScrollerItem>
</template>
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
</MessageScroller>
</MessageScrollerProvider>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { useMessageScrollerContext } from './useMessageScroller'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
const { autoscrolling, scrollableAttr } = useMessageScrollerContext()
</script>
<template>
<div
data-slot="message-scroller"
:data-scrollable="scrollableAttr"
:data-autoscrolling="autoscrolling ? '' : undefined"
:class="cn(
'group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden',
props.class,
)"
>
<slot />
</div>
</template>
@@ -0,0 +1,64 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type { MessageScrollerButtonDirection } from './useMessageScroller'
import type { ButtonVariants } from '@/components/ui/button'
import { ArrowDownIcon } from '@lucide/vue'
import { computed } from 'vue'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { useMessageScroller, useMessageScrollerScrollable } from './useMessageScroller'
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
direction?: MessageScrollerButtonDirection
behavior?: ScrollBehavior
variant?: ButtonVariants['variant']
size?: ButtonVariants['size']
}>(), {
direction: 'end',
behavior: 'smooth',
variant: 'secondary',
size: 'icon-sm',
})
const { scrollToEnd, scrollToStart } = useMessageScroller()
const scrollable = useMessageScrollerScrollable()
const active = computed(() =>
props.direction === 'start' ? scrollable.value.start : scrollable.value.end)
function onClick(event: MouseEvent) {
if (!active.value)
return
const target = event.currentTarget as HTMLElement | null
target?.blur()
if (event.defaultPrevented)
return
if (props.direction === 'start')
scrollToStart({ behavior: props.behavior })
else
scrollToEnd({ behavior: props.behavior })
}
</script>
<template>
<Button
data-slot="message-scroller-button"
:data-direction="direction"
:data-active="active ? 'true' : 'false'"
:variant="variant"
:size="size"
:inert="!active"
:tabindex="active ? undefined : -1"
:class="cn(
'absolute inset-s-1/2 -translate-x-1/2 border-border bg-background text-foreground transition-[translate,scale,opacity] duration-200 hover:bg-muted hover:text-foreground data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180',
props.class,
)"
@click="onClick"
>
<slot>
<ArrowDownIcon />
<span class="sr-only">{{ direction === "end" ? "Scroll to end" : "Scroll to start" }}</span>
</slot>
</Button>
</template>
@@ -0,0 +1,77 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { onBeforeUnmount, onMounted, useTemplateRef } from 'vue'
import { cn } from '@/lib/utils'
import { useMessageScrollerContext } from './useMessageScroller'
const props = defineProps<{
class?: HTMLAttributes['class']
spacerClass?: HTMLAttributes['class']
}>()
const {
handleContentChange,
handleResize,
setContentElement,
setSpacerElement,
} = useMessageScrollerContext()
const contentRef = useTemplateRef<HTMLElement>('content')
const spacerRef = useTemplateRef<HTMLElement>('spacer')
let mutationObserver: MutationObserver | null = null
let resizeObserver: ResizeObserver | null = null
let resizeFrame = 0
onMounted(() => {
const content = contentRef.value
if (!content)
return
setContentElement(content)
setSpacerElement(spacerRef.value ?? null)
handleContentChange()
if (typeof MutationObserver !== 'undefined') {
mutationObserver = new MutationObserver(() => handleContentChange())
mutationObserver.observe(content, { childList: true })
}
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(() => {
window.cancelAnimationFrame(resizeFrame)
resizeFrame = window.requestAnimationFrame(handleResize)
})
resizeObserver.observe(content)
}
})
onBeforeUnmount(() => {
window.cancelAnimationFrame(resizeFrame)
mutationObserver?.disconnect()
resizeObserver?.disconnect()
mutationObserver = null
resizeObserver = null
setContentElement(null)
setSpacerElement(null)
})
</script>
<template>
<div
ref="content"
data-slot="message-scroller-content"
role="log"
aria-relevant="additions"
:class="cn('flex h-max min-h-full flex-col gap-8', props.class)"
>
<slot />
<div
ref="spacer"
aria-hidden="true"
data-message-scroller-spacer=""
hidden
:class="props.spacerClass"
/>
</div>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from 'vue'
import { cn } from '@/lib/utils'
import { useMessageScrollerRegister } from './useMessageScroller'
const props = withDefaults(defineProps<{
messageId?: string
scrollAnchor?: boolean
class?: HTMLAttributes['class']
}>(), {
scrollAnchor: false,
})
const register = useMessageScrollerRegister()
const itemEl = useTemplateRef<HTMLElement>('item')
onMounted(() => {
if (props.messageId && itemEl.value)
register(props.messageId, itemEl.value, null)
})
watch(() => props.messageId, (messageId, previousMessageId) => {
const element = itemEl.value
if (!element)
return
if (previousMessageId)
register(previousMessageId, null, element)
if (messageId)
register(messageId, element, null)
})
onBeforeUnmount(() => {
if (props.messageId && itemEl.value)
register(props.messageId, null, itemEl.value)
})
</script>
<template>
<div
ref="item"
data-slot="message-scroller-item"
:data-message-id="messageId"
:data-scroll-anchor="scrollAnchor ? 'true' : 'false'"
:class="cn(
'min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]',
props.class,
)"
>
<slot />
</div>
</template>
@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { MessageScrollerProviderProps } from './useMessageScroller'
import { provideMessageScroller } from './useMessageScroller'
const props = defineProps<MessageScrollerProviderProps>()
provideMessageScroller(props)
</script>
<template>
<slot />
</template>
@@ -0,0 +1,76 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from 'vue'
import { cn } from '@/lib/utils'
import { SCROLL_KEYS, useMessageScrollerContext } from './useMessageScroller'
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
preserveScrollOnPrepend?: boolean
}>(), {
preserveScrollOnPrepend: true,
})
const {
autoscrolling,
handleResize,
scrollableAttr,
setPreserveScrollOnPrepend,
setViewportElement,
syncAfterScroll,
userScrollIntent,
} = useMessageScrollerContext()
const viewportEl = useTemplateRef<HTMLElement>('viewport')
watch(() => props.preserveScrollOnPrepend, setPreserveScrollOnPrepend, { immediate: true })
function onKeyDown(event: KeyboardEvent) {
if (SCROLL_KEYS.has(event.key))
userScrollIntent()
}
let resizeObserver: ResizeObserver | null = null
let resizeFrame = 0
onMounted(() => {
const viewport = viewportEl.value
setViewportElement(viewport)
if (!viewport || typeof ResizeObserver === 'undefined')
return
resizeObserver = new ResizeObserver(() => {
window.cancelAnimationFrame(resizeFrame)
resizeFrame = window.requestAnimationFrame(handleResize)
})
resizeObserver.observe(viewport)
})
onBeforeUnmount(() => {
window.cancelAnimationFrame(resizeFrame)
resizeObserver?.disconnect()
resizeObserver = null
setViewportElement(null)
})
</script>
<template>
<div
ref="viewport"
data-slot="message-scroller-viewport"
role="region"
aria-label="Messages"
:tabindex="0"
:data-scrollable="scrollableAttr"
:data-autoscrolling="autoscrolling ? '' : undefined"
:class="cn(
'size-full min-h-0 min-w-0 scroll-fade-b scrollbar-thin scrollbar-gutter-stable overflow-y-auto overscroll-contain contain-content data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent',
props.class,
)"
@scroll="syncAfterScroll()"
@wheel="userScrollIntent()"
@touchmove="userScrollIntent()"
@keydown="onKeyDown"
>
<slot />
</div>
</template>
@@ -0,0 +1,22 @@
export { default as MessageScroller } from './MessageScroller.vue'
export { default as MessageScrollerButton } from './MessageScrollerButton.vue'
export { default as MessageScrollerContent } from './MessageScrollerContent.vue'
export { default as MessageScrollerItem } from './MessageScrollerItem.vue'
export { default as MessageScrollerProvider } from './MessageScrollerProvider.vue'
export { default as MessageScrollerViewport } from './MessageScrollerViewport.vue'
export type {
MessageScrollerButtonDirection,
MessageScrollerDefaultScrollPosition,
MessageScrollerProviderProps,
MessageScrollerScrollable,
MessageScrollerScrollAlign,
MessageScrollerScrollOptions,
MessageScrollerVisibilityState,
} from './useMessageScroller'
export {
useMessageScroller,
useMessageScrollerScrollable,
useMessageScrollerVisibility,
} from './useMessageScroller'
File diff suppressed because it is too large. Load diff