Aadi

Conversation Divider

AI chats 2

About

Dividers for a chat thread: day boundaries, where you left off, unread replies and events such as a model switch or a compaction.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Conversation Divider to your project and fits it to your theme.

Code

How Conversation Divider is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { forwardRef, createElement, type SVGAttributes, type ForwardRefExoticComponent, type RefAttributes } from "react"
import { cn } from "@/lib/utils"
import { ConversationDivider, ConversationDividerAction } from "@/components/ui/conversation-divider"

/** How many items show on the first frame, so a still cover already reads as a thread. */
const FIRST = 7

const reducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches

const STOP = Symbol("stop")

/**
 * Runs `script` in a loop with a `wait(ms)` that stops cleanly on unmount or once `active` turns
 * false. Reduced motion never starts it.
 */
function useLoop(
  script: (wait: (ms: number) => Promise<void>) => Promise<void>,
  active = true,
) {
  const ref = React.useRef(script)
  ref.current = script
  React.useEffect(() => {
    if (!active || reducedMotion()) return
    let alive = true
    const timers = new Set<number>()
    const wait = (ms: number) =>
      new Promise<void>((resolve, reject) => {
        const id = window.setTimeout(() => {
          timers.delete(id)
          if (alive) resolve()
          else reject(STOP)
        }, ms)
        timers.add(id)
      })
    ;(async () => {
      try {
        while (alive) await ref.current(wait)
      } catch (error) {
        if (error !== STOP) throw error
      }
    })()
    return () => {
      alive = false
      for (const id of timers) window.clearTimeout(id)
    }
  }, [active])
}

type Item =
  | { kind: "user" | "assistant"; id: string; text: string }
  | { kind: "date"; id: string; daysAgo: number }
  | { kind: "model" | "compact" | "resume"; id: string }
  | { kind: "unread"; id: string; count: number }

/** Two days of one thread about a slow import, told through the dividers between its messages. */
const SCRIPT: Item[] = [
  { kind: "date", id: "yesterday", daysAgo: 1 },
  { kind: "user", id: "u1", text: "Why does the import job time out on the 40k row CSV?" },
  {
    kind: "assistant",
    id: "a1",
    text: "Each row is inserted in its own transaction, so most of the 30 s budget goes on commits. Batching 500 rows per transaction should fix it.",
  },
  { kind: "resume", id: "resume" },
  { kind: "date", id: "today", daysAgo: 0 },
  { kind: "model", id: "model" },
  { kind: "user", id: "u2", text: "Batch the inserts and run the import again." },
  { kind: "compact", id: "compact" },
  { kind: "unread", id: "unread", count: 2 },
  { kind: "assistant", id: "a2", text: "Batched the inserts: 500 rows per transaction." },
  {
    kind: "assistant",
    id: "a3",
    text: "The import finished: 40,112 rows in 3.8 s. Nothing was skipped.",
  },
]

const STEP_MS = 900

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

/* -------------------------------------------------------------------------------------------------
 * Types and context
 * -----------------------------------------------------------------------------------------------*/

type MessageRole = "user" | "assistant" | "system"

type MessageLayout = "auto" | "bubble" | "flat" | "compact"

type MessageState = "streaming" | "done" | "edited" | "error" | "stopped" | "queued"

/* -------------------------------------------------------------------------------------------------
 * Message
 * -----------------------------------------------------------------------------------------------*/

interface MessageProps extends React.ComponentProps<"div"> {
  /** Who wrote it. Named `from` so the ARIA `role` attribute stays free. */
  from: MessageRole
  /**
   * `auto` gives users a subtle bubble and assistants a flat, document-style block. `compact`
   * is the dense log style for agent traces and side panels. Defaults to `auto`.
   */
  layout?: MessageLayout
  /** Lifecycle state. Defaults to `done`. */
  state?: MessageState
  /** Follows a message from the same author: tightens the gap and hides the avatar. */
  grouped?: boolean
  /** The newest message. Keeps its actions visible instead of revealing them on hover. */
  latest?: boolean
  /**
   * Enter animation. Defaults to animating only messages that arrive after the conversation
   * mounted, so restored history appears at once.
   */
  animate?: boolean
  /** Announce the text to screen readers when streaming finishes. Defaults to true. */
  announce?: boolean
}

/** Scroll behavior for imperative calls. `smooth` falls back to instant under reduced motion. */
type ChatcnScrollBehavior = "smooth" | "instant"

/* -------------------------------------------------------------------------------------------------
 * Context
 * -----------------------------------------------------------------------------------------------*/

interface ConversationContextValue {
  scrollRef: (element: HTMLElement | null) => void
  contentRef: (element: HTMLElement | null) => void
  spacerRef: (element: HTMLElement | null) => void
  /** Within the threshold of the bottom. */
  isAtBottom: boolean
  /** Following new content. */
  isSticky: boolean
  /** More than one viewport from the bottom. */
  isFar: boolean
  /** Messages that arrived below while the reader was scrolled up. */
  unread: number
  scrollToBottom: (options?: { behavior?: ChatcnScrollBehavior }) => void
  scrollToTurn: (element: HTMLElement, options?: { behavior?: ChatcnScrollBehavior }) => void
  /** Read text to screen readers through the conversation's polite live region. */
  announce: (text: string) => void
  /** False during the first render, so restored history does not animate in. */
  ready: boolean
}

const ConversationContext = React.createContext<ConversationContextValue | null>(null)

/** Scroll state and controls of the nearest `Conversation`. Returns null outside one. */
function useConversation() {
  return React.useContext(ConversationContext)
}

interface MessageContextValue {
  from: MessageRole
  /** Resolved layout: `auto` becomes `bubble` for users and `flat` for everyone else. */
  layout: Exclude<MessageLayout, "auto">
  state: MessageState
  /** The newest message: its actions stay visible. */
  latest: boolean
}

const MessageContext = React.createContext<MessageContextValue | null>(null)

/**
 * One turn in the conversation. Compose `MessageAvatar`, `MessageContent`, `MessageMeta`,
 * `MessageStatus` and `MessageActions` inside it.
 */
function Message({
  from,
  layout: layoutProp = "auto",
  state = "done",
  grouped = false,
  latest = false,
  animate,
  announce = true,
  className,
  children,
  ...props
}: MessageProps) {
  const conversation = useConversation()
  const layout: MessageContextValue["layout"] =
    layoutProp === "auto" ? (from === "user" ? "bubble" : "flat") : layoutProp
  const [enter] = React.useState(() => animate ?? conversation?.ready ?? false)
  const ref = React.useRef<HTMLDivElement>(null)

  // Screen readers hear the finished reply once, never token by token.
  const previous = React.useRef(state)
  React.useEffect(() => {
    const was = previous.current
    previous.current = state
    if (!announce || was !== "streaming" || state === "streaming") return
    const text = ref.current?.querySelector('[data-slot="message-content"]')?.textContent?.trim()
    if (text) conversation?.announce(text)
  }, [state, announce, conversation])

  const value = React.useMemo(
    () => ({ from, layout, state, latest }),
    [from, layout, state, latest],
  )

  return (
    <MessageContext.Provider value={value}>
      <div
        ref={ref}
        data-slot="message"
        data-role={from}
        data-layout={layout}
        data-message-state={state}
        data-grouped={grouped ? "" : undefined}
        data-latest={latest ? "" : undefined}
        aria-busy={state === "streaming" || undefined}
        className={cn(
          "group/message relative flex min-w-0 flex-col",
          layout === "compact" ? "gap-1" : "gap-2",
          layout === "bubble" ? "items-end" : "items-start",
          from === "system" && layout !== "compact" && "items-center text-center",
          grouped && (layout === "compact" ? "-mt-2" : "-mt-4"),
          // An avatar sits in the start gutter (the end gutter for bubbles).
          layout === "bubble"
            ? "has-[>[data-slot=message-avatar]]:pe-9"
            : "has-[>[data-slot=message-avatar]]:ps-9",
          enter &&
            (from === "user"
              ? "ease-(--chatcn-ease-out-soft) transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0 motion-reduce:starting:translate-y-0"
              : "ease-(--chatcn-ease-out-soft) transition-opacity duration-150 starting:opacity-0"),
          className,
        )}
        {...props}
      >
        {children}
      </div>
    </MessageContext.Provider>
  )
}

/** Role, layout and state of the nearest `Message`. Returns null outside one. */
function useMessage() {
  return React.useContext(MessageContext)
}

/* -------------------------------------------------------------------------------------------------
 * MessageContent
 * -----------------------------------------------------------------------------------------------*/

/**
 * The text of a message, capped at a 68ch measure. Plain text keeps its line breaks. Markdown
 * renderers drop in as children and inherit the 15/24 prose size.
 */
function MessageContent({ className, children, ...props }: React.ComponentProps<"div">) {
  const ctx = useMessage()
  const layout = ctx?.layout ?? "flat"
  const from = ctx?.from ?? "assistant"
  const state = ctx?.state ?? "done"
  const plain = typeof children === "string"

  return (
    <div
      data-slot="message-content"
      className={cn(
        "text-(color:--chatcn-fg) min-w-0 [overflow-wrap:anywhere]",
        // Bubbles fill their lines: pretty wrapping would leave a wide, half-empty bubble.
        layout !== "bubble" && "text-pretty",
        plain && "whitespace-pre-wrap",
        layout === "bubble" &&
          "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] rounded-(--chatcn-radius-xl) bg-(color:--chatcn-fill) max-w-[80%] px-4 py-2.5 text-start",
        layout === "flat" && "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] w-full max-w-[68ch]",
        layout === "compact" &&
          (from === "user"
            ? "text-[0.875rem]/[1.25rem] tracking-[-0.003em] rounded-(--chatcn-radius-md) bg-(color:--chatcn-fill) max-w-full px-3 py-1.5"
            : "text-[0.875rem]/[1.25rem] tracking-[-0.003em] w-full max-w-[68ch]"),
        from === "system" && "text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) max-w-[60ch]",
        // Queued turns are not sent yet: an outline instead of a fill says "pending".
        state === "queued" &&
          from === "user" &&
          "text-(color:--chatcn-fg-muted) border-(color:--chatcn-border-strong) border border-dashed bg-transparent",
        state === "error" && from === "user" && "text-(color:--chatcn-fg-muted)",
        className,
      )}
      {...props}
    >
      {children}
    </div>
  )
}

const DAY = 86_400_000

interface IconProps extends SVGAttributes<SVGSVGElement> {
  /** Width and height. Number means px. Default 24. */
  size?: number | string
  /** Stroke width in viewBox units (24 grid). Default 1.5. */
  strokeWidth?: number | string
  /** Keep the rendered stroke at `strokeWidth` px at any size. */
  absoluteStrokeWidth?: boolean
  /** Stroke color. Default currentColor. */
  color?: string
  /** Accessible name. Renders <title> and sets role="img"; without it the icon is aria-hidden. */
  title?: string
}

type Icon = ForwardRefExoticComponent<IconProps & RefAttributes<SVGSVGElement>>

/** Shape elements an icon may contain. */
type IconElement = "path" | "circle" | "rect" | "ellipse" | "line" | "polyline" | "polygon"

/** An icon's drawing: a flat list of [element, attributes] pairs, lucide compatible. */
type IconNode = ReadonlyArray<readonly [IconElement, Readonly<Record<string, string>>]>

const toPascal = (name: string): string =>
  name
    .split("-")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join("")

/**
 * Builds a React icon component from an icon node.
 * `name` is the kebab-case icon name, used for the class `chatcn-icon-<name>` and displayName.
 */
function createIcon(name: string, iconNode: IconNode): Icon {
  // biome-ignore lint/correctness/noComponentHookFactories: runs once per icon at module load
  const Component = forwardRef<SVGSVGElement, IconProps>(function ChatcnIcon(
    {
      size = 24,
      strokeWidth = 1.5,
      absoluteStrokeWidth = false,
      color = "currentColor",
      title,
      className,
      children,
      ...rest
    },
    ref,
  ) {
    const stroke = absoluteStrokeWidth
      ? (Number(strokeWidth) * 24) / Number.parseFloat(String(size))
      : strokeWidth
    const labelled = Boolean(title || rest["aria-label"] || rest["aria-labelledby"])
    return createElement(
      "svg",
      {
        ref,
        xmlns: "http://www.w3.org/2000/svg",
        width: size,
        height: size,
        viewBox: "0 0 24 24",
        fill: "none",
        stroke: color,
        strokeWidth: stroke,
        strokeLinecap: "round",
        strokeLinejoin: "round",
        "data-slot": "icon",
        className: className
          ? `chatcn-icon chatcn-icon-${name} ${className}`
          : `chatcn-icon chatcn-icon-${name}`,
        ...(labelled ? { role: "img" } : { "aria-hidden": true }),
        ...rest,
      },
      title ? createElement("title", null, title) : null,
      ...iconNode.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })),
      children,
    )
  })
  Component.displayName = `${toPascal(name)}Icon`
  return Component
}

const iconNode: IconNode = [
  ["path", {"d":"M6 3h12a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3"}],
  ["path", {"d":"m12.88 7.88 3.24 3.24a1.25 1.25 0 0 1 0 1.76l-3.24 3.24a1.25 1.25 0 0 1-1.76 0l-3.24-3.24a1.25 1.25 0 0 1 0-1.76l3.24-3.24a1.25 1.25 0 0 1 1.76 0"}],
]

const ModelIcon: Icon = /* @__PURE__ */ createIcon("model", iconNode)

const iconNode2: IconNode = [
  ["path", {"d":"M7 4.5H6a3 3 0 0 0-3 3v9a3 3 0 0 0 3 3h1"}],
  ["path", {"d":"M17 4.5h1a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-1"}],
  ["path", {"d":"M8 9h8"}],
  ["path", {"d":"M8 12h8"}],
  ["path", {"d":"M8 15h4.5"}],
]

const ContextWindowIcon: Icon = /* @__PURE__ */ createIcon("context-window", iconNode2)

function Row({ item, now }: { item: Item; now: number }) {
  switch (item.kind) {
    case "user":
    case "assistant":
      return (
        <Message from={item.kind}>
          <MessageContent>{item.text}</MessageContent>
        </Message>
      )
    case "date":
      return <ConversationDivider variant="date" date={now - item.daysAgo * DAY} now={now} />
    case "resume":
      return <ConversationDivider variant="resume" meta="18:40" />
    case "model":
      return (
        <ConversationDivider
          icon={<ModelIcon />}
          meta="09:12"
          action={<ConversationDividerAction>Undo</ConversationDividerAction>}
        >
          Model changed to Atlas Lite
        </ConversationDivider>
      )
    case "compact":
      return (
        <ConversationDivider
          icon={<ContextWindowIcon />}
          action={<ConversationDividerAction>View summary</ConversationDividerAction>}
        >
          Context compacted, 48k tokens saved
        </ConversationDivider>
      )
    case "unread":
      return <ConversationDivider variant="unread" count={item.count} />
  }
}

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * A thread that spans two days. Dividers land between the messages: the day boundary, where you
 * left off, a model switch, a compaction and the start of two unread replies. Loops.
 */
export default function ConversationDividerPreview() {
  const [now] = React.useState(() => Date.now())
  const [shown, setShown] = React.useState(FIRST)

  useLoop(async (wait) => {
    setShown(FIRST)
    await wait(900)
    for (let n = FIRST + 1; n <= SCRIPT.length; n += 1) {
      setShown(n)
      await wait(STEP_MS)
    }
    await wait(3200)
    setShown(3)
    await wait(900)
    for (let n = 4; n <= FIRST; n += 1) {
      setShown(n)
      await wait(700)
    }
  })

  return (
    <FitFrame minWidth="38rem">
      <div className="flex w-full flex-col items-center justify-center gap-3 p-4">
        <div className="bg-(color:--chatcn-bg) rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-border) h-[23rem] w-full max-w-2xl overflow-hidden">
          <div className="flex h-full flex-col justify-end overflow-hidden px-6 py-5 [mask-image:linear-gradient(to_bottom,transparent,black_3.5rem)]">
            <div className="flex flex-col gap-4">
              {SCRIPT.slice(0, shown).map((item) => (
                <div
                  key={item.id}
                  className="transition-opacity duration-300 ease-out starting:opacity-0"
                >
                  <Row item={item} now={now} />
                </div>
              ))}
            </div>
          </div>
        </div>
        <MoreOn slug="conversation-divider">Dividers for days, unread replies and thread events. On</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Stat Card

    Stat Card

    46
  • Audio Visualizer

    Audio Visualizer

    32
  • Dither Orb

    Dither Orb

    24
  • Voice Orb

    Voice Orb

    20
  • Weather Card

    Weather Card

    18
  • Waveform

    Waveform

    15
  • Ticker Card

    Ticker Card

    15
  • Message Feedback

    Message Feedback

    13

More in AI chats

View all
  • AI Actions

    AI Actions

    351
  • Aquarium Prompt

    Aquarium Prompt

    113
  • Agent Chat

    Agent Chat

    21
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    60
  • Research Report

    Research Report

    7
  • Tool Web Fetch

    Tool Web Fetch

    4
  • Color Picker

    Color Picker

    201
  • Suggestions

    Suggestions

    40

Explore more

Part of chatcn — browse the full library on 21st.dev.