State OTP inputs
Five one-time-code inputs that keep the same slots and vary only the state feedback: a success look, the standard aria-invalid danger look, a fixed-timeout verifying spinner, a locked and disabled entry, and a complete state that reveals a check. 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-stateDependencies, the @ai2/tokens theme and the component file are installed together.
Install dependencies
npm install lucide-reactCopy the source
components/ui/input-otp-state.tsx"use client"
import * as React from "react"
import { Check, Loader2, Lock } from "lucide-react"
import { cn } from "@/lib/utils"
/* State OTP family: 5 state presentations (valid, invalid, loading, locked,
complete). The difference is ONLY in the state feedback: a success border, the
aria-invalid danger appearance, a fixed-duration verification spinner,
locked/disabled cells, and a checkmark that appears once the code is complete.
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; the invalid appearance comes from the ai2 danger
tone. 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"
const boxLook = "rounded-md border focus-visible:border-ring"
const invalidLook =
"aria-invalid:border-danger aria-invalid:ring-danger/20 dark:aria-invalid:ring-danger/40"
const iconBase = "shrink-0 [&_svg]:size-4 [&_svg]:shrink-0 [&_i]:text-base [&_i]:leading-none"
/* 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()
}
const isComplete = chars.every((c) => c !== "")
return { chars, refs, setAt, onKey, onPaste, isComplete }
}
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}`,
}
}
/* Valid: dolan her hucre success kenarligi ve yumusak success dolgusu alir. */
export function ValidOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
return (
<div
data-slot="styled-input-otp"
data-tone="success"
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,
"focus-visible:border-success focus-visible:ring-success/40",
ch
? "border-success bg-[color-mix(in_oklab,var(--color-success)_12%,transparent)]"
: "border-field-border"
)}
/>
))}
</div>
)
}
/* Invalid: the rejected-code appearance; the cells carry aria-invalid and take the standard danger border and ring styling. The helper text is wired through aria-describedby. */
export function InvalidOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const msgId = React.useId()
return (
<div
data-slot="styled-input-otp"
data-tone="danger"
role="group"
aria-label="Verification code"
className={cn("inline-flex flex-col items-start gap-2", className)}
>
<div className={rootBase}>
{ctl.chars.map((ch, i) => (
<input
key={i}
{...cellHandlers(ctl, i)}
aria-invalid="true"
aria-describedby={msgId}
className={cn(
cellBase,
cellSize[size],
boxLook,
invalidLook,
ch ? "bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)]" : null
)}
/>
))}
</div>
<p id={msgId} className="text-sm text-danger">
That code is not correct. Please try again.
</p>
</div>
)
}
/* Loading: once the code is complete a fixed-duration verification simulation runs; the cells lock and a spinner appears. The timeout is cleared on cleanup. */
export function LoadingOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const [verifying, setVerifying] = React.useState(false)
const statusId = React.useId()
const complete = ctl.isComplete
React.useEffect(() => {
if (!complete) {
setVerifying(false)
return
}
setVerifying(true)
const id = window.setTimeout(() => setVerifying(false), 1600)
return () => window.clearTimeout(id)
}, [complete])
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
aria-describedby={statusId}
aria-busy={verifying || undefined}
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<input
key={i}
{...cellHandlers(ctl, i)}
disabled={verifying}
className={cn(cellBase, cellSize[size], boxLook, ch ? "border-primary" : "border-field-border")}
/>
))}
<span
id={statusId}
role="status"
aria-live="polite"
className={cn(iconBase, "ml-1 inline-flex items-center gap-2 text-sm text-muted-foreground")}
>
{verifying ? (
<>
<Loader2 className="animate-spin" />
Verifying
</>
) : null}
</span>
</div>
)
}
/* Locked: kilitli/disabled kod girisi; hucreler devre disi, yaninda kilit ikonu. */
export function LockedOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const msgId = React.useId()
return (
<div
data-slot="styled-input-otp"
role="group"
aria-label="Verification code"
aria-describedby={msgId}
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<input
key={i}
{...cellHandlers(ctl, i)}
disabled
className={cn(cellBase, cellSize[size], boxLook, "bg-muted", ch ? "border-primary" : "border-field-border")}
/>
))}
<span
id={msgId}
className={cn(iconBase, "ml-1 inline-flex items-center gap-2 text-sm text-muted-foreground")}
>
<Lock />
Locked
</span>
</div>
)
}
/* Complete: tum haneler dolunca hucreler success'e doner ve onay isareti cikar. */
export function CompleteOtp({ className, size = "md", length = 6, value, defaultValue, onValueChange }: OtpProps) {
const ctl = useOtpCode(length, { value, defaultValue, onValueChange })
const statusId = React.useId()
const done = ctl.isComplete
return (
<div
data-slot="styled-input-otp"
data-tone={done ? "success" : "neutral"}
role="group"
aria-label="Verification code"
aria-describedby={statusId}
className={cn(rootBase, className)}
>
{ctl.chars.map((ch, i) => (
<input
key={i}
{...cellHandlers(ctl, i)}
className={cn(
cellBase,
cellSize[size],
boxLook,
done
? "border-success bg-[color-mix(in_oklab,var(--color-success)_12%,transparent)] focus-visible:border-success focus-visible:ring-success/40"
: ch
? "border-primary"
: "border-field-border"
)}
/>
))}
<span
id={statusId}
role="status"
aria-live="polite"
className={cn(iconBase, "ml-1 inline-flex items-center gap-2 text-sm text-success")}
>
{done ? (
<>
<Check />
Code complete
</>
) : 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.
Valid
Filled slots take the success border and fill.
import { ValidOtp } from "@/components/ui/input-otp-state"
<ValidOtp />Invalid
A rejected code with the standard aria-invalid danger look and a linked message.
That code is not correct. Please try again.
import { InvalidOtp } from "@/components/ui/input-otp-state"
<InvalidOtp />That code is not correct. Please try again.
That code is not correct. Please try again.
That code is not correct. Please try again.
That code is not correct. Please try again.
Loading
Completing the code locks the slots and runs a fixed-timeout verify spinner.
import { LoadingOtp } from "@/components/ui/input-otp-state"
<LoadingOtp />Locked
A disabled code entry with a lock marker.
import { LockedOtp } from "@/components/ui/input-otp-state"
<LockedOtp />Complete
Filling every digit turns the slots success and reveals a check.
import { CompleteOtp } from "@/components/ui/input-otp-state"
<CompleteOtp />ai2 State OTP inputs: 5 styled variations on the token system
The ai2 State 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 that reflects a validation state. 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: the loading spinner rotates while the code is verified. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, the spinner keeps rotating on purpose because a frozen spinner reads as a hang.
What is in the ai2 State OTP inputs?
5 exports in one file: Valid, Invalid, Loading, Locked and Complete. 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: the loading spinner rotates while the code is verified.
- Reduced-motion aware: Under prefers-reduced-motion, the spinner keeps rotating on purpose because a frozen spinner reads as a hang.
- 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 State 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.