← Components

Selection and input

Dice

A 3D die for random picks. Press it and it tumbles, then settles on a face with a small bounce. The result is announced.

Examples and variants

Who presents

The rolled number lights up a name.

Rolled 1
  • 1 Ana
  • 2 Ben
  • 3 Chen
  • 4 Dee
  • 5 Eli
  • 6 Fay
Example
function DiceRoll() {
  const [rolled, setRolled] = useState<number | null>(null)
  return (
    <div className="flex flex-col items-center gap-stack-sm">
      <Dice className="my-3" label="Roll to pick who presents" onRoll={setRolled} />
      <ul className="flex flex-wrap justify-center gap-1 text-sm" aria-label="People">
        {people.map((name, i) => (
          <li
            key={name}
            className="rounded-(--shape-sm) px-2 py-0.5 transition-colors duration-(--duration-fast)"
            style={rolled === i + 1 ? { background: "var(--color-brand-subtle)", color: "var(--color-brand-fg)" } : { color: "var(--on-surface-variant)" }}
          >
            {i + 1} {name}
          </li>
        ))}
      </ul>
    </div>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/dice.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install cn
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/dice.tsxdice
      components/ui/dice.tsx
      "use client"
      
      import * as React from "react"
      import { cn } from "cn"
      import { motionLevel } from "@/lib/overlay"
      
      /*
        Dice: a 3D die for random picks, resting at a slight tilt so it reads as a cube. Press it (or Enter / Space) and it tumbles,
        then settles on a face with a small bounce. Calm tumbles once; still shows
        the result straight away. The result is announced.
      */
      const pips: Record<number, number[]> = {
        1: [4],
        2: [0, 8],
        3: [0, 4, 8],
        4: [0, 2, 6, 8],
        5: [0, 2, 4, 6, 8],
        6: [0, 2, 3, 5, 6, 8],
      }
      
      // Face placement on the cube, and the cube rotation that brings it to the front.
      const faces: Record<number, { place: string; x: number; y: number }> = {
        1: { place: "rotateY(0deg)", x: 0, y: 0 },
        2: { place: "rotateY(90deg)", x: 0, y: -90 },
        6: { place: "rotateY(180deg)", x: 0, y: 180 },
        5: { place: "rotateY(-90deg)", x: 0, y: 90 },
        3: { place: "rotateX(90deg)", x: -90, y: 0 },
        4: { place: "rotateX(-90deg)", x: 90, y: 0 },
      }
      
      function Face({ value }: { value: number }) {
        return (
          <span
            className="dice-face absolute inset-0 grid grid-cols-3 grid-rows-3 place-items-center rounded-(--dice-corner) bg-(--dice-face) p-[12%] shadow-[inset_0_0_0_var(--stroke-width-thin)_var(--stroke-color-subtle)]"
            style={{ transform: `${faces[value].place} translateZ(calc(var(--dice-size) / 2))` }}
          >
            {Array.from({ length: 9 }, (_, i) => (
              <span key={i} className={cn("size-[60%] rounded-full", pips[value].includes(i) ? "bg-(--dice-pip)" : "")} />
            ))}
          </span>
        )
      }
      
      function Dice({
        defaultValue = 1,
        onRoll,
        label = "Roll the die",
        className,
      }: {
        defaultValue?: 1 | 2 | 3 | 4 | 5 | 6
        onRoll?: (value: number) => void
        label?: string
        className?: string
      }) {
        const ref = React.useRef<HTMLButtonElement>(null)
        const [value, setValue] = React.useState<number>(defaultValue)
        const [turn, setTurn] = React.useState({ x: faces[defaultValue].x, y: faces[defaultValue].y, still: false })
        const [rolling, setRolling] = React.useState(false)
      
        function roll() {
          if (rolling) return
          const level = motionLevel(ref.current)
          const next = 1 + Math.floor(Math.random() * 6)
          const tumbles = level === "calm" ? 1 : 2 + Math.floor(Math.random() * 2)
          // Keep turning forward: round the current angle up to whole turns, add tumbles, then the face.
          const whole = (deg: number) => Math.ceil(deg / 360) * 360
          setTurn({
            x: whole(turn.x) + tumbles * 360 + faces[next].x,
            y: whole(turn.y) + tumbles * 360 + faces[next].y,
            still: level === "still",
          })
          setValue(next)
          onRoll?.(next)
          if (level !== "still") setRolling(true)
        }
      
        return (
          <>
          <button
            ref={ref}
            type="button"
            data-slot="dice"
            aria-label={label}
            aria-busy={rolling}
            onClick={roll}
            className={cn(
              "dice inline-grid size-(--dice-size) place-items-center rounded-(--dice-corner) outline-none [perspective:calc(var(--dice-size)*6)] focus-visible:shadow-(--focus-ring)",
              className
            )}
          >
            <span
              className="dice-cube relative size-full [transform-style:preserve-3d]"
              data-still={turn.still || undefined}
              style={{ transform: `rotateX(var(--dice-tilt-x)) rotateY(var(--dice-tilt-y)) rotateX(${turn.x}deg) rotateY(${turn.y}deg)` }}
              onTransitionEnd={() => setRolling(false)}
            >
              {[1, 2, 3, 4, 5, 6].map((face) => (
                <Face key={face} value={face} />
              ))}
            </span>
          </button>
          <span className="sr-only" aria-live="polite">
            {rolling ? "" : `Rolled ${value}`}
          </span>
          </>
        )
      }
      
      export { Dice }
      

Imports

What the examples on this page import:

Imports
import { Button } from "@/components/ui/button"
import { CardStack } from "@/components/ui/card-stack"
import { Confetti } from "@/components/ui/confetti"
import { Dice } from "@/components/ui/dice"
import { FlipBoard } from "@/components/ui/flip-board"
import { Metaballs } from "@/components/ui/metaballs"
import { tokenMs } from "@/lib/motion/token-ms"

Anatomy

  1. 1Cube · --dice-size, --dice-corner; turns over --dice-roll-duration.
  2. 2Faces · --dice-face with --dice-pip pips.

Props

PropTypeDefaultDescription
onRoll(value: number) => void—Called with 1 to 6.
defaultValue1 to 61Starting face.
labelstring"Roll the die"Button name.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--dice-sizevar(--space-16)64pxsame
--dice-facevar(--surface-container-lowest)oklch(1 0 0)oklch(0.14 0 0)
--dice-pipvar(--on-surface)oklch(0.22 0.01 260)oklch(1 0 0)
--dice-cornervar(--shape-md)14pxsame
--dice-roll-durationvar(--duration-reward)800mssame
--dice-tilt-x-18deg-18degsame
--dice-tilt-y24deg24degsame

Motion

TriggerWhat happensTokens
Press2 or 3 tumbles, then a bounce onto the face. Calm: one tumble. Still: the face appears.--dice-roll-duration, --ease-bounce

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • A button; Enter and Space roll.
  • "Rolled 4" is announced when it settles.

Usage

Do

  • Use for playful random picks.

Don’t

  • Don't use where fairness must be auditable.

Code

components/ui/dice.tsx
"use client"

import * as React from "react"
import { cn } from "cn"
import { motionLevel } from "@/lib/overlay"

/*
  Dice: a 3D die for random picks, resting at a slight tilt so it reads as a cube. Press it (or Enter / Space) and it tumbles,
  then settles on a face with a small bounce. Calm tumbles once; still shows
  the result straight away. The result is announced.
*/
const pips: Record<number, number[]> = {
  1: [4],
  2: [0, 8],
  3: [0, 4, 8],
  4: [0, 2, 6, 8],
  5: [0, 2, 4, 6, 8],
  6: [0, 2, 3, 5, 6, 8],
}

// Face placement on the cube, and the cube rotation that brings it to the front.
const faces: Record<number, { place: string; x: number; y: number }> = {
  1: { place: "rotateY(0deg)", x: 0, y: 0 },
  2: { place: "rotateY(90deg)", x: 0, y: -90 },
  6: { place: "rotateY(180deg)", x: 0, y: 180 },
  5: { place: "rotateY(-90deg)", x: 0, y: 90 },
  3: { place: "rotateX(90deg)", x: -90, y: 0 },
  4: { place: "rotateX(-90deg)", x: 90, y: 0 },
}

function Face({ value }: { value: number }) {
  return (
    <span
      className="dice-face absolute inset-0 grid grid-cols-3 grid-rows-3 place-items-center rounded-(--dice-corner) bg-(--dice-face) p-[12%] shadow-[inset_0_0_0_var(--stroke-width-thin)_var(--stroke-color-subtle)]"
      style={{ transform: `${faces[value].place} translateZ(calc(var(--dice-size) / 2))` }}
    >
      {Array.from({ length: 9 }, (_, i) => (
        <span key={i} className={cn("size-[60%] rounded-full", pips[value].includes(i) ? "bg-(--dice-pip)" : "")} />
      ))}
    </span>
  )
}

function Dice({
  defaultValue = 1,
  onRoll,
  label = "Roll the die",
  className,
}: {
  defaultValue?: 1 | 2 | 3 | 4 | 5 | 6
  onRoll?: (value: number) => void
  label?: string
  className?: string
}) {
  const ref = React.useRef<HTMLButtonElement>(null)
  const [value, setValue] = React.useState<number>(defaultValue)
  const [turn, setTurn] = React.useState({ x: faces[defaultValue].x, y: faces[defaultValue].y, still: false })
  const [rolling, setRolling] = React.useState(false)

  function roll() {
    if (rolling) return
    const level = motionLevel(ref.current)
    const next = 1 + Math.floor(Math.random() * 6)
    const tumbles = level === "calm" ? 1 : 2 + Math.floor(Math.random() * 2)
    // Keep turning forward: round the current angle up to whole turns, add tumbles, then the face.
    const whole = (deg: number) => Math.ceil(deg / 360) * 360
    setTurn({
      x: whole(turn.x) + tumbles * 360 + faces[next].x,
      y: whole(turn.y) + tumbles * 360 + faces[next].y,
      still: level === "still",
    })
    setValue(next)
    onRoll?.(next)
    if (level !== "still") setRolling(true)
  }

  return (
    <>
    <button
      ref={ref}
      type="button"
      data-slot="dice"
      aria-label={label}
      aria-busy={rolling}
      onClick={roll}
      className={cn(
        "dice inline-grid size-(--dice-size) place-items-center rounded-(--dice-corner) outline-none [perspective:calc(var(--dice-size)*6)] focus-visible:shadow-(--focus-ring)",
        className
      )}
    >
      <span
        className="dice-cube relative size-full [transform-style:preserve-3d]"
        data-still={turn.still || undefined}
        style={{ transform: `rotateX(var(--dice-tilt-x)) rotateY(var(--dice-tilt-y)) rotateX(${turn.x}deg) rotateY(${turn.y}deg)` }}
        onTransitionEnd={() => setRolling(false)}
      >
        {[1, 2, 3, 4, 5, 6].map((face) => (
          <Face key={face} value={face} />
        ))}
      </span>
    </button>
    <span className="sr-only" aria-live="polite">
      {rolling ? "" : `Rolled ${value}`}
    </span>
    </>
  )
}

export { Dice }