Aadi

Thumbs pour

AI chats

About

Feedback thumbs that fill like a glass, with a meniscus that sloshes and settles, and reasons that unfurl after a thumbs down.

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

Code

How Thumbs pour 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 { ThumbsPour, useReducedMotion } from "@/components/ui/thumbs-pour"

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,
  maxScale = 1,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
  /** Above 1, a small demo grows until its first child fills most of the frame. */
  maxScale?: number
}) {
  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)
      let scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      const child = el.firstElementChild as HTMLElement | null
      if (mode === "scale" && maxScale > 1 && scale === 1 && child) {
        const grow = Math.min(maxScale, (vw * 0.9) / child.offsetWidth, (vh * 0.9) / child.offsetHeight)
        if (grow > 1) scale = grow
      }
      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, maxScale])

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

const ANSWER =
  "Both tabs read the same expired token and race to refresh it. Put the refresh behind a lock in localStorage so the second tab waits for the first, then reads the new token instead of asking for its own."

interface CopyFlightProps
  extends Omit<React.ComponentProps<"button">, "value" | "onCopy" | "children"> {
  /** What lands on the clipboard. A function is read at click time. */
  value: string | (() => string)
  /**
   * The element being copied (a code block, a message). It is selected line by line and the
   * selection lifts off into the button, so the copy is something you see happen. Without it the
   * button only confirms.
   */
  from?: React.RefObject<HTMLElement | null>
  /** Visible label. `false` for an icon only button (it still has an accessible name). */
  label?: string | false
  copiedLabel?: string
  size?: "sm" | "md"
  variant?: "ghost" | "outline" | "subtle"
  /** How long the check holds before the sheets come back. Default 1600 ms. */
  holdMs?: number
  /** Say how many lines were copied after the label: "Copied 4 lines". Default true. */
  showLines?: boolean
  onCopy?: (value: string) => void
}

/** The kit's curves, for `style` and the Web Animations API. */
const MICRO_EASE = {
  /** Enters and state changes: fast start, long settle. */
  out: "cubic-bezier(0.23, 1, 0.32, 1)",
  /** Things that move across the screen. */
  inOut: "cubic-bezier(0.77, 0, 0.175, 1)",
  /** Exits: leaves at once, no lingering tail. */
  exit: "cubic-bezier(0.4, 0, 1, 1)",
} as const

function legacyCopy(text: string): Promise<void> {
  const area = document.createElement("textarea")
  area.value = text
  area.setAttribute("readonly", "")
  area.style.position = "fixed"
  area.style.opacity = "0"
  document.body.appendChild(area)
  area.select()
  const ok = document.execCommand("copy")
  area.remove()
  return ok ? Promise.resolve() : Promise.reject(new Error("Copy was blocked"))
}

/** The async clipboard, then the old execCommand path for contexts that lack it. */
function writeClipboard(text: string): Promise<void> {
  if (navigator.clipboard?.writeText) {
    return navigator.clipboard.writeText(text).catch(() => legacyCopy(text))
  }
  return legacyCopy(text)
}

const clamp = (v: number, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, v))

const LIFT_MS = 420

/**
 * Selects `source` line by line, then lifts the selection off as a sheet into `target`. Returns
 * how long it all takes, so the button can land its check on time.
 */
function liftSelection(source: HTMLElement, target: Element): number {
  const r = source.getBoundingClientRect()
  const t = target.getBoundingClientRect()
  const style = getComputedStyle(source)
  const padT = Number.parseFloat(style.paddingTop) || 0
  const padB = Number.parseFloat(style.paddingBottom) || 0
  const padX = Number.parseFloat(style.paddingInlineStart) || 0
  const lh = Number.parseFloat(style.lineHeight) || Number.parseFloat(style.fontSize) * 1.5 || 20
  const lines = clamp(Math.round((r.height - padT - padB) / lh), 1, 40)

  const sheet = document.createElement("div")
  sheet.setAttribute("aria-hidden", "true")
  sheet.className =
    "rounded-(--chatcn-radius-md) ring-(color:--chatcn-blue-border) pointer-events-none fixed z-[2147483000] overflow-hidden ring-1"
  Object.assign(sheet.style, {
    left: `${r.left}px`,
    top: `${r.top}px`,
    width: `${r.width}px`,
    height: `${r.height}px`,
    background: "color-mix(in oklab, var(--chatcn-blue) 16%, transparent)",
    transformOrigin: "0 0",
  })
  // The shape of the lines, shown once the sheet comes away from the text it covered.
  const marks = document.createElement("div")
  Object.assign(marks.style, { position: "absolute", inset: "0", opacity: "0" })
  for (let i = 0; i < Math.min(lines, 18); i++) {
    const bar = document.createElement("span")
    Object.assign(bar.style, {
      position: "absolute",
      left: `${padX}px`,
      top: `${padT + i * lh + lh * 0.38}px`,
      height: `${Math.max(2, lh * 0.24)}px`,
      width: `${38 + ((i * 37) % 52)}%`,
      borderRadius: "999px",
      background: "color-mix(in oklab, var(--chatcn-blue) 55%, transparent)",
    })
    marks.appendChild(bar)
  }
  sheet.appendChild(marks)
  document.body.appendChild(sheet)

  // Select: line by line, as if holding Shift and pressing down.
  const selectMs = clamp(lines * 34, 140, 320)
  sheet.animate([{ clipPath: "inset(0 0 100% 0)" }, { clipPath: "inset(0 0 0% 0)" }], {
    duration: selectMs,
    easing: `steps(${lines}, end)`,
    fill: "both",
  })
  // Lift: the selection comes away, carrying its lines, and arcs into the button.
  const hold = 90
  const sx = t.width / r.width
  const sy = t.height / r.height
  const ex = t.left - r.left
  const ey = t.top - r.top
  const arc = Math.min(70, 26 + Math.abs(ex) * 0.12)
  const frames: Keyframe[] = []
  const N = 16
  for (let i = 0; i <= N; i++) {
    const k = i / N
    const e = k < 0.5 ? 4 * k * k * k : 1 - (-2 * k + 2) ** 3 / 2
    const rise = Math.sin(Math.PI * Math.min(1, k * 1.6)) * -6 * (1 - e)
    frames.push({
      transform: `translate(${ex * e}px, ${ey * e - Math.sin(Math.PI * e) * arc + rise}px) scale(${1 + (sx - 1) * e}, ${1 + (sy - 1) * e})`,
      opacity: k > 0.85 ? 1 - (k - 0.85) / 0.15 : 1,
      boxShadow: k > 0.05 && k < 0.9 ? "var(--chatcn-shadow-lg)" : "none",
    })
  }
  // The marks wait until the sheet has left the text, so they never sit on top of it.
  marks.animate([{ opacity: 0 }, { opacity: 1 }], {
    duration: 120,
    delay: selectMs + hold + LIFT_MS * 0.22,
    fill: "forwards",
  })
  sheet
    .animate(frames, {
      duration: LIFT_MS,
      delay: selectMs + hold,
      easing: "linear",
      fill: "forwards",
    })
    .finished.catch(() => undefined)
    .finally(() => sheet.remove())
  return selectMs + hold + LIFT_MS
}

type ButtonVariant = "solid" | "outline" | "ghost" | "subtle"

type ButtonSize = "xs" | "sm" | "md" | "lg" | "icon-xs" | "icon-sm" | "icon-md" | "icon-lg"

const base = cn(
  "chatcn-focus inline-flex shrink-0 items-center justify-center gap-1.5 font-medium whitespace-nowrap select-none",
  "ease-(--chatcn-ease-standard) transition-[background-color,color,box-shadow,scale] duration-150",
  "active:scale-(--chatcn-press-scale) active:duration-100 disabled:pointer-events-none disabled:opacity-50",
  "[&_svg]:pointer-events-none [&_svg]:shrink-0",
)

const variants: Record<ButtonVariant, string> = {
  solid: "bg-(color:--chatcn-primary) text-(color:--chatcn-primary-fg) hover:bg-(color:--chatcn-primary-hover)",
  outline: "bg-(color:--chatcn-card) text-(color:--chatcn-fg) shadow-(--chatcn-shadow-xs) hover:bg-(color:--chatcn-fill-hover)",
  ghost: "text-(color:--chatcn-fg-muted) hover:bg-(color:--chatcn-fill-hover) hover:text-(color:--chatcn-fg)",
  subtle: "bg-(color:--chatcn-fill) text-(color:--chatcn-fg) hover:bg-(color:--chatcn-fill-hover)",
}

// Heights follow the control scale: 24, 28, 32, 36. Radii stay concentric inside 12 px surfaces.
const sizes: Record<ButtonSize, string> = {
  xs: "h-6 rounded-(--chatcn-radius-sm) px-2 text-[0.75rem]/[1rem] [&_svg]:size-3.5",
  sm: "h-7 rounded-(--chatcn-radius-sm) px-2.5 text-[0.8125rem]/[1.25rem] [&_svg]:size-3.5",
  md: "h-8 rounded-(--chatcn-radius-md) px-3 text-[0.875rem]/[1.25rem] tracking-[-0.003em] [&_svg]:size-4",
  lg: "h-9 rounded-(--chatcn-radius-md) px-3.5 text-[0.875rem]/[1.25rem] tracking-[-0.003em] [&_svg]:size-4",
  "icon-xs": "size-6 rounded-(--chatcn-radius-sm) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-3.5",
  "icon-sm": "size-7 rounded-(--chatcn-radius-sm) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-3.5",
  "icon-md": "size-8 rounded-(--chatcn-radius-md) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-4",
  "icon-lg": "size-9 rounded-(--chatcn-radius-md) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-4",
}

/** Class names for anything that should look like a button, such as a link. */
function buttonVariants({
  variant = "ghost",
  size = "md",
}: {
  variant?: ButtonVariant
  size?: ButtonSize
} = {}) {
  return cn(base, variants[variant], sizes[size])
}

/**
 * A copy button that shows the copy happen: select, lift, land. Press it and the block is
 * selected the way you would by hand, a blue selection filling it line by line from the top.
 * Then the selection comes away as a sheet carrying the shape of its lines, rises a little and
 * arcs into the button, landing as the icon's second sheet. The two sheets slide into one and give
 * way to a check, and the label says what happened: "Copied 4 lines". After a beat the check folds
 * back into the sheets.
 */
function CopyFlight({
  value,
  from,
  label = "Copy",
  copiedLabel = "Copied",
  size = "sm",
  variant = "ghost",
  holdMs = 1600,
  showLines = true,
  onCopy,
  onClick,
  className,
  ...props
}: CopyFlightProps) {
  const reduced = useReducedMotion()
  const iconRef = React.useRef<SVGSVGElement>(null)
  const [copied, setCopied] = React.useState<{ n: number; ms: number; lines: number } | null>(null)
  const [done, setDone] = React.useState(false)

  React.useEffect(() => {
    if (!copied) return
    const land = window.setTimeout(
      () => {
        setDone(true)
        // The button takes the sheet in: a short squeeze, as if it swallowed it.
        if (copied.ms) {
          iconRef.current?.animate([{ scale: "1" }, { scale: "0.8" }, { scale: "1" }], {
            duration: 320,
            easing: MICRO_EASE.out,
          })
        }
      },
      Math.max(0, copied.ms - 80),
    )
    const reset = window.setTimeout(() => setDone(false), holdMs + copied.ms)
    return () => {
      window.clearTimeout(land)
      window.clearTimeout(reset)
    }
  }, [copied, holdMs])

  const iconOnly = label === false
  const lines = copied?.lines ?? 0
  const swap = "ease-(--chatcn-ease-out) motion-reduce:transition-none"
  return (
    <button
      type="button"
      data-slot="copy-flight"
      data-copied={done ? "" : undefined}
      aria-label={iconOnly ? (done ? copiedLabel : "Copy") : undefined}
      onClick={(event) => {
        onClick?.(event)
        if (event.defaultPrevented) return
        const text = typeof value === "function" ? value() : value
        // Only a person's click touches the clipboard. A scripted one (a demo playing itself, a
        // test) still plays the motion, but writing without a gesture makes browsers ask for
        // clipboard permission, which nobody expects from a copy button.
        const write = event.nativeEvent.isTrusted ? writeClipboard(text) : Promise.resolve()
        write
          .then(() => {
            const source = from?.current
            const ms =
              source && iconRef.current && !reduced ? liftSelection(source, iconRef.current) : 0
            setCopied((c) => ({ n: (c?.n ?? 0) + 1, ms, lines: text.split("\n").length }))
            onCopy?.(text)
          })
          // Clipboard access can be denied (insecure context, permissions): stay unchanged.
          .catch(() => {})
      }}
      className={cn(
        buttonVariants({
          variant,
          size: iconOnly ? (size === "sm" ? "icon-sm" : "icon-md") : size,
        }),
        "relative gap-1.5",
        className,
      )}
      {...props}
    >
      <svg
        ref={iconRef}
        aria-hidden="true"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth={1.5}
        strokeLinecap="round"
        strokeLinejoin="round"
        className="shrink-0 overflow-visible"
      >
        {/* The copy icon's two sheets: they slide into one and give way to the check. */}
        <g
          className={cn(swap, "transition-[opacity,scale] duration-200")}
          style={{
            transformOrigin: "12px 12px",
            opacity: done ? 0 : 1,
            scale: done ? "0.7" : "1",
            transitionDelay: done ? "90ms" : "120ms",
          }}
        >
          <path
            d="M6 15L5.5 15A2.5 2.5 0 0 1 3 12.5L3 5.5A2.5 2.5 0 0 1 5.5 3L12.5 3A2.5 2.5 0 0 1 15 5.5L15 6"
            className={cn(swap, "transition-[translate] duration-200")}
            style={{ translate: done ? "3px 3px" : "0 0" }}
          />
          <path
            d="M11.5 9L18.5 9A2.5 2.5 0 0 1 21 11.5L21 18.5A2.5 2.5 0 0 1 18.5 21L11.5 21A2.5 2.5 0 0 1 9 18.5L9 11.5A2.5 2.5 0 0 1 11.5 9Z"
            className={cn(swap, "transition-[translate] duration-200")}
            style={{ translate: done ? "-3px -3px" : "0 0" }}
          />
        </g>
        {/* The kit's own check, drawn at full size so it reads at 14 px. */}
        <path
          d="M4.5 12.75L7.73 15.98A2.5 2.5 0 0 0 11.27 15.98L19.75 7.5"
          pathLength={1}
          strokeDasharray="1 1"
          className={cn(swap, "text-(color:--chatcn-green) transition-[stroke-dashoffset,opacity]")}
          style={{
            strokeDashoffset: done ? 0 : 1,
            opacity: done ? 1 : 0,
            transitionDuration: done ? "280ms" : "140ms",
            transitionDelay: done ? "170ms" : "0ms",
          }}
        />
      </svg>
      {iconOnly ? null : (
        <span className="relative inline-grid">
          <span
            className={cn(
              "ease-(--chatcn-ease-out) col-start-1 row-start-1 transition-[opacity,filter,translate] duration-200 motion-reduce:transition-opacity",
              done ? "-translate-y-1 opacity-0 blur-[2px]" : "opacity-100",
            )}
          >
            {label}
          </span>
          <span
            aria-hidden={!done}
            className={cn(
              "ease-(--chatcn-ease-out) col-start-1 row-start-1 whitespace-nowrap transition-[opacity,filter,translate] duration-200 motion-reduce:transition-opacity",
              done ? "opacity-100" : "translate-y-1 opacity-0 blur-[2px]",
            )}
          >
            {copiedLabel}
            {showLines && lines > 1 ? (
              <span className="text-(color:--chatcn-fg-subtle) ms-1 font-normal tabular-nums">
                {lines} lines
              </span>
            ) : null}
          </span>
        </span>
      )}
      <span className="sr-only" aria-live="polite">
        {done ? `${copiedLabel}${lines > 1 ? `, ${lines} lines` : ""}` : ""}
      </span>
    </button>
  )
}

function ThumbsPourDemo() {
  // Plays itself: a thumbs up that pours, a change of mind to a thumbs down, a reason picked, then
  // back to neutral, until someone touches it.
  const ref = React.useRef<HTMLDivElement>(null)
  const [touched, setTouched] = React.useState(false)
  const [cycle, setCycle] = React.useState(0)
  React.useEffect(() => {
    if (touched) return
    const press = (sel: string) => ref.current?.querySelector<HTMLButtonElement>(sel)?.click()
    const ids = [
      window.setTimeout(() => press('[aria-label="Good response"]'), 800),
      window.setTimeout(() => press('[aria-label="Bad response"]'), 3000),
      window.setTimeout(() => press('[data-slot="thumbs-pour"] [role="group"] button'), 4700),
      window.setTimeout(() => setCycle((c) => c + 1), 8000),
    ]
    return () => {
      for (const id of ids) window.clearTimeout(id)
    }
  }, [touched, cycle])
  return (
    <div
      ref={ref}
      key={cycle}
      className="flex w-full justify-center px-4 py-12"
      onPointerDownCapture={(e) => e.isTrusted && setTouched(true)}
      onKeyDownCapture={() => setTouched(true)}
    >
      <div className="flex w-full max-w-lg flex-col gap-2">
        <p className="text-(color:--chatcn-fg) text-[0.9375rem]/[1.5rem] tracking-[-0.006em] text-pretty">{ANSWER}</p>
        <div className="-ms-1.5 flex items-center gap-0.5">
          <CopyFlight value={ANSWER} label={false} />
          <ThumbsPour />
        </div>
      </div>
    </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>
  )
}

/** Thumbs pour, playing on its own, with the line back to its chatcn page. */
export default function ThumbsPourPreview() {
  return (
    <FitFrame maxScale={1.6}>
      <div className="mx-auto flex w-[34rem] max-w-full flex-col items-center gap-2 py-4">
        <ThumbsPourDemo />
        <MoreOn slug="thumbs-pour">One of 30 free microinteractions on</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Stat Card

    Stat Card

    96
  • Weather Card

    Weather Card

    45
  • Audio Visualizer

    Audio Visualizer

    43
  • Product Card

    Product Card

    37
  • Ticker Card

    Ticker Card

    37
  • Settings Panel

    Settings Panel

    35
  • Dither Orb

    Dither Orb

    32
  • Voice Orb

    Voice Orb

    32

More in AI chats

View all
  • AI Actions

    AI Actions

    372
  • Agent Chat

    Agent Chat

    21
  • Aquarium Prompt

    Aquarium Prompt

    212
  • Illos Knowledge Sources

    Illos Knowledge Sources

    71
  • AI SaaS Workflow Hero

    AI SaaS Workflow Hero

    32
  • AI Chat Composer

    AI Chat Composer

    17
  • AI Response

    AI Response

    16
  • Research Report

    Research Report

    12