Length OTP inputs
Five one-time-code inputs that keep the same slot look and vary only the shape of the code: four, six and eight digits, a 3-3 grouped code, and a masked code that renders token dots instead of digits. 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-lengthDependencies, the @ai2/tokens theme and the component file are installed together.
Copy the source
components/ui/input-otp-length.tsx"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
/* Length OTP family: 5 code shapes (4 digits, 6 digits, 8 digits, a 3-3 group and a
masked one). The difference is ONLY the shape of the code: the number of digits,
the grouping, and whether the digit is masked with a dot. 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. No animation. 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 dotSize: Record<StyledSize, string> = {
sm: "size-1.5",
md: "size-2",
lg: "size-2.5",
xl: "size-3",
}
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"
const boxLook = "rounded-md border focus-visible:border-ring"
/* 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}`,
}
}
/* Shared shell: a plain box row, the only difference is the digit count. */
function PlainOtp({ className, size = "md", length, value, defaultValue, onValueChange }: OtpProps & { length: number }) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<input
key={i}
{...cellHandlers(ctl, i)}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
))}
</div>
)
}
/* Four: 4 haneli kisa kod. */
export function FourOtp({ length = 4, ...props }: OtpProps) {
return <PlainOtp length={length} {...props} />
}
/* Six: 6 haneli standart dogrulama kodu. */
export function SixOtp({ length = 6, ...props }: OtpProps) {
return <PlainOtp length={length} {...props} />
}
/* Eight: an 8-digit long code; the sm or md size is recommended for narrow areas. */
export function EightOtp({ length = 8, ...props }: OtpProps) {
return <PlainOtp length={length} {...props} />
}
/* Grouped: haneler 3-3 iki gruba ayrilir, aralarinda token tire. */
export function GroupedOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const groupAt = 3
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<React.Fragment key={i}>
{i > 0 && i % groupAt === 0 ? (
<span aria-hidden="true" className="mx-1 h-0.5 w-3 shrink-0 rounded-full bg-input" />
) : null}
<input
{...cellHandlers(ctl, i)}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
</React.Fragment>
))}
</div>
)
}
/* Masked: a token dot is shown instead of the digit; the value stays in the real input, the text is made transparent and an aria-hidden dot is drawn over it. */
export function MaskedOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<span key={i} className="relative inline-flex">
<input
{...cellHandlers(ctl, i)}
className={cn(
cellBase,
cellSize[size],
boxLook,
"caret-primary text-transparent selection:bg-transparent selection:text-transparent",
ch ? "border-primary" : "border-field-border"
)}
/>
{ch ? (
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground",
dotSize[size]
)}
/>
) : null}
</span>
))}
</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.
Four
A short four-digit code.
import { FourOtp } from "@/components/ui/input-otp-length"
<FourOtp />Six
The standard six-digit verification code.
import { SixOtp } from "@/components/ui/input-otp-length"
<SixOtp />Eight
A long eight-digit code for tighter security.
import { EightOtp } from "@/components/ui/input-otp-length"
<EightOtp />Grouped
Six digits split into two groups of three by a token dash.
import { GroupedOtp } from "@/components/ui/input-otp-length"
<GroupedOtp />Masked
Digits are masked as token dots while the real value stays in the input.
import { MaskedOtp } from "@/components/ui/input-otp-length"
<MaskedOtp />ai2 Length OTP inputs: 5 styled variations on the token system
The ai2 Length 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 in different code shapes. 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: no animation is used; only the code shape changes. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, nothing changes because there is no motion to skip.
What is in the ai2 Length OTP inputs?
5 exports in one file: Four, Six, Eight, Grouped and Masked. 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: no animation is used; only the code shape changes.
- Reduced-motion aware: Under prefers-reduced-motion, nothing changes because there is no motion to skip.
- 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 Length 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.