Skip to content
Browse documentation

A single-line hairline card composer with live Visa, Mastercard, Amex and Discover detection, 3D CVC back-stripe flip, Luhn validation and seamless field handoff.

Used forSaaS billing and plan upgradesSingle-page checkout drawersCard validation before tokenisationCorporate and virtual card entry

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/credit-card-input.json

Registered the namespace? Then it’s shadcn add @hairline/credit-card-input. Set it up

Templates

Need the whole page?

63 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

All 63 templates

Where it’s used

  • SaaS billing and plan upgrades

    Update a workspace payment method inside a compact settings row without a tall multi-field form.

  • Single-page checkout drawers

    Keep card number, MM / YY, CVC and optional ZIP on one crisp line that stays readable even on narrow viewports.

  • Card validation before tokenisation

    Catch Mod-10 Luhn typos and expired dates instantaneously with clear inline feedback before calling your payment provider.

  • Corporate and virtual card entry

    Handle both 16-digit / 3-digit CVC cards and 15-digit / 4-digit CID Amex cards automatically.

What it handles for you

Good card inputs feel effortless to type: network formatting adapts immediately, focus advances at the exact right digit, and mistakes explain themselves without erasing what you typed.

Instead of wiring upmulti-field card formcard-validator wrappercustom Luhn checkerbrand logo sprites
  1. Live vector network detection

    Detects Visa, Mastercard, Amex and Discover from BIN prefixes, switching bespoke SVG card emblems, spacing (4-4-4-4 vs 4-6-5) and CVC length (3 vs 4) automatically.

  2. 3D CVC back-stripe flip

    Focusing CVC rotates the left card emblem 180 degrees to highlight the security-code strip on the back, flipping cleanly back on blur.

  3. Real Mod-10 Luhn and expiry checks

    Validates full card numbers with real Luhn checksum math and rejects expired MM / YY dates with a damped horizontal recoil and inline alert.

  4. Smart single-line compact handoff

    Compresses a verified number into a clickable •••• 4242 chip while editing Expiry and CVC so tight containers never clip; Backspace at slot start expands it right back.

  5. Auto-padding and keyboard flow

    Auto-pads single-digit months 2 to 9 as 02 to 09, auto-advances across Number, Expiry, CVC and optional ZIP, and moves backwards cleanly on Backspace.

  6. Exported validation helpers

    Exports detectCardBrand() and isValidLuhn() alongside CreditCardInput so forms and tests share identical rules.

Overview

Multi-box payment forms waste vertical space and lose rhythm between card number, expiry and security code. CreditCardInput packs the complete payment line into one crisp hairline capsule: the left vector emblem switches dynamically as Visa, Mastercard, Amex or Discover prefixes arrive, adjusts grouping automatically between 4-4-4-4 and Amex 4-6-5, and flips 180 degrees in 3D to highlight the back security stripe the instant focus moves into CVC. Months 2 through 9 auto-pad to 02 through 09, valid Luhn numbers compress cleanly into a clickable trailing-four chip while editing Expiry and CVC, Backspace at position zero hands focus back cleanly, and a quiet emerald 8×8 Bayer floor pulse confirms the moment every field validates.

States

empty
Minimal hairline card silhouette with clean placeholders for card number, MM / YY and CVC.
network detected
Typing 4, 51 to 55, 34/37 or 6011 switches the left emblem to the matching vector mark and adapts digit grouping and CVC length.
compact handoff
Once Luhn passes and focus advances to Expiry, the number compresses cleanly into a clickable •••• 4242 pill.
CVC flipped
Focusing CVC rotates the left emblem 180 degrees to highlight the security-code zone on the card back.
verified
When Luhn, expiry and CVC (plus postal if shown) all pass, an emerald check morphs in alongside a quiet emerald 8×8 Bayer floor sweep.
invalid
A Luhn failure or expired date nudges the field with a damped horizontal recoil, rose Bayer floor pulse and inline alert.

Usage

usage.tsx
import { CreditCardInput } from "@/components/credit-card-input";<CreditCardInput  showPostal  onChange={(card) => {    setCanSubmit(card.valid);  }}/>

Works with

Billing card update form guarded by live Luhn and expiry checks

Use CreditCardInput for client-side formatting and pre-validation, or pair its state cleanly with your tokenisation workflow.

example.tsx
"use client";import { useState } from "react";import { CreditCardInput, type CardValue } from "@/components/credit-card-input";export function BillingCardForm({ onSave }: { onSave: (card: CardValue) => Promise<void> }) {  const [card, setCard] = useState<CardValue | null>(null);  return (    <form      onSubmit={(e) => {        e.preventDefault();        if (card?.valid) void onSave(card);      }}      className="space-y-3"    >      <CreditCardInput showPostal onChange={setCard} />      <button        type="submit"        disabled={!card?.valid}        className="h-10 w-full rounded-xl bg-foreground text-sm font-medium text-background disabled:opacity-40"      >        Save payment method      </button>    </form>  );}

Props

onChange
(card: CardValue) => void
Emits { number, formattedNumber, last4, brand, expMonth, expYear, cvc, postal, valid, error } on every edit.
compactOnAdvance / showPostal= true / false
boolean / boolean
Compress valid number to clickable •••• 4242 while editing Expiry/CVC, and toggle optional ZIP slot.
defaultNumber / defaultExpiry / defaultCvc
string
Optional initial values for previews or test fixtures (omit in production forms).
label / disabled / sound= "Card details" / false / false
string / boolean / boolean
Accessible group label, disabled state and opt-in Web Audio ticks.
detectCardBrand / isValidLuhn
exported utility functions
BIN network detector and Mod-10 Luhn validator exported directly from the component file.

Accessibility and motion

  • In production PCI-scoped checkouts, tokenise directly through your payment processor SDK rather than transmitting raw PANs to your own backend.
  • All card brand icons are inline SVGs with zero external image requests.
  • The 8×8 Bayer optical floor sleeps at 0% CPU at rest and wakes only for ~0.5s on valid completion or validation error.
  • Under prefers-reduced-motion: reduce, the 3D CVC flip, horizontal recoil and Bayer sweeps switch cleanly without motion.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Text morph.

Source

"use client";import * as React from "react";import {  EASE_OUT,  INTERACTION_FOCUS,  createSpring,  useInteractionActivity,  useInteractionReducedMotion,  type Spring,} from "./ui-interaction-motion";import { TextMorph } from "./text-morph";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * CREDIT CARD INPUT: single-line hairline card composer * *   network   detects Visa, Mastercard, Amex and Discover on the *             first digits, switching formatting (4-4-4-4 vs Amex *             4-6-5), CVC length (3 vs 4) and the left vector *             card emblem automatically * *   cvc flip  focusing the CVC field rotates the left card emblem *             180° in 3D to show the security-code zone on the *             back stripe (or Amex front 4-digit badge) * *   flow      auto-pads months 2..9 to 02..09, auto-advances on *             valid Luhn completion -> MM / YY -> CVC, hands focus *             back on Backspace at position 0, compresses to *             "•••• 4242" in compact spaces, and sweeps an emerald *             8×8 Bayer floor pulse when the full card validates * ───────────────────────────────────────────────────────── */export type CardBrand = "visa" | "mastercard" | "amex" | "discover" | "unknown";export interface CardValue {  /** Raw digits only (no spaces). */  number: string;  /** Formatted number (e.g. "4242 4242 4242 4242"). */  formattedNumber: string;  /** Last four digits once available. */  last4: string;  /** Detected card network. */  brand: CardBrand;  /** Two-digit expiry month ("01".."12") or partial draft. */  expMonth: string;  /** Two-digit expiry year ("27") or partial draft. */  expYear: string;  /** Security code (3 digits, or 4 for Amex). */  cvc: string;  /** Optional postal / ZIP code when `showPostal` is enabled. */  postal?: string;  /** True only when Luhn checksum, non-expired date, CVC length (and postal if shown) all pass. */  valid: boolean;  /** Specific field error message if any completed field fails validation. */  error: string | null;}export interface CreditCardInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> {  /** Fires cleanly on every edit with structured card details and validation state. */  onChange?: (card: CardValue) => void;  /** Optional initial card number digits (useful for previews/tests; omit in production). */  defaultNumber?: string;  /** Optional initial expiry in "MM/YY" format. */  defaultExpiry?: string;  /** Optional initial CVC. */  defaultCvc?: string;  /** Compress valid card number to "•••• 4242" while editing Expiry / CVC so tight layouts never clip (default true). */  compactOnAdvance?: boolean;  /** Include an inline postal / ZIP code slot at the end (default false). */  showPostal?: boolean;  /** Accessible group label (default "Card details"). */  label?: string;  /** Disabled state. */  disabled?: boolean;  /** Opt-in quiet Web Audio ticks on valid lock-in and validation error (from ui-sounds.ts). */  sound?: boolean;}const BAYER8: Float32Array = (() => {  const m = [    [0, 32, 8, 40, 2, 34, 10, 42],    [48, 16, 56, 24, 50, 18, 58, 26],    [12, 44, 4, 36, 14, 46, 6, 38],    [60, 28, 52, 20, 62, 30, 54, 22],    [3, 35, 11, 43, 1, 33, 9, 41],    [51, 19, 59, 27, 49, 17, 57, 25],    [15, 47, 7, 39, 13, 45, 5, 37],    [63, 31, 55, 23, 61, 29, 53, 21],  ];  const out = new Float32Array(64);  for (let y = 0; y < 8; y++) {    for (let x = 0; x < 8; x++) {      out[(y << 3) | x] = (m[y][x] + 0.5) / 64;    }  }  return out;})();const IS_LE = (() => {  const b = new ArrayBuffer(4);  new Uint32Array(b)[0] = 0x0a0b0c0d;  return new Uint8Array(b)[0] === 0x0d;})();function packRgba(r: number, g: number, b: number, a: number): number {  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;}const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);const clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);const onlyDigits = (s: string) => s.replace(/\D+/g, "");/** Detect card network from leading digits (BIN prefix). */export function detectCardBrand(digits: string): CardBrand {  const d = onlyDigits(digits);  if (!d) return "unknown";  if (/^4/.test(d)) return "visa";  if (/^3[47]/.test(d)) return "amex";  if (/^(5[1-5]|222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)/.test(d)) return "mastercard";  if (/^(6011|65|64[4-9])/.test(d)) return "discover";  return "unknown";}/** Standard Mod-10 Luhn checksum validation. */export function isValidLuhn(digits: string): boolean {  const d = onlyDigits(digits);  if (d.length < 13) return false;  let sum = 0;  let dbl = false;  for (let i = d.length - 1; i >= 0; i--) {    let n = d.charCodeAt(i) - 48;    if (dbl) {      n *= 2;      if (n > 9) n -= 9;    }    sum += n;    dbl = !dbl;  }  return sum % 10 === 0;}function cardMaxDigits(brand: CardBrand): number {  return brand === "amex" ? 15 : 16;}function cardCvcLength(brand: CardBrand): number {  return brand === "amex" ? 4 : 3;}function formatCardNumber(digits: string, brand: CardBrand): string {  const d = onlyDigits(digits).slice(0, cardMaxDigits(brand));  if (brand === "amex") {    const p1 = d.slice(0, 4);    const p2 = d.slice(4, 10);    const p3 = d.slice(10, 15);    return [p1, p2, p3].filter(Boolean).join(" ");  }  const groups: string[] = [];  for (let i = 0; i < d.length; i += 4) groups.push(d.slice(i, i + 4));  return groups.join(" ");}function caretAfterDigits(formatted: string, digitCount: number): number {  if (digitCount <= 0) return 0;  let seen = 0;  for (let i = 0; i < formatted.length; i++) {    if (formatted[i] >= "0" && formatted[i] <= "9") {      seen++;      if (seen === digitCount) return i + 1;    }  }  return formatted.length;}function validateExpiry(mm: string, yy: string): { complete: boolean; valid: boolean; reason: string | null } {  if (mm.length < 2 || yy.length < 2) return { complete: false, valid: false, reason: null };  const m = Number(mm);  const y = Number(yy);  if (!Number.isInteger(m) || m < 1 || m > 12) {    return { complete: true, valid: false, reason: "Enter a valid expiry month." };  }  const now = new Date();  const curY = now.getFullYear() % 100;  const curM = now.getMonth() + 1;  if (y < curY || (y === curY && m < curM)) {    return { complete: true, valid: false, reason: "Card has expired." };  }  return { complete: true, valid: true, reason: null };}function CardEmblem({ brand, flipped, reduced }: { brand: CardBrand; flipped: boolean; reduced: boolean }) {  return (    <span className="relative inline-block h-[20px] w-[30px] shrink-0" style={{ perspective: "220px" }} aria-hidden="true">      <span        className="relative block h-full w-full"        style={{          transformStyle: "preserve-3d",          transform: flipped ? "rotateY(180deg)" : "rotateY(0deg)",          transition: reduced ? "none" : `transform 360ms ${EASE_OUT}`,        }}      >        {/* Front face: dynamic bespoke vector card emblem */}        <span          className="absolute inset-0 flex items-center justify-center overflow-hidden rounded-[4.5px] border border-border bg-background"          style={{ backfaceVisibility: "hidden" }}        >          {brand === "visa" ? (            <svg width="30" height="20" viewBox="0 0 30 20" fill="none">              <rect width="30" height="20" fill="#1A369B" />              <text x="15" y="13.2" textAnchor="middle" fill="#FFFFFF" fontSize="8" fontWeight="700" fontStyle="italic" fontFamily="system-ui, sans-serif" letterSpacing="0.4">                VISA              </text>            </svg>          ) : brand === "mastercard" ? (            <svg width="30" height="20" viewBox="0 0 30 20" fill="none">              <rect width="30" height="20" fill="#18181B" />              <circle cx="12" cy="10" r="5" fill="#EB001B" />              <circle cx="18" cy="10" r="5" fill="#F79E1B" fillOpacity="0.92" />            </svg>          ) : brand === "amex" ? (            <svg width="30" height="20" viewBox="0 0 30 20" fill="none">              <rect width="30" height="20" fill="#0F769E" />              <text x="15" y="12.8" textAnchor="middle" fill="#FFFFFF" fontSize="6.5" fontWeight="700" fontFamily="system-ui, sans-serif" letterSpacing="0.3">                AMEX              </text>            </svg>          ) : brand === "discover" ? (            <svg width="30" height="20" viewBox="0 0 30 20" fill="none">              <rect width="30" height="20" fill="#1E293B" />              <circle cx="24" cy="16" r="7" fill="#F97316" />              <rect x="4" y="6" width="11" height="2" rx="1" fill="#E2E8F0" />            </svg>          ) : (            <svg width="30" height="20" viewBox="0 0 30 20" fill="none" className="text-muted-foreground">              <rect x="3.5" y="4.5" width="7" height="4.5" rx="1" stroke="currentColor" strokeWidth="1.1" strokeOpacity="0.6" />              <line x1="3.5" y1="14" x2="12" y2="14" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeOpacity="0.45" />              <line x1="15" y1="14" x2="22" y2="14" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeOpacity="0.3" />            </svg>          )}        </span>        {/* Back face: magnetic stripe + highlighted security code zone when focused on CVC */}        <span          className="absolute inset-0 flex items-center justify-center overflow-hidden rounded-[4.5px] border border-border bg-muted"          style={{ backfaceVisibility: "hidden", transform: "rotateY(180deg)" }}        >          <svg width="30" height="20" viewBox="0 0 30 20" fill="none">            <rect width="30" height="20" className="fill-zinc-800 dark:fill-zinc-900" />            <rect y="3.5" width="30" height="4" className="fill-zinc-950" />            <rect x="3" y="10.5" width="15" height="4.5" rx="1" className="fill-zinc-600/70" />            <rect x="19.5" y="10" width="7.5" height="5.5" rx="1.2" fill="#3B82F6" fillOpacity="0.28" stroke="#60A5FA" strokeWidth="1" />          </svg>        </span>      </span>    </span>  );}export function CreditCardInput({  onChange,  defaultNumber = "",  defaultExpiry = "",  defaultCvc = "",  compactOnAdvance = true,  showPostal = false,  label = "Card details",  disabled = false,  sound = false,  className = "",  ...props}: CreditCardInputProps) {  const reduced = useInteractionReducedMotion();  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();  const [numDigits, setNumDigits] = React.useState(() => onlyDigits(defaultNumber).slice(0, 16));  const [expDigits, setExpDigits] = React.useState(() => onlyDigits(defaultExpiry).slice(0, 4));  const [cvcDigits, setCvcDigits] = React.useState(() => onlyDigits(defaultCvc).slice(0, 4));  const [postal, setPostal] = React.useState("");  const [activeSlot, setActiveSlot] = React.useState<"number" | "expiry" | "cvc" | "postal" | null>(null);  const [liveStatus, setLiveStatus] = React.useState("");  const shellRef = React.useRef<HTMLDivElement>(null);  const numberRef = React.useRef<HTMLInputElement>(null);  const expiryRef = React.useRef<HTMLInputElement>(null);  const cvcRef = React.useRef<HTMLInputElement>(null);  const postalRef = React.useRef<HTMLInputElement>(null);  const floorCanvasRef = React.useRef<HTMLCanvasElement>(null);  const recoilRef = React.useRef<Spring | null>(null);  const flashRef = React.useRef<((kind: "valid" | "error") => void) | null>(null);  const brand = React.useMemo(() => detectCardBrand(numDigits), [numDigits]);  const maxNumLen = cardMaxDigits(brand);  const reqCvcLen = cardCvcLength(brand);  const cleanNum = numDigits.slice(0, maxNumLen);  const formattedNumber = React.useMemo(() => formatCardNumber(cleanNum, brand), [cleanNum, brand]);  const numComplete = cleanNum.length === maxNumLen;  const numValid = numComplete && isValidLuhn(cleanNum);  const numError = numComplete && !numValid ? "Check the card number." : null;  const expMonth = expDigits.slice(0, 2);  const expYear = expDigits.slice(2, 4);  const formattedExpiry = expDigits.length > 2 ? `${expMonth} / ${expYear}` : expMonth;  const expCheck = React.useMemo(() => validateExpiry(expMonth, expYear), [expMonth, expYear]);  const cleanCvc = cvcDigits.slice(0, reqCvcLen);  const cvcValid = cleanCvc.length === reqCvcLen;  const postalValid = !showPostal || postal.trim().length >= 3;  const fieldError = numError ?? (expCheck.complete && !expCheck.valid ? expCheck.reason : null);  const allValid = numValid && expCheck.valid && cvcValid && postalValid;  // Compact the valid card number cleanly to "•••• 4242" while editing Expiry / CVC / Postal so nothing ever clips!  const isCompact = compactOnAdvance && numValid && activeSlot !== "number";  const prevValidRef = React.useRef(allValid);  const prevErrRef = React.useRef<string | null>(fieldError);  // Horizontal spring recoil on invalid Luhn or expired card  React.useEffect(() => {    const sp = createSpring(      0,      { stiffness: 450, damping: 17 },      () => {        const el = shellRef.current;        if (!el) return;        const x = sp.get();        el.style.transform = Math.abs(x) > 0.04 ? `translate3d(${x.toFixed(2)}px, 0, 0)` : "";      },      0.04,    );    recoilRef.current = sp;    return () => {      sp.stop();      recoilRef.current = null;    };  }, []);  // Optical 8×8 Bayer floor pulse (wakes strictly for ~0.5s on valid card or error -> 0% CPU at rest!)  React.useEffect(() => {    const canvas = floorCanvasRef.current;    const ctx = canvas?.getContext("2d");    if (!canvas || !ctx) return;    const gridCanvas = document.createElement("canvas");    const gridCtx = gridCanvas.getContext("2d");    if (!gridCtx) return;    let raf = 0;    let kind: "none" | "valid" | "error" = "none";    let age = 0;    let last = 0;    let gCols = 0;    let gRows = 0;    let gridImg: ImageData | null = null;    let gridU32: Uint32Array | null = null;    const tick = (now: number) => {      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;      last = now;      age += dt;      const life = kind === "error" ? 0.45 : 0.56;      if (age >= life || !onScreen || reduced) {        kind = "none";        raf = 0;        ctx.clearRect(0, 0, canvas.width, canvas.height);        return;      }      const rect = canvas.getBoundingClientRect();      const w = Math.round(rect.width);      const h = Math.round(rect.height);      if (w > 0 && h > 0) {        const dpr = Math.min(2, window.devicePixelRatio || 1);        if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {          canvas.width = Math.round(w * dpr);          canvas.height = Math.round(h * dpr);        }        const pitch = 1.5;        const cols = Math.max(1, Math.ceil(w / pitch));        const rows = Math.max(1, Math.ceil(h / pitch));        if (cols !== gCols || rows !== gRows || !gridImg || !gridU32) {          gCols = cols;          gRows = rows;          gridCanvas.width = cols;          gridCanvas.height = rows;          gridImg = gridCtx.createImageData(cols, rows);          gridU32 = new Uint32Array(gridImg.data.buffer);        }        const u32 = gridU32;        u32.fill(0);        const k = age / life;        const fade = Math.sin(Math.PI * Math.pow(k, 0.72));        const front = (1 - Math.pow(1 - k, 2.2)) * 1.18 - 0.06;        const rgb: [number, number, number] = kind === "error" ? [239, 68, 68] : [52, 211, 153];        for (let r = 0; r < rows; r++) {          const v = (r + 0.5) / rows;          const floorV = Math.pow(v, 1.7);          const bRow = (r & 7) << 3;          const rowOff = r * cols;          for (let c = 0; c < cols; c++) {            const u = (c + 0.5) / cols;            let boost = 0;            if (kind === "error") {              boost = floorV * (0.45 + 0.55 * (1 - Math.abs(u - 0.5) * 1.6)) * fade;            } else {              const df = u - front;              const lead = Math.exp(-(df * df) / 0.02);              const tail = df < 0 ? Math.exp(df / 0.22) * 0.48 : 0;              boost = floorV * (lead + tail) * fade;            }            const bayer = BAYER8[bRow | (c & 7)];            const hit = clamp01((boost * 0.85 - bayer + 0.05) / 0.14);            if (hit > 0.02) {              u32[rowOff + c] = packRgba(rgb[0], rgb[1], rgb[2], hit * 0.74 * 255);            }          }        }        gridCtx.putImageData(gridImg, 0, 0);        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);        ctx.clearRect(0, 0, w, h);        ctx.imageSmoothingEnabled = false;        ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch);      }      raf = requestAnimationFrame(tick);    };    flashRef.current = (nextKind) => {      if (reduced || !onScreen) return;      kind = nextKind;      age = 0;      last = 0;      if (!raf) raf = requestAnimationFrame(tick);    };    return () => {      flashRef.current = null;      cancelAnimationFrame(raf);    };  }, [onScreen, reduced]);  // Emit structured CardValue on changes + trigger subtle optical confirmation / recoil strictly on transitions  React.useEffect(() => {    onChange?.({      number: cleanNum,      formattedNumber,      last4: cleanNum.length >= 4 ? cleanNum.slice(-4) : "",      brand,      expMonth,      expYear,      cvc: cleanCvc,      ...(showPostal ? { postal } : {}),      valid: allValid,      error: fieldError,    });  }, [cleanNum, formattedNumber, brand, expMonth, expYear, cleanCvc, postal, showPostal, allValid, fieldError, onChange]);  React.useEffect(() => {    if (allValid && !prevValidRef.current) {      flashRef.current?.("valid");      if (sound) playSound("success", 0.36);    }    prevValidRef.current = allValid;  }, [allValid, sound]);  React.useEffect(() => {    if (fieldError && fieldError !== prevErrRef.current) {      if (!reduced) recoilRef.current?.push(145);      flashRef.current?.("error");      if (sound) playSound("error", 0.34);    }    prevErrRef.current = fieldError;  }, [fieldError, reduced, sound]);  const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {    const el = e.currentTarget;    const raw = el.value;    const sel = el.selectionStart ?? raw.length;    const digitsBefore = onlyDigits(raw.slice(0, sel)).length;    const nextDigits = onlyDigits(raw);    const nextBrand = detectCardBrand(nextDigits);    const nextMax = cardMaxDigits(nextBrand);    const clamped = nextDigits.slice(0, nextMax);    setNumDigits(clamped);    const nextFmt = formatCardNumber(clamped, nextBrand);    const nextCaret = caretAfterDigits(nextFmt, Math.min(digitsBefore, clamped.length));    if (clamped.length === nextMax && isValidLuhn(clamped)) {      if (sound) playSound("tick", 0.28);      setLiveStatus(`${nextBrand === "unknown" ? "Card" : nextBrand} ending in ${clamped.slice(-4)} verified. Enter expiry date.`);      window.requestAnimationFrame(() => expiryRef.current?.focus());    } else {      window.requestAnimationFrame(() => {        if (numberRef.current) numberRef.current.setSelectionRange(nextCaret, nextCaret);      });    }  };  const handleExpiryChange = (e: React.ChangeEvent<HTMLInputElement>) => {    let raw = onlyDigits(e.currentTarget.value).slice(0, 4);    // Auto-pad months 2..9 to 02..09 as the first digit arrives    if (raw.length === 1 && Number(raw) >= 2 && expDigits.length === 0) {      raw = `0${raw}`;    }    setExpDigits(raw);    if (raw.length === 4) {      const check = validateExpiry(raw.slice(0, 2), raw.slice(2, 4));      if (check.valid) {        if (sound) playSound("tick", 0.26);        window.requestAnimationFrame(() => cvcRef.current?.focus());      }    }  };  const handleCvcChange = (e: React.ChangeEvent<HTMLInputElement>) => {    const raw = onlyDigits(e.currentTarget.value).slice(0, reqCvcLen);    setCvcDigits(raw);    if (raw.length === reqCvcLen && showPostal) {      window.requestAnimationFrame(() => postalRef.current?.focus());    }  };  const expandNumber = () => {    setActiveSlot("number");    window.requestAnimationFrame(() => {      const el = numberRef.current;      if (el) {        el.focus();        el.setSelectionRange(el.value.length, el.value.length);      }    });  };  const hasFocus = activeSlot !== null;  const [lastError, setLastError] = React.useState<string>("");  if (fieldError && fieldError !== lastError) {    setLastError(fieldError);  }  return (    <div ref={rootRef} role="group" aria-label={label} className={`@container flex w-full flex-col ${className}`} {...props}>      <div        ref={shellRef}        data-brand={brand}        data-valid={allValid ? "true" : "false"}        data-cvc-flipped={activeSlot === "cvc" ? "true" : "false"}        className={`relative flex w-full flex-col overflow-hidden rounded-[13px] border bg-card text-card-foreground transition-[border-color,box-shadow] duration-200 shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] @[440px]:h-11 @[440px]:flex-row @[440px]:items-center @[440px]:px-3 ${          fieldError            ? "border-red-500/45 dark:border-red-400/45"            : hasFocus              ? "border-foreground/25"              : "border-border hover:border-foreground/20"        } ${disabled ? "opacity-55" : ""}`}      >        {/* Optical 8×8 Bayer floor pulse (0% CPU at rest) */}        <canvas          ref={floorCanvasRef}          aria-hidden="true"          className="pointer-events-none absolute inset-x-1 bottom-1 z-0 h-5 w-[calc(100%_-_8px)] rounded-b-[9px]"        />        {/* Row 1 (mobile) / Left section (desktop): Network emblem + Card number */}        <div className="relative z-10 flex h-11 min-w-0 flex-1 items-center px-3 @[440px]:h-full @[440px]:px-0">          {/* Dynamic network emblem -> flips 180° to CVC back-stripe when CVC has focus */}          <span className="mr-2.5 flex shrink-0 items-center">            <CardEmblem brand={brand} flipped={activeSlot === "cvc"} reduced={reduced} />          </span>          {/* Card number slot (smoothly compresses to clickable "•••• 4242" pill when advancing on wide layouts) */}          {isCompact ? (            <button              type="button"              disabled={disabled}              aria-label={`Card ending in ${cleanNum.slice(-4)}. Click to edit card number.`}              onClick={expandNumber}              className={`mr-1 inline-flex h-7 shrink-0 cursor-pointer items-center gap-1 rounded-[7px] bg-muted/60 px-2 font-mono text-[13px] tabular-nums text-foreground transition-colors hover:bg-accent ${INTERACTION_FOCUS}`}            >              <span className="tracking-[0.12em] text-muted-foreground">••••</span>              <span>{cleanNum.slice(-4)}</span>            </button>          ) : (            <input              ref={numberRef}              type="text"              inputMode="numeric"              autoComplete="cc-number"              disabled={disabled}              aria-label="Card number"              aria-invalid={Boolean(numError) || undefined}              placeholder="1234 5678 9012 3456"              value={formattedNumber}              onChange={handleNumberChange}              onFocus={() => setActiveSlot("number")}              onBlur={() => setActiveSlot((s) => (s === "number" ? null : s))}              className={`h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13.5px] tracking-[-0.01em] tabular-nums placeholder:text-muted-foreground/45 focus:outline-none ${                numError ? "text-red-600 dark:text-red-400" : "text-foreground"              }`}            />          )}          {/* Drawn verification check (mobile top-right slot) */}          <span            aria-hidden="true"            className="ml-2 flex size-5 shrink-0 items-center justify-center text-emerald-600 dark:text-emerald-400 @[440px]:hidden"          >            <svg viewBox="0 0 16 16" fill="none" className="size-4">              <path                d="M3.25 8.5 6.5 11.75 12.75 4.75"                stroke="currentColor"                strokeWidth="2.1"                strokeLinecap="round"                strokeLinejoin="round"                pathLength={1}                style={{                  strokeDasharray: 1,                  strokeDashoffset: allValid ? 0 : 1,                  opacity: allValid ? 1 : 0,                  transition: reduced ? "none" : `stroke-dashoffset 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,                }}              />            </svg>          </span>        </div>        {/* Row 2 (mobile, full hairline tier so MM/YY, CVC and ZIP never clip) / Right group (desktop) */}        <div          className={`relative z-10 flex h-10 shrink-0 items-center border-t border-border/75 px-3 @[440px]:h-full @[440px]:border-t-0 @[440px]:px-0 ${            isCompact ? "@[440px]:flex-1 @[440px]:justify-end" : ""          }`}        >          <span aria-hidden="true" className="mx-2 hidden h-4 w-px bg-border/80 @[440px]:block" />          <input            ref={expiryRef}            type="text"            inputMode="numeric"            autoComplete="cc-exp"            disabled={disabled}            aria-label="Expiry date"            aria-invalid={Boolean(expCheck.complete && !expCheck.valid) || undefined}            placeholder="MM / YY"            value={formattedExpiry}            onChange={handleExpiryChange}            onKeyDown={(e) => {              if (e.key === "Backspace" && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {                e.preventDefault();                expandNumber();              }            }}            onFocus={() => setActiveSlot("expiry")}            onBlur={() => setActiveSlot((s) => (s === "expiry" ? null : s))}            className={`h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13.5px] tabular-nums placeholder:text-muted-foreground/45 focus:outline-none @[440px]:w-[62px] @[440px]:flex-none ${              expCheck.complete && !expCheck.valid ? "text-red-600 dark:text-red-400" : "text-foreground"            }`}          />          <span aria-hidden="true" className="mx-2.5 h-4 w-px shrink-0 bg-border/80 @[440px]:mx-2" />          <input            ref={cvcRef}            type="text"            inputMode="numeric"            autoComplete="cc-csc"            disabled={disabled}            aria-label={brand === "amex" ? "4-digit security code" : "3-digit security code"}            placeholder={brand === "amex" ? "CID" : "CVC"}            value={cleanCvc}            onChange={handleCvcChange}            onKeyDown={(e) => {              if (e.key === "Backspace" && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {                e.preventDefault();                expiryRef.current?.focus();              }            }}            onFocus={() => setActiveSlot("cvc")}            onBlur={() => setActiveSlot((s) => (s === "cvc" ? null : s))}            className="h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13.5px] tabular-nums text-foreground placeholder:text-muted-foreground/45 focus:outline-none @[440px]:w-[40px] @[440px]:flex-none"          />          {showPostal && (            <>              <span aria-hidden="true" className="mx-2.5 h-4 w-px shrink-0 bg-border/80 @[440px]:mx-2" />              <input                ref={postalRef}                type="text"                autoComplete="postal-code"                disabled={disabled}                aria-label="Postal code"                placeholder="ZIP"                value={postal}                onChange={(e) => setPostal(e.currentTarget.value.slice(0, 10))}                onKeyDown={(e) => {                  if (e.key === "Backspace" && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {                    e.preventDefault();                    cvcRef.current?.focus();                  }                }}                onFocus={() => setActiveSlot("postal")}                onBlur={() => setActiveSlot((s) => (s === "postal" ? null : s))}                className="h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13px] text-foreground placeholder:text-muted-foreground/45 focus:outline-none @[440px]:w-[58px] @[440px]:flex-none"              />            </>          )}          {/* Drawn verification check (desktop right slot) */}          <span            aria-hidden="true"            className="ml-1 hidden size-5 shrink-0 items-center justify-center text-emerald-600 dark:text-emerald-400 @[440px]:flex"          >            <svg viewBox="0 0 16 16" fill="none" className="size-4">              <path                d="M3.25 8.5 6.5 11.75 12.75 4.75"                stroke="currentColor"                strokeWidth="2.1"                strokeLinecap="round"                strokeLinejoin="round"                pathLength={1}                style={{                  strokeDasharray: 1,                  strokeDashoffset: allValid ? 0 : 1,                  opacity: allValid ? 1 : 0,                  transition: reduced ? "none" : `stroke-dashoffset 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,                }}              />            </svg>          </span>        </div>      </div>      {/* Inline validation error fold (keeps last error while folding shut so text never vanishes mid-close) */}      <div        aria-hidden={!fieldError || undefined}        className={`grid ${!fieldError ? "pointer-events-none" : ""}`}        style={{          gridTemplateRows: fieldError ? "1fr" : "0fr",          opacity: fieldError ? 1 : 0,          transition: reduced ? "none" : `grid-template-rows 280ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,        }}      >        <div className="min-h-0 overflow-hidden">          <p role="alert" className="px-1 pt-1.5 text-[12px] leading-5 text-red-600 dark:text-red-400">            <TextMorph animateWidth={false}>{fieldError ?? lastError}</TextMorph>          </p>        </div>      </div>      <span className="sr-only" role="status" aria-live="polite">        {liveStatus}      </span>    </div>  );}export default CreditCardInput;

Registry item: /r/credit-card-input.json