Aadi

Preview Toolbar

AI chats

About

A floating toolbar over a live preview to select elements, comment and draw, with shortcuts and a sliding active state.

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

Code

How Preview Toolbar 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 { cn } from "@/lib/utils"
import { PreviewSelection, PreviewSelectionRect, PreviewTool, PreviewToolbar } from "@/components/ui/preview-toolbar"

interface GhostState {
  x: number
  y: number
  shown: boolean
  down: boolean
}

/**
 * A pointer that walks a demo through its clicks, so a preview shows what each control does.
 * `stage` is the positioned box the pointer moves in; targets are found inside it. Sizes come
 * from layout boxes, so a scaled FitFrame never throws the aim off.
 */
function useGhost(stage: React.RefObject<HTMLElement | null>) {
  const [ghost, setGhost] = React.useState<GhostState>({ x: 0, y: 0, shown: false, down: false })

  const find = React.useCallback(
    (target: string | HTMLElement) =>
      typeof target === "string"
        ? stage.current?.querySelector<HTMLElement>(target) ?? null
        : target,
    [stage],
  )

  const moveTo = React.useCallback(
    (target: string | HTMLElement, dx = 0.5, dy = 0.6) => {
      const root = stage.current
      const el = find(target)
      if (!root || !el) return null
      const rr = root.getBoundingClientRect()
      const scale = root.offsetWidth ? rr.width / root.offsetWidth : 1
      const er = el.getBoundingClientRect()
      const x = (er.left - rr.left + er.width * dx) / scale
      const y = (er.top - rr.top + er.height * dy) / scale
      // A hidden pointer fades in a short way off its first target instead of flying in from
      // wherever it was last.
      setGhost((g) => (g.shown ? { x, y, shown: true, down: false } : { x: x + 70, y: y + 46, shown: false, down: false }))
      window.requestAnimationFrame(() =>
        window.requestAnimationFrame(() => setGhost({ x, y, shown: true, down: false })),
      )
      return el
    },
    [stage, find],
  )

  const press = React.useCallback((down: boolean) => setGhost((g) => ({ ...g, down })), [])
  const hide = React.useCallback(() => setGhost((g) => ({ ...g, shown: false, down: false })), [])

  return { ghost, moveTo, press, hide, find }
}

type Target = { el: HTMLElement; label: string; rect: PreviewSelectionRect }

type Pin = { x: number; y: number; text: string; typing: boolean }

/** An element's box inside the preview in layout pixels, so a scaled frame never skews it. */
function rectOf(el: HTMLElement, root: HTMLElement): PreviewSelectionRect {
  const a = el.getBoundingClientRect()
  const b = root.getBoundingClientRect()
  const s = root.offsetWidth ? b.width / root.offsetWidth : 1
  return { x: (a.left - b.left) / s, y: (a.top - b.top) / s, width: a.width / s, height: a.height / s }
}

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])
}

const NOTE = "Make the pay button full width"

/** A loose loop around a box, as someone circling it with a pen would draw it. */
function circlePoints(r: PreviewSelectionRect, steps = 36): [number, number][] {
  const cx = r.x + r.width / 2
  const cy = r.y + r.height / 2
  const rx = r.width / 2 + 12
  const ry = r.height / 2 + 10
  return Array.from({ length: steps + 4 }, (_, i) => {
    const t = -Math.PI * 0.75 + (i / steps) * Math.PI * 2
    const wobble = 1 + Math.sin(i * 1.7) * 0.03
    return [cx + Math.cos(t) * rx * wobble, cy + Math.sin(t) * ry * wobble] as [number, number]
  })
}

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>
  )
}

/** The app being previewed: the payment step of a checkout the agent is building. */
function PreviewApp() {
  return (
    <div className="flex h-full flex-col">
      <div data-inspect="header" className="border-(color:--chatcn-border) flex h-11 items-center justify-between border-b px-5">
        <span className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] font-semibold">Fieldnote</span>
        <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle)">
          Cart / Shipping / <span className="text-(color:--chatcn-fg)">Payment</span>
        </span>
      </div>
      <div className="grid flex-1 place-items-center px-6 pb-14">
        <div data-inspect="Card" className="bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) rounded-(--chatcn-radius-lg) flex w-full max-w-xs flex-col gap-3.5 p-5">
          <div className="flex flex-col gap-1">
            <h3 data-inspect="h3" className="text-[1rem]/[1.5rem] tracking-[-0.01em] font-semibold">
              Payment details
            </h3>
            <p data-inspect="p" className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted)">
              Your card is charged when the order ships.
            </p>
          </div>
          <div data-inspect="Input" className="rounded-(--chatcn-radius-md) shadow-(--chatcn-shadow-xs) flex h-9 items-center justify-between px-3">
            <span className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-subtle) font-mono">4242 4242 4242 4242</span>
            <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle)">12 / 28</span>
          </div>
          <div
            data-inspect="Button"
            className="bg-(color:--chatcn-fg) text-(color:--chatcn-bg) rounded-(--chatcn-radius-md) text-[0.875rem]/[1.25rem] tracking-[-0.003em] flex h-9 w-28 items-center justify-center font-medium"
          >
            Pay $48.00
          </div>
        </div>
      </div>
    </div>
  )
}

/** The pointer itself. Put it last inside the stage, which must be `relative`. */
function Ghost({ ghost }: { ghost: GhostState }) {
  return (
    <div
      aria-hidden
      className="pointer-events-none absolute top-0 left-0 z-20"
      style={{
        transform: `translate(${ghost.x}px, ${ghost.y}px)`,
        opacity: ghost.shown ? 1 : 0,
        // Hidden, it jumps; shown, it glides.
        transition: ghost.shown
          ? "transform 620ms cubic-bezier(0.4, 0, 0.2, 1), opacity 220ms ease-out"
          : "opacity 220ms ease-out",
      }}
    >
      <svg
        width="18"
        height="20"
        viewBox="0 0 18 20"
        className="drop-shadow-[0_1px_2px_rgb(0_0_0/0.25)]"
        style={{
          transform: ghost.down ? "scale(0.86)" : "scale(1)",
          transformOrigin: "2px 2px",
          transition: "transform 120ms ease-out",
        }}
      >
        <path
          d="M2 1.5 L2 16 L5.9 12.4 L8.6 18.3 L11.2 17.1 L8.6 11.3 L13.9 11.1 Z"
          className="fill-[oklch(0.2_0_0)] stroke-white dark:fill-white dark:stroke-[oklch(0.2_0_0)]"
          strokeWidth="1.3"
          strokeLinejoin="round"
        />
      </svg>
    </div>
  )
}

/** 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 live preview of a checkout an agent is building, with the tools to point at what to change.
 * The pointer selects the pay button, pins a comment on it and circles it with the pen, then
 * clears the marks. Loops. Click anything to stop the tour and use the tools yourself.
 */
export default function PreviewToolbarPreview() {
  const rootRef = React.useRef<HTMLDivElement>(null)
  const g = useGhost(rootRef)
  const scripted = React.useRef(false)
  const [touring, setTouring] = React.useState(true)
  const [tool, setTool] = React.useState<PreviewTool | null>("select")
  const [hover, setHover] = React.useState<Target | null>(null)
  const [selected, setSelected] = React.useState<Target | null>(null)
  const [stroke, setStroke] = React.useState<[number, number][]>([])
  const [pin, setPin] = React.useState<Pin | null>(null)

  const target = (name: string): Target | null => {
    const root = rootRef.current
    const el = root?.querySelector<HTMLElement>(`[data-inspect="${name}"]`)
    return root && el ? { el, label: name, rect: rectOf(el, root) } : null
  }

  const pickTool = async (t: PreviewTool, wait: (ms: number) => Promise<void>) => {
    const button = rootRef.current?.querySelector<HTMLElement>(
      `[data-slot="preview-toolbar"] button[aria-keyshortcuts="${{ select: "S", edit: "T", draw: "D", comment: "C" }[t]}"]`,
    )
    if (!button) return
    g.moveTo(button)
    await wait(650)
    g.press(true)
    await wait(110)
    scripted.current = true
    button.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }))
    scripted.current = false
    g.press(false)
    await wait(300)
  }

  useLoop(async (wait) => {
    setTool("select")
    setSelected(null)
    setHover(null)
    setStroke([])
    setPin(null)
    await wait(1000)
    // Select: skim the card, then pick the button.
    for (const name of ["Card", "Input", "Button"]) {
      const t = target(name)
      if (!t) return
      g.moveTo(t.el, 0.5, 0.55)
      await wait(650)
      setHover(t)
      await wait(350)
    }
    g.press(true)
    await wait(110)
    g.press(false)
    setHover(null)
    setSelected(target("Button"))
    await wait(1500)

    // Comment: pin a note on the button.
    await pickTool("comment", wait)
    setSelected(null)
    const button = target("Button")
    if (!button) return
    // The pin lands just right of the button, clear of the loop the pen draws around it.
    const at = { x: button.rect.x + button.rect.width + 36, y: button.rect.y + button.rect.height / 2 }
    g.moveTo(button.el, 1.3, 0.5)
    await wait(700)
    g.press(true)
    await wait(110)
    g.press(false)
    setPin({ ...at, text: "", typing: true })
    g.hide()
    await wait(400)
    for (let i = 1; i <= NOTE.length; i += 1) {
      setPin({ ...at, text: NOTE.slice(0, i), typing: true })
      await wait(42)
    }
    await wait(500)
    setPin({ ...at, text: NOTE, typing: false })
    await wait(1200)

    // Draw: circle the button.
    await pickTool("draw", wait)
    g.hide()
    const points = circlePoints(button.rect)
    for (let i = 1; i <= points.length; i += 1) {
      setStroke(points.slice(0, i))
      await wait(28)
    }
    await wait(1600)

    // Back to select, and clear the marks for the next run.
    await pickTool("select", wait)
    g.hide()
    await wait(900)
  }, touring)

  // While drawing, a pen tip leads the line; the pointer's glide would lag behind it.
  const tip = tool === "draw" ? stroke[stroke.length - 1] : undefined

  return (
    <FitFrame minWidth="40rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div
          ref={rootRef}
          data-tool={tool ?? "none"}
          onPointerDownCapture={() => {
            if (scripted.current || !touring) return
            setTouring(false)
            g.hide()
          }}
          onPointerMove={(event) => {
            if (touring || tool !== "select") return
            const root = rootRef.current
            const el = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-inspect]") : null
            setHover(root && el ? { el, label: el.dataset.inspect ?? "", rect: rectOf(el, root) } : null)
          }}
          onClickCapture={(event) => {
            const root = rootRef.current
            if (touring || !root || tool !== "select") return
            const el = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-inspect]") : null
            setSelected(el ? { el, label: el.dataset.inspect ?? "", rect: rectOf(el, root) } : null)
          }}
          className={cn(
            "rounded-(--chatcn-radius-lg) bg-(color:--chatcn-bg-subtle) shadow-(--chatcn-shadow-border) relative h-[21.5rem] w-full max-w-xl overflow-hidden",
            tool === "draw" && "cursor-crosshair",
          )}
        >
          <PreviewApp />

          {hover && hover.el !== selected?.el ? <PreviewSelection rect={hover.rect} variant="hover" /> : null}
          {tool === "select" && selected ? <PreviewSelection rect={selected.rect} label={selected.label} /> : null}

          <svg aria-hidden="true" className="text-(color:--chatcn-accent) pointer-events-none absolute inset-0 size-full">
            {stroke.length > 1 ? (
              <polyline
                points={stroke.map((p) => p.join(",")).join(" ")}
                fill="none"
                stroke="currentColor"
                strokeWidth={2.5}
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            ) : null}
          </svg>

          {pin ? (
            <div className="absolute flex items-start gap-2" style={{ left: pin.x - 12, top: pin.y - 12 }}>
              <span className="bg-(color:--chatcn-fg) text-(color:--chatcn-bg) text-[0.75rem]/[1rem] shadow-(--chatcn-shadow-md) grid size-6 shrink-0 place-items-center rounded-full rounded-bl-none font-medium">
                1
              </span>
              <span
                className={cn(
                  "bg-(color:--chatcn-surface) rounded-(--chatcn-radius-md) text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg) flex h-8 items-center px-2.5 whitespace-nowrap",
                  pin.typing ? "shadow-(--chatcn-shadow-lg) w-60" : "shadow-(--chatcn-shadow-md)",
                )}
              >
                {pin.text}
                {pin.typing ? <span className="bg-(color:--chatcn-fg) ms-px inline-block h-4 w-px animate-pulse" /> : null}
              </span>
            </div>
          ) : null}

          {tip ? (
            <span
              aria-hidden="true"
              className="bg-(color:--chatcn-accent) pointer-events-none absolute top-0 left-0 size-2.5 rounded-full shadow-[0_0_0_3px_color-mix(in_oklab,var(--chatcn-accent)_25%,transparent)]"
              style={{ transform: `translate(${tip[0] - 5}px, ${tip[1] - 5}px)` }}
            />
          ) : null}
          <PreviewToolbar tool={tool} onToolChange={setTool} />
          <Ghost ghost={g.ghost} />
        </div>
        <MoreOn slug="preview-toolbar">Select, comment on or draw over a live preview. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

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.