Capítulo 6 de 20

Chapter 6: Chat

Core Idea

Chat, AI streams, logs, and reverse feeds append at the end but often prepend older history at the start. End anchoring preserves the visible message and follows new output only when the reader is already at the latest position.

Key Concepts

  • anchorTo: 'end': Enables end-oriented anchoring for prepend and growth behavior.
  • Stable message key: getItemKey must return the message ID, not its changing array index.
  • Prepend stability: Existing content can be prepended without moving the visible message.
  • followOnAppend: Follows newly appended items only when pinned near the end.
  • scrollEndThreshold: Defines how close to the end counts as pinned.
  • Streaming growth: Dynamic measurement keeps the bottom attached while the latest message grows.
  • scrollToEnd(): Starts the view at the latest item after mount.
  • Latest affordance: isAtEnd() can drive a "jump to latest" control.

Code Examples

const virtualizer = useVirtualizer({
  count: messages.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 72,
  getItemKey: (index) => messages[index]!.id,
  anchorTo: 'end',
  followOnAppend: true,
  scrollEndThreshold: 80,
  overscan: 6,
})
  • What it demonstrates: End anchoring, stable identity, selective append following, and chat-oriented overscan.

Key Takeaways

  1. Keep normal array order; do not invert with column-reverse.
  2. Prepend older messages normally and let stable keys preserve the anchor.
  3. Measure growing message rows.
  4. Do not pull a reader away from history when they are not near the end.

Connects To

  • Ch 017: The React example implements streaming, prepend, and latest controls.
  • Ch 005: Pretext can estimate text-heavy message heights.
  • Ch 007: End behavior is part of the Virtualizer API.