Getting started

Actions

Forms

Layout

Navigation

Overlays

Feedback

Data display

Controllers

Helpers

Recipes

Chat log

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.

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 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.

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

  1. Hi! I will post release updates here.
  2. Thanks, keep them coming.
  3. Tests are running on the release branch.
  4. About ten minutes left.
  5. I will keep an eye on it.
  6. Halfway there.
  7. Is the media suite still flaky?
  8. It passed twice in a row, so maybe not.
  9. Starting the docs build next.
  10. Ping me when the preview is up.
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);
	}
}

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.

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.