Motion OTP inputs
Five one-time-code inputs that keep the same bordered slots and vary only the per-slot entry motion: a scale pop, a fade, a slide, a spring settle and a shake that rejects a non-digit. Each is self-contained, sized, token-driven, auto-advances on typing, and handles paste and Backspace.
Installation
The styled layer is free and installs like any other ai2 component.
Run the following command
npx shadcn@latest add @ai2/input-otp-motionDependencies, the @ai2/tokens theme and the component file are installed together.
Install dependencies
npm install motionCopy the source
components/ui/input-otp-motion.tsx"use client"
import * as React from "react"
import { motion, useReducedMotion } from "motion/react"
import { cn } from "@/lib/utils"
/* Motion OTP family: 5 shaped one-time-code inputs. The difference is ONLY in the
cell entrance animation: pop, fade, slide, spring and a shake on invalid input.
Every cell is a real <input maxLength=1 inputMode=numeric>; typing a digit moves
focus forward, Backspace clears and moves back, and pasting fills every cell.
Color comes ONLY from tokens. All animations are disabled through
useReducedMotion. Self-sufficient: NO input-otp package and NO radix. */
export type StyledSize = "sm" | "md" | "lg" | "xl"
type OtpProps = {
className?: string
size?: StyledSize
length?: number
value?: string
defaultValue?: string
onValueChange?: (v: string) => void
}
const cellSize: Record<StyledSize, string> = {
sm: "size-8 text-sm",
md: "size-10 text-base",
lg: "size-12 text-lg",
xl: "size-14 text-xl",
}
const cellBase =
"bg-transparent text-center font-medium tabular-nums text-foreground outline-none transition-colors placeholder:text-muted-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
const rootBase = "inline-flex items-center gap-2"
/* Kontrollu/kontrolsuz OTP durumu + ileri/geri odak, yapistirma. */
function useOtpCode(
length: number,
{ value, defaultValue, onValueChange }: Pick<OtpProps, "value" | "defaultValue" | "onValueChange">
) {
const isControlled = value !== undefined
const [internal, setInternal] = React.useState<string>(() => (defaultValue ?? "").slice(0, length))
const current = (isControlled ? value : internal) ?? ""
const chars = React.useMemo(() => {
const arr: string[] = Array(length).fill("")
for (let i = 0; i < length; i++) arr[i] = current[i] ?? ""
return arr
}, [current, length])
const refs = React.useRef<Array<HTMLInputElement | null>>([])
const commit = (next: string) => {
if (!isControlled) setInternal(next)
onValueChange?.(next)
}
const setAt = (i: number, raw: string) => {
const ch = raw.slice(-1)
const arr = [...chars]
arr[i] = ch
commit(arr.join(""))
if (ch && i < length - 1) refs.current[i + 1]?.focus()
}
const onKey = (i: number, e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Backspace") {
const arr = [...chars]
if (chars[i]) {
arr[i] = ""
commit(arr.join(""))
} else if (i > 0) {
arr[i - 1] = ""
commit(arr.join(""))
refs.current[i - 1]?.focus()
}
e.preventDefault()
} else if (e.key === "ArrowLeft" && i > 0) {
refs.current[i - 1]?.focus()
} else if (e.key === "ArrowRight" && i < length - 1) {
refs.current[i + 1]?.focus()
}
}
const onPaste = (i: number, e: React.ClipboardEvent<HTMLInputElement>) => {
e.preventDefault()
const text = e.clipboardData.getData("text").replace(/\s+/g, "")
if (!text) return
const arr = [...chars]
for (let k = 0; k < text.length && i + k < length; k++) arr[i + k] = text[k]
commit(arr.join(""))
const last = Math.min(i + text.length, length - 1)
refs.current[last]?.focus()
}
return { chars, refs, setAt, onKey, onPaste }
}
type Controller = ReturnType<typeof useOtpCode>
function cellHandlers(ctl: Controller, i: number) {
return {
ref: (el: HTMLInputElement | null) => {
ctl.refs.current[i] = el
},
value: ctl.chars[i],
onChange: (e: React.ChangeEvent<HTMLInputElement>) => ctl.setAt(i, e.target.value),
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => ctl.onKey(i, e),
onPaste: (e: React.ClipboardEvent<HTMLInputElement>) => ctl.onPaste(i, e),
inputMode: "numeric" as const,
autoComplete: i === 0 ? ("one-time-code" as const) : ("off" as const),
maxLength: 1,
"aria-label": `Digit ${i + 1}`,
}
}
const boxLook = "rounded-md border focus-visible:border-ring"
/* Pop: the filling cell does a short scale jump. */
export function PopOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const reduce = useReducedMotion()
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<motion.input
key={i}
{...cellHandlers(ctl, i)}
animate={reduce ? undefined : { scale: ch ? [1, 1.16, 1] : 1 }}
transition={{ duration: 0.26, ease: "easeOut" }}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
))}
</div>
)
}
/* Fade: the filling cell goes from a muted opacity to full opacity. */
export function FadeOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const reduce = useReducedMotion()
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<motion.input
key={i}
{...cellHandlers(ctl, i)}
animate={reduce ? undefined : { opacity: ch ? [0.35, 1] : 1 }}
transition={{ duration: 0.32, ease: "easeOut" }}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
))}
</div>
)
}
/* Slide: the filling cell does a short slide downwards from the top. */
export function SlideOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const reduce = useReducedMotion()
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<motion.input
key={i}
{...cellHandlers(ctl, i)}
animate={reduce ? undefined : { y: ch ? [-6, 0] : 0 }}
transition={{ duration: 0.24, ease: "easeOut" }}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
))}
</div>
)
}
/* Spring: the filling cell grows springily and settles into place. */
export function SpringOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const reduce = useReducedMotion()
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<motion.input
key={i}
{...cellHandlers(ctl, i)}
animate={reduce ? undefined : { scale: ch ? 1.08 : 1 }}
transition={{ type: "spring" as const, stiffness: 480, damping: 12 }}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
))}
</div>
)
}
/* Shake: if a non-digit character is typed the cell trembles in the danger tone. The invalid marker is cleared by a fixed-duration timeout (cancelled on cleanup). */
export function ShakeOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const reduce = useReducedMotion()
const [invalidAt, setInvalidAt] = React.useState<number | null>(null)
React.useEffect(() => {
if (invalidAt === null) return
const id = window.setTimeout(() => setInvalidAt(null), 420)
return () => window.clearTimeout(id)
}, [invalidAt])
const handleChange = (i: number, raw: string) => {
const ch = raw.slice(-1)
if (ch && !/[0-9]/.test(ch)) {
setInvalidAt(i)
return
}
setInvalidAt(null)
ctl.setAt(i, raw)
}
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => {
const bad = invalidAt === i
return (
<motion.input
key={i}
{...cellHandlers(ctl, i)}
onChange={(e) => handleChange(i, e.target.value)}
aria-invalid={bad || undefined}
animate={reduce || !bad ? undefined : { x: [0, -5, 5, -3, 3, 0] }}
transition={{ duration: 0.38, ease: "easeInOut" }}
className={cn(
cellBase,
cellSize[size],
boxLook,
ch ? "border-primary" : "border-field-border",
"aria-invalid:border-danger aria-invalid:ring-danger/20 dark:aria-invalid:ring-danger/40"
)}
/>
)
})}
</div>
)
}Manual installs skip the @ai2/tokens theme, so add the token CSS from the theming guide or the tone colors will be missing.
Variations
5 takes on the same idea. Each is its own export, and every one accepts a size prop (sm, md, lg, xl) aligned to the base Button scale.
Pop
The filled slot pops with a short scale burst.
import { PopOtp } from "@/components/ui/input-otp-motion"
<PopOtp />Fade
The digit fades up from a dim opacity.
import { FadeOtp } from "@/components/ui/input-otp-motion"
<FadeOtp />Slide
The digit slides down into its slot.
import { SlideOtp } from "@/components/ui/input-otp-motion"
<SlideOtp />Spring
The filled slot settles with a spring.
import { SpringOtp } from "@/components/ui/input-otp-motion"
<SpringOtp />Shake
A non-digit entry shakes the slot in the danger tone.
import { ShakeOtp } from "@/components/ui/input-otp-motion"
<ShakeOtp />ai2 Motion OTP inputs: 5 styled variations on the token system
The ai2 Motion OTP inputs are a set of 5 decorative button variations from the styled layer of the @ai2 design system, built around one-time-code entry with animated slots. They are free and MIT licensed, and every color comes from a semantic token, so they theme with the rest of ai2 in light and dark.
Motion runs on framer-motion: framer-motion animates each slot as it is filled. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, every transform is skipped and the digit appears instantly.
What is in the ai2 Motion OTP inputs?
5 exports in one file: Pop, Fade, Slide, Spring and Shake. Each renders a native button and takes a size prop (sm, md, lg, xl) aligned to the base Button. They are separate from the base Button on purpose: the base keeps its clean variant, tone and size axes, while the styled layer carries the effects.
You own the file. Copy the one category file and you have all 5 variations, with no runtime dependency on ai2 itself.
Why use it
- On-system by construction: Every color resolves to an ai2 semantic token, so the buttons follow your theme in light and dark with no extra work.
- Effect without the sprawl: The decorations live in a dedicated styled file, so the base Button keeps its clean, predictable API.
- Accessible and honest: Each renders a real button element, keeps a visible focus ring, and respects prefers-reduced-motion.
Features
- Token-driven color: No hardcoded hex or oklch; the look recolors with your theme tokens.
- framer-motion: framer-motion animates each slot as it is filled.
- Reduced-motion aware: Under prefers-reduced-motion, every transform is skipped and the digit appears instantly.
- Size aligned to the base: Every variation takes sm, md, lg and xl matching the base Button height scale, so styled and base buttons line up in a row.
Production tips
- Use it for emphasis, not everywhere: Styled buttons draw the eye. Reserve them for the one action you want people to take on a screen, and use the base Button for the rest.
- Keep labels as verbs: The decoration adds weight, so a clear action label keeps the button scannable.
- Pick one variation per surface: The variations share a family; using two different ones in the same view competes for attention.
Works with the rest of ai2
The Motion OTP inputs sit alongside the base Button and the rest of the @ai2 registry. They share the same token file, so a styled action next to a base button or a badge stays visually consistent in both modes.