---
title: Chat log
description: 'A conversation that follows new messages while you are at the bottom, and counts them when you scroll up to read.'
order: 12
---

import { PrimitiveExample } from '@/components/primitive-example';
import { RecipeCode, RecipeExample, RecipePattern, RecipePatterns } from '@/components/recipe-patterns';

export const config = {
	dependencies: {
		components: [PrimitiveExample, RecipePatterns, RecipeCode, RecipeExample],
		scripts: ['./chat-log.script.ts', './chat-log.element.ts'],
		stylesheets: ['./chat-log.css'],
	},
};

# Chat log

<p class="docs-lede">
	A conversation that keeps the newest message in view while you are at the bottom, stops when you scroll up to read,
	and offers a button with the number of messages that arrived since.
</p>

## Goal

A chat, an agent log or a live feed: new messages and replies that stream in a word at a time stay in view while you read along, scrolling up to an older message holds the view still however much arrives, and one click takes you back to the latest and follows again. Loading older messages at the top does not move what you are reading.

## Primitives

- [StickToBottomController](/docs/controllers/stick-to-bottom) does all the scrolling. It pins the scroller to its end while following, watches the items with a `ResizeObserver` so a reply that grows as it streams stays in view, stops following when you scroll up, counts the items appended after that as `unseen`, and keeps the first visible message in place when older ones are prepended. It reports `{ following, atBottom, unseen }` through `onState`.

Left to the recipe: the messages, the streaming, the "Load earlier messages" button, and the jump button, which shows while the scroller is away from the bottom and reads the `unseen` count. Sending a message calls `scrollToBottom()`, because your own message should always be in view. The jump button calls `scrollToBottom({ behavior: 'smooth' })`, or the default instant scroll under `prefers-reduced-motion`, then moves focus to the conversation so it does not stay on a button that has just hidden.

## Example

Scroll up in the conversation, press Receive a message a few times and watch the count on the button; press it to jump back. Load earlier messages while you are scrolled up and the message you were reading stays put. Pick an authoring pattern below; they behave the same, and the one you pick is remembered on the other recipes.

<RecipePatterns patterns={['element', 'plain']}>

<RecipePattern id="element">

The same behavior as a `RadiantElement`. The markup is authored inside the element, which finds its parts with `@query`.

```ts title="chat-log.element.ts"
import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
import { createStickToBottomController } from '@ecopages/radiant-ui/controllers';
import { EARLIER, EARLIER_PAGE, INCOMING, WORD_DELAY, type ChatMessage } from './chat-log.data';

const jumpLabel = (unseen: number) =>
	unseen === 0 ? 'Jump to latest' : `${unseen} new ${unseen === 1 ? 'message' : 'messages'}`;

function messageItem({ from, text }: ChatMessage): HTMLLIElement {
	const item = document.createElement('li');
	item.dataset.from = from;
	item.textContent = text;
	return item;
}

@customElement('chat-log-element')
export class ChatLogElement extends RadiantElement {
	@query('[data-scroller]') private scroller!: HTMLElement;
	@query('[data-scroller] ol') private log!: HTMLOListElement;
	@query('[data-jump]') private jump!: HTMLButtonElement;
	@query('[data-earlier]') private earlierButton!: HTMLButtonElement;
	@query('form') private form!: HTMLFormElement;
	@query('input') private input!: HTMLInputElement;

	private readonly timers = new Set<ReturnType<typeof setTimeout>>();
	private earlier = EARLIER.length;
	private incoming = 0;

	private readonly stick = createStickToBottomController(this, {
		getScroller: () => this.scroller,
		getContent: () => this.log,
		onState: ({ atBottom, unseen }) => {
			this.jump.hidden = atBottom;
			this.jump.textContent = jumpLabel(unseen);
		},
	});

	constructor() {
		super();
		this.registerCleanupCallback(() => {
			this.timers.forEach(clearTimeout);
			this.timers.clear();
		});
	}

	@onEvent({ selector: '[data-earlier]', type: 'click' })
	loadEarlier(): void {
		const start = Math.max(0, this.earlier - EARLIER_PAGE);
		this.log.prepend(...EARLIER.slice(start, this.earlier).map(messageItem));
		this.earlier = start;
		this.earlierButton.disabled = start === 0;
	}

	@onEvent({ selector: '[data-receive]', type: 'click' })
	receive(): void {
		this.stream(INCOMING[this.incoming % INCOMING.length]!);
		this.incoming += 1;
	}

	@onEvent({ selector: 'form', type: 'submit' })
	send(event: SubmitEvent): void {
		event.preventDefault();
		this.log.append(messageItem({ from: 'me', text: this.input.value }));
		this.form.reset();
		this.stick.scrollToBottom();
	}

	@onEvent({ selector: '[data-jump]', type: 'click' })
	jumpToLatest(): void {
		const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
		this.stick.scrollToBottom({ behavior: reduce ? 'auto' : 'smooth' });
		this.scroller.focus({ preventScroll: true });
	}

	private stream(text: string): void {
		const item = messageItem({ from: 'them', text: '' });
		item.setAttribute('aria-busy', 'true');
		this.log.append(item);
		const words = text.split(' ');
		const step = (count: number) => {
			const timer = setTimeout(() => {
				this.timers.delete(timer);
				item.textContent = words.slice(0, count).join(' ');
				if (count < words.length) {
					step(count + 1);
				} else {
					item.removeAttribute('aria-busy');
				}
			}, WORD_DELAY);
			this.timers.add(timer);
		};
		step(1);
	}
}
```

```ts title="chat-log.data.ts"
/** One message in the conversation. */
export type ChatMessage = { from: 'me' | 'them'; text: string };

/** Older messages, oldest first, that "Load earlier messages" prepends in pages of `EARLIER_PAGE`. */
export const EARLIER: readonly ChatMessage[] = [
	{ from: 'them', text: 'Morning! The release branch is cut.' },
	{ from: 'me', text: 'Great. Anything blocking?' },
	{ from: 'them', text: 'One flaky test in the media suite.' },
	{ from: 'me', text: 'I will look at it after lunch.' },
	{ from: 'them', text: 'Thanks. The changelog is drafted too.' },
	{ from: 'me', text: 'Send it over when you can.' },
];

export const EARLIER_PAGE = 3;

/** The incoming messages, used in turn and streamed in a word at a time. */
export const INCOMING: readonly string[] = [
	'The build finished and every check is green.',
	'I tagged the release candidate, so the preview deploy is running now.',
	'Docs are live on the preview URL if you want to read them before we publish.',
	'Two people approved the version bump.',
];

/** How long each streamed word waits, in ms. */
export const WORD_DELAY = 40;
```

```html title="chat-log.html"
<chat-log-element>
	<button type="button" data-earlier>Load earlier messages</button>
	<div data-thread>
		<div data-scroller role="log" aria-label="Conversation" tabindex="0">
			<ol>
				<li data-from="them">Hi! I will post release updates here.</li>
				<li data-from="me">Thanks, keep them coming.</li>
				<li data-from="them">Tests are running on the release branch.</li>
				<li data-from="them">About ten minutes left.</li>
				<li data-from="me">I will keep an eye on it.</li>
				<li data-from="them">Halfway there.</li>
				<li data-from="me">Is the media suite still flaky?</li>
				<li data-from="them">It passed twice in a row, so maybe not.</li>
				<li data-from="them">Starting the docs build next.</li>
				<li data-from="me">Ping me when the preview is up.</li>
			</ol>
		</div>
		<button type="button" data-jump hidden>Jump to latest</button>
	</div>
	<form>
		<input name="message" aria-label="Message" placeholder="Write a message" autocomplete="off" required />
		<button type="submit">Send</button>
	</form>
	<button type="button" data-receive>Receive a message</button>
</chat-log-element>
```

```css title="chat-log.css"
:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 26rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) [data-thread] {
	position: relative;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) [data-scroller] {
	box-sizing: border-box;
	height: 16rem;
	overflow-y: auto;
	overscroll-behavior: contain;
	padding: 0.5rem;
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) [data-scroller]:focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) ol {
	display: flex;
	flex-direction: column;
	gap: 0.5rem;
	margin: 0;
	padding: 0;
	border: 0;
	background: transparent;
	list-style: none;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li {
	max-width: 80%;
	min-height: 1.25rem;
	padding: 0.5rem 0.75rem;
	border: 0;
	border-radius: var(--radius-container);
	background: var(--surface-container-high);
	font-size: 0.875rem;
	line-height: 1.25rem;
	overflow-wrap: anywhere;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li[data-from='them'] {
	align-self: flex-start;
	border-end-start-radius: 0.25rem;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li[data-from='me'] {
	align-self: flex-end;
	border-end-end-radius: 0.25rem;
	background: var(--primary);
	color: var(--on-primary);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li[aria-busy='true']::after {
	content: '';
	display: inline-block;
	width: 0.5em;
	height: 1em;
	margin-inline-start: 0.125em;
	vertical-align: text-bottom;
	background: currentColor;
	opacity: 0.5;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) form {
	display: grid;
	grid-template-columns: minmax(0, 1fr) auto;
	gap: var(--space-stack);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) input {
	box-sizing: border-box;
	width: 100%;
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
	color: inherit;
	font: inherit;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button {
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container);
	color: inherit;
	font: inherit;
	font-weight: 600;
	cursor: pointer;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button:disabled {
	cursor: default;
	opacity: 0.5;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button[type='submit'] {
	border-color: transparent;
	background: var(--primary);
	color: var(--on-primary);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button[data-jump] {
	position: absolute;
	inset-block-end: 0.75rem;
	inset-inline: 0;
	width: fit-content;
	margin-inline: auto;
	min-height: var(--size-control-sm);
	padding: 0.25rem 0.875rem;
	border-color: transparent;
	border-radius: 999px;
	background: var(--primary-container);
	color: var(--on-primary-container);
	font-size: 0.8125rem;
	box-shadow: var(--shadow-overlay);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button[data-jump][hidden] {
	display: none;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) :where(input, button):focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}
```

`createStickToBottomController(this, ...)` attaches when the element connects, which scrolls the conversation to its end, and destroys the controller when the element disconnects. The stream timers are cleared in a cleanup callback, so removing the element mid-reply stops it.

What the Radiant form removes: the `mount` function and its registration, the listeners to remove, and the cleanup to return and call.

</RecipePattern>

<RecipePattern id="plain">

A `mount` function wires the controller to one element and returns the cleanup that undoes it.

```ts title="chat-log.script.ts"
import { StickToBottomController } from '@ecopages/radiant-ui/controllers';
import { EARLIER, EARLIER_PAGE, INCOMING, WORD_DELAY, type ChatMessage } from './chat-log.data';

const jumpLabel = (unseen: number) =>
	unseen === 0 ? 'Jump to latest' : `${unseen} new ${unseen === 1 ? 'message' : 'messages'}`;

function messageItem({ from, text }: ChatMessage): HTMLLIElement {
	const item = document.createElement('li');
	item.dataset.from = from;
	item.textContent = text;
	return item;
}

export function mount(root: HTMLElement): () => void {
	const scroller = root.querySelector<HTMLElement>('[data-scroller]')!;
	const log = scroller.querySelector('ol')!;
	const jump = root.querySelector<HTMLButtonElement>('[data-jump]')!;
	const earlierButton = root.querySelector<HTMLButtonElement>('[data-earlier]')!;
	const receive = root.querySelector<HTMLButtonElement>('[data-receive]')!;
	const form = root.querySelector('form')!;
	const input = form.querySelector('input')!;
	const timers = new Set<ReturnType<typeof setTimeout>>();
	let earlier = EARLIER.length;
	let incoming = 0;

	const stick = new StickToBottomController({
		getScroller: () => scroller,
		getContent: () => log,
		onState: ({ atBottom, unseen }) => {
			jump.hidden = atBottom;
			jump.textContent = jumpLabel(unseen);
		},
	});
	stick.attach();

	const stream = (text: string) => {
		const item = messageItem({ from: 'them', text: '' });
		item.setAttribute('aria-busy', 'true');
		log.append(item);
		const words = text.split(' ');
		const step = (count: number) => {
			const timer = setTimeout(() => {
				timers.delete(timer);
				item.textContent = words.slice(0, count).join(' ');
				if (count < words.length) {
					step(count + 1);
				} else {
					item.removeAttribute('aria-busy');
				}
			}, WORD_DELAY);
			timers.add(timer);
		};
		step(1);
	};

	const loadEarlier = () => {
		const start = Math.max(0, earlier - EARLIER_PAGE);
		log.prepend(...EARLIER.slice(start, earlier).map(messageItem));
		earlier = start;
		earlierButton.disabled = earlier === 0;
	};
	const receiveMessage = () => {
		stream(INCOMING[incoming % INCOMING.length]!);
		incoming += 1;
	};
	const send = (event: SubmitEvent) => {
		event.preventDefault();
		log.append(messageItem({ from: 'me', text: input.value }));
		form.reset();
		stick.scrollToBottom();
	};
	const jumpToLatest = () => {
		const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
		stick.scrollToBottom({ behavior: reduce ? 'auto' : 'smooth' });
		scroller.focus({ preventScroll: true });
	};

	earlierButton.addEventListener('click', loadEarlier);
	receive.addEventListener('click', receiveMessage);
	form.addEventListener('submit', send);
	jump.addEventListener('click', jumpToLatest);

	return () => {
		earlierButton.removeEventListener('click', loadEarlier);
		receive.removeEventListener('click', receiveMessage);
		form.removeEventListener('submit', send);
		jump.removeEventListener('click', jumpToLatest);
		timers.forEach(clearTimeout);
		stick.destroy();
	};
}
```

```ts title="chat-log.data.ts"
/** One message in the conversation. */
export type ChatMessage = { from: 'me' | 'them'; text: string };

/** Older messages, oldest first, that "Load earlier messages" prepends in pages of `EARLIER_PAGE`. */
export const EARLIER: readonly ChatMessage[] = [
	{ from: 'them', text: 'Morning! The release branch is cut.' },
	{ from: 'me', text: 'Great. Anything blocking?' },
	{ from: 'them', text: 'One flaky test in the media suite.' },
	{ from: 'me', text: 'I will look at it after lunch.' },
	{ from: 'them', text: 'Thanks. The changelog is drafted too.' },
	{ from: 'me', text: 'Send it over when you can.' },
];

export const EARLIER_PAGE = 3;

/** The incoming messages, used in turn and streamed in a word at a time. */
export const INCOMING: readonly string[] = [
	'The build finished and every check is green.',
	'I tagged the release candidate, so the preview deploy is running now.',
	'Docs are live on the preview URL if you want to read them before we publish.',
	'Two people approved the version bump.',
];

/** How long each streamed word waits, in ms. */
export const WORD_DELAY = 40;
```

```html title="chat-log.html"
<div data-example="chat-log">
	<button type="button" data-earlier>Load earlier messages</button>
	<div data-thread>
		<div data-scroller role="log" aria-label="Conversation" tabindex="0">
			<ol>
				<li data-from="them">Hi! I will post release updates here.</li>
				<li data-from="me">Thanks, keep them coming.</li>
				<li data-from="them">Tests are running on the release branch.</li>
				<li data-from="them">About ten minutes left.</li>
				<li data-from="me">I will keep an eye on it.</li>
				<li data-from="them">Halfway there.</li>
				<li data-from="me">Is the media suite still flaky?</li>
				<li data-from="them">It passed twice in a row, so maybe not.</li>
				<li data-from="them">Starting the docs build next.</li>
				<li data-from="me">Ping me when the preview is up.</li>
			</ol>
		</div>
		<button type="button" data-jump hidden>Jump to latest</button>
	</div>
	<form>
		<input name="message" aria-label="Message" placeholder="Write a message" autocomplete="off" required />
		<button type="submit">Send</button>
	</form>
	<button type="button" data-receive>Receive a message</button>
</div>
```

```css title="chat-log.css"
:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 26rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) [data-thread] {
	position: relative;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) [data-scroller] {
	box-sizing: border-box;
	height: 16rem;
	overflow-y: auto;
	overscroll-behavior: contain;
	padding: 0.5rem;
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) [data-scroller]:focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) ol {
	display: flex;
	flex-direction: column;
	gap: 0.5rem;
	margin: 0;
	padding: 0;
	border: 0;
	background: transparent;
	list-style: none;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li {
	max-width: 80%;
	min-height: 1.25rem;
	padding: 0.5rem 0.75rem;
	border: 0;
	border-radius: var(--radius-container);
	background: var(--surface-container-high);
	font-size: 0.875rem;
	line-height: 1.25rem;
	overflow-wrap: anywhere;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li[data-from='them'] {
	align-self: flex-start;
	border-end-start-radius: 0.25rem;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li[data-from='me'] {
	align-self: flex-end;
	border-end-end-radius: 0.25rem;
	background: var(--primary);
	color: var(--on-primary);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) li[aria-busy='true']::after {
	content: '';
	display: inline-block;
	width: 0.5em;
	height: 1em;
	margin-inline-start: 0.125em;
	vertical-align: text-bottom;
	background: currentColor;
	opacity: 0.5;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) form {
	display: grid;
	grid-template-columns: minmax(0, 1fr) auto;
	gap: var(--space-stack);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) input {
	box-sizing: border-box;
	width: 100%;
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
	color: inherit;
	font: inherit;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button {
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container);
	color: inherit;
	font: inherit;
	font-weight: 600;
	cursor: pointer;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button:disabled {
	cursor: default;
	opacity: 0.5;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button[type='submit'] {
	border-color: transparent;
	background: var(--primary);
	color: var(--on-primary);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button[data-jump] {
	position: absolute;
	inset-block-end: 0.75rem;
	inset-inline: 0;
	width: fit-content;
	margin-inline: auto;
	min-height: var(--size-control-sm);
	padding: 0.25rem 0.875rem;
	border-color: transparent;
	border-radius: 999px;
	background: var(--primary-container);
	color: var(--on-primary-container);
	font-size: 0.8125rem;
	box-shadow: var(--shadow-overlay);
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) button[data-jump][hidden] {
	display: none;
}

:is(chat-log-element, div[data-example='chat-log']:not(.primitive-example)) :where(input, button):focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}
```

`mount` runs once for each example element on the page, and the function it returns undoes it; see [how the examples run](/docs/recipes/overview#how-the-examples-run).

</RecipePattern>

</RecipePatterns>

### Styles

The stylesheet is the `chat-log.css` tab in the files above. The scroller has a fixed height and `overflow-y: auto`, and the jump button sits over its bottom edge inside a positioned wrapper, so it never covers the field. The selectors are scoped to the example on this site; drop the scope in your own project.

## Accessibility

- The scroller has `role="log"`, which is a polite live region: a screen reader reads a new message without moving focus. It also has a name and `tabindex="0"`, so the keyboard can scroll it.
- A reply that streams in carries `aria-busy="true"` until its last word, so it is read once and not a word at a time.
- The controller writes no ARIA and moves no focus; the jump button is a real button and its label carries the count.
