Aadi

Seed dice

Component

About

A seed you can roll: a 3D die tumbles while each digit spins like a slot drum.

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

Code

How Seed dice 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 { SeedDice } from "@/components/ui/seed-dice"

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) {
        // A full width wrapper says nothing about the demo's size: measure its widest child.
        let cw = child.offsetWidth
        if (cw >= el.offsetWidth - 1) {
          cw = 0
          for (const c of Array.from(child.children)) cw = Math.max(cw, (c as HTMLElement).offsetWidth)
        }
        const grow = Math.min(maxScale, (vw * 0.9) / Math.max(cw, 1), (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>
  )
}

/**
 * The landscape reads its colours as `--chatcn-${name}` at runtime, and the packer only ships
 * variables named in full somewhere in the source. Naming them here ships them; without this
 * every colour falls back to gray on 21st.
 */
const SCENE_COLORS =
  "var(--chatcn-purple) var(--chatcn-red) var(--chatcn-amber) var(--chatcn-blue) var(--chatcn-teal) var(--chatcn-green) var(--chatcn-green-bg) var(--chatcn-amber-bg)"

type Palette = {
  sky: string[]
  far: string
  near: string
  ground: string[]
  sun: boolean
  reflect: boolean
}

// biome-ignore format: kept on one line so the design lint exception below covers every colour
// design-lint-ignore-next-line raw-color: paint for a picture (night sky, lit highlights), not UI colours
const PAINT = { night: "#0b1026", hill: "#141a33", core: "rgba(255, 251, 240, 1)", warm: "rgba(255, 238, 205, 0.95)", cool: "rgba(235, 238, 255, 0.92)", shine: "rgba(255, 246, 228, 1)" }

const PALETTES: Palette[] = [
  {
    sky: ["purple", "red", "amber"],
    far: "purple",
    near: "blue",
    ground: ["teal", "blue"],
    sun: true,
    reflect: true,
  },
  {
    sky: ["blue", "teal", "green-bg"],
    far: "teal",
    near: "green",
    ground: ["blue", "teal"],
    sun: true,
    reflect: true,
  },
  {
    sky: [PAINT.night, "blue", "purple"],
    far: "purple",
    near: PAINT.hill,
    ground: ["blue", PAINT.night],
    sun: false,
    reflect: true,
  },
  {
    sky: ["amber", "red", "amber-bg"],
    far: "red",
    near: "amber",
    ground: ["amber", "red"],
    sun: true,
    reflect: false,
  },
  {
    sky: ["teal", "green-bg", "amber-bg"],
    far: "green",
    near: "teal",
    ground: ["green", "teal"],
    sun: true,
    reflect: true,
  },
]

function paint(
  ctx: CanvasRenderingContext2D,
  w: number,
  h: number,
  seed: number,
  time: number | undefined,
  c: (v: string) => string,
) {
  const s = Math.abs(Math.floor(seed))
  const p = PALETTES[s % PALETTES.length] as Palette
  const rand = (k: number) => {
    const x = Math.sin(s * 12.9898 + k * 78.233) * 43758.5453
    return x - Math.floor(x)
  }
  const horizon = h * (0.56 + rand(1) * 0.08)
  const sky = ctx.createLinearGradient(0, 0, 0, horizon)
  p.sky.forEach((v, i) => {
    sky.addColorStop(i / (p.sky.length - 1), c(v))
  })
  ctx.fillStyle = sky
  ctx.fillRect(0, 0, w, h)

  // The sun (or moon) rides an arc; time 0 to 1 takes it across.
  const t = time ?? 0.35 + rand(2) * 0.4
  const sx = w * (0.12 + t * 0.76)
  const sy = horizon - Math.sin(Math.PI * t) * h * 0.38 + h * 0.04
  const r = h * (0.08 + rand(3) * 0.05)
  const glow = ctx.createRadialGradient(sx, sy, 0, sx, sy, r)
  glow.addColorStop(0, PAINT.core)
  glow.addColorStop(0.75, p.sun ? PAINT.warm : PAINT.cool)
  glow.addColorStop(1, p.sun ? c("amber") : c("blue"))
  ctx.fillStyle = glow
  ctx.beginPath()
  ctx.arc(sx, sy, r, 0, Math.PI * 2)
  ctx.fill()

  const ridge = (base: number, amp: number, color: string, k: number, alpha: number) => {
    ctx.globalAlpha = alpha
    ctx.fillStyle = color
    ctx.beginPath()
    ctx.moveTo(0, h)
    for (let x = 0; x <= w + 1; x += w / 32) {
      const y =
        base +
        Math.sin(x / (w / (3 + rand(k) * 3)) + rand(k + 1) * 6) * amp +
        Math.sin(x / (w / 11) + rand(k + 2) * 6) * amp * 0.35
      ctx.lineTo(x, y)
    }
    ctx.lineTo(w, h)
    ctx.fill()
    ctx.globalAlpha = 1
  }
  ridge(horizon - h * 0.05, h * 0.06, c(p.far), 10, 0.55)
  ridge(horizon + h * 0.02, h * 0.045, c(p.near), 20, 1)

  const ground = ctx.createLinearGradient(0, horizon + h * 0.08, 0, h)
  p.ground.forEach((v, i) => {
    ground.addColorStop(i, c(v))
  })
  ctx.fillStyle = ground
  ctx.fillRect(0, horizon + h * 0.09, w, h)
  if (p.reflect) {
    ctx.globalAlpha = 0.45
    ctx.fillStyle = PAINT.shine
    for (let i = 0; i < 5; i++) {
      const y = horizon + h * (0.13 + i * 0.045)
      if (y > h) break
      ctx.fillRect(sx - (r * (1.2 - i * 0.2)) / 1, y, r * 2 * (1.2 - i * 0.2), 1.5)
    }
    ctx.globalAlpha = 1
  }
}

/**
 * A small landscape painted on a canvas from the theme's own colours, for demos that stand in for
 * a generated or rendered picture. The seed picks the palette (dusk, day, night, desert, forest),
 * where the sun sits and the shape of the hills, so a new seed is a new picture. `time` moves the
 * sun across the sky, for a render that advances frame by frame.
 */
function Scene({ seed, time, className }: { seed: number; time?: number; className?: string }) {
  const ref = React.useRef<HTMLCanvasElement>(null)
  const [size, setSize] = React.useState<[number, number] | null>(null)

  React.useLayoutEffect(() => {
    const el = ref.current
    if (!el) return
    const ro = new ResizeObserver(() => setSize([el.clientWidth, el.clientHeight]))
    ro.observe(el)
    return () => ro.disconnect()
  }, [])

  React.useEffect(() => {
    const canvas = ref.current
    const ctx = canvas?.getContext("2d")
    if (!canvas || !ctx || !size) return
    const [w, h] = size
    const dpr = Math.min(2, window.devicePixelRatio || 1)
    canvas.width = Math.round(w * dpr)
    canvas.height = Math.round(h * dpr)
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
    const style = getComputedStyle(canvas)
    // Theme colours by name; a literal colour (night's deep blues) passes straight through.
    const c = (v: string) =>
      v.startsWith("#") ? v : style.getPropertyValue(`--chatcn-${v}`).trim() || "gray"
    paint(ctx, w, h, seed, time, c)
  }, [seed, time, size])

  return <canvas ref={ref} className={cn("block size-full", className)} />
}

/** The new picture resolves over the old one, out of a blur, like a fresh generation. */
function Resolve({ children }: { children: React.ReactNode }) {
  const ref = React.useRef<HTMLDivElement>(null)
  React.useLayoutEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
    ref.current?.animate(
      [
        { opacity: 0, filter: "blur(10px)" },
        { opacity: 1, filter: "blur(0px)" },
      ],
      { duration: 520, delay: 380, easing: "cubic-bezier(0.23, 1, 0.32, 1)", fill: "backwards" },
    )
  }, [])
  return (
    <div ref={ref} className="absolute inset-0">
      {children}
    </div>
  )
}

function SeedDiceDemo() {
  const [seed, setSeed] = React.useState(482193)
  // The last two seeds are both painted, so the new one resolves over the old.
  const [layers, setLayers] = React.useState([482193])
  React.useEffect(
    () => setLayers((l) => (l[l.length - 1] === seed ? l : [...l.slice(-1), seed])),
    [seed],
  )
  const [locked, setLocked] = React.useState(false)
  const [touched, setTouched] = React.useState(false)
  const diceRef = React.useRef<HTMLDivElement>(null)

  // Rolls by itself every couple of seconds until someone uses it.
  React.useEffect(() => {
    if (touched) return
    const id = window.setInterval(() => {
      diceRef.current?.querySelector<HTMLButtonElement>("button")?.click()
    }, 2200)
    return () => window.clearInterval(id)
  }, [touched])

  return (
    <div className="flex w-full justify-center px-4 py-12" onPointerDown={() => setTouched(true)}>
      <div className="flex flex-col items-start gap-3">
        <div
          className="rounded-(--chatcn-radius-lg) relative aspect-[4/3] w-72 overflow-hidden"
          role="img"
          aria-label={`Landscape, seed ${seed}`}
        >
          {layers.map((s, i) =>
            i === 0 ? (
              <div key={s} className="absolute inset-0">
                <Scene seed={s} />
              </div>
            ) : (
              <Resolve key={s}>
                <Scene seed={s} />
              </Resolve>
            ),
          )}
        </div>
        <div ref={diceRef}>
          <SeedDice seed={seed} onSeedChange={setSeed} locked={locked} onLockedChange={setLocked} />
        </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>
  )
}

/** Seed dice, playing on its own, with the line back to its chatcn page. */
export default function SeedDicePreview() {
  return (
    <FitFrame maxScale={1.6}>
      <div data-scene-colors={SCENE_COLORS} className="mx-auto flex w-[24rem] max-w-full flex-col items-center gap-2 py-4">
        <SeedDiceDemo />
        <MoreOn slug="seed-dice">One of 30 free microinteractions on</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Stat Card

    Stat Card

    98
  • Weather Card

    Weather Card

    46
  • Audio Visualizer

    Audio Visualizer

    44
  • Product Card

    Product Card

    38
  • Ticker Card

    Ticker Card

    37
  • Settings Panel

    Settings Panel

    36
  • Voice Orb

    Voice Orb

    34
  • Dither Orb

    Dither Orb

    32

Explore more

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