Backup codesNew
A 2FA recovery codes panel with 1.5px 8×8 Bayer secret veiling, copy-while-veiled, .txt export, used-code audit stamps and inline regeneration.
Used for2FA and MFA enrolmentAccount security settingsPasskey and authenticator fallbackEnterprise recovery rotation
Install with the shadcn CLI
$ npxnpx shadcn@latest add https://hairlineui.com/r/backup-codes.jsonRegistered the namespace? Then it’s shadcn add @hairline/backup-codes. 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.
Where it’s used
2FA and MFA enrolment
Present newly minted recovery codes with one-click Copy all, .txt file download and print actions before completing setup.
Account security settings
Keep active codes veiled by default while showing exactly how many remain and which ones were already used.
Passkey and authenticator fallback
Pair directly with Passkey button, Sudo gate and Verify code to complete your authentication surface.
Enterprise recovery rotation
Guard code rotation behind an inline two-step confirmation so operators never invalidate active codes by misclick.
What it handles for you
Recovery codes only protect an account if users can save them effortlessly without exposing them on screen or losing track of how many remain.
- 01
Per-slot 8×8 Bayer secret veil
Unused recovery codes stay concealed behind crisp 1.5px Bayer grain at rest; click any slot to peek one code or Reveal codes to open the sheet.
- 02
Copy all while veiled with emerald wave
Copies every unused code straight to the clipboard without exposing them on screen, confirming with a staggered emerald Bayer wavefront across the grid.
- 03
Real .txt download and print sheet
Generates a formatted plain-text recovery file with issuer, account, date and numbered codes via Blob download, plus a clean print sheet helper.
- 04
Used stamps and low-capacity warning
Redeemed codes render struck through in a recessed slot while an amber notice warns automatically when remaining codes reach lowThreshold.
- 05
Two-step inline Regenerate guard
Clicking Regenerate opens an inline hairline confirmation bar inside the footer with loading state and zero native browser alerts.
- 06
Unambiguous code generator included
Exports generateBackupCodes() using crypto.getRandomValues without ambiguous 0/O/1/I/L characters alongside formatBackupCodesFile().
Overview
Two-factor recovery sheets are usually dumped into an exposed preformatted box with a browser confirm dialog for rotation. BackupCodes wraps one-time recovery codes in real account-security ergonomics: unused codes start veiled behind individual 1.5px 8×8 Bayer optical panes (0% CPU at rest) so screen shares stay safe, while already-redeemed codes stay visibly struck through with used timestamps so remaining capacity is auditable at a glance. Copy all lifts every unused code directly to the clipboard even while veiled with a staggered emerald Bayer wavefront, Download .txt exports a formatted plain-text recovery file with issuer and account metadata, low remaining counts surface an amber warning, and Regenerate confirms in place without browser popups.
States
- veiled grid
- Unused codes sit behind individual 1.5px 8×8 Bayer panes while already-used codes remain visibly struck through so counts stay legible.
- copy while veiled
- Copy all writes unused codes to the clipboard and ripples a staggered emerald Bayer sweep across the veiled cells.
- revealed
- Codes display in crisp monospace with single-click individual copy and hover Use controls when onToggleUsed is wired.
- low remaining
- When unused codes fall at or below lowThreshold, the header count shifts amber and an inline warning banner prompts rotation.
- confirm regenerate
- The footer turns into an inline hairline confirmation bar with Cancel and async Confirm states.
Usage
import { BackupCodes } from "@/components/backup-codes";<BackupCodes codes={codes} issuer="Acme" account="alex@acme.dev" onRegenerate={async () => { const fresh = await regenerateOnServer(); setCodes(fresh); }}/>Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.
Works with
Wired to a server 2FA rotation endpoint
Generate and hash recovery codes on the server, pass the plaintext batch to BackupCodes once, and wire onRegenerate to rotate.
"use client";import { useState } from "react";import { BackupCodes, type BackupCodeItem } from "@/components/backup-codes";export function SecurityRecoverySection({ initial }: { initial: BackupCodeItem[] }) { const [codes, setCodes] = useState<BackupCodeItem[]>(initial); return ( <BackupCodes codes={codes} issuer="Acme Cloud" account="alex@acme.dev" filename="acme-recovery-codes.txt" onRegenerate={async () => { const res = await fetch("/api/auth/2fa/backup-codes", { method: "POST" }); if (!res.ok) throw new Error("Failed to rotate codes"); setCodes(await res.json()); }} /> );}Props
| Prop | Type | Description |
|---|---|---|
| codes | Array<string | BackupCodeItem> | Recovery codes as plain strings or { code, used?, usedAt? } objects. |
| issuer / account / filename | string= "Hairline" / — / "recovery-codes.txt" | Metadata written into downloaded .txt exports and print sheets. |
| defaultVeiled / allowCopyIndividual | boolean= true / true | Start veiled behind Bayer grain and allow one-click copying of individual revealed codes. |
| onRegenerate / onToggleUsed | () => Promise<void> | void / (code, used) => void | Enable the inline two-step Regenerate confirmation and per-code used toggling. |
| lowThreshold / onDownload / onPrint / sound | number / fn / fn / boolean= 2 / built-in / built-in / false | Low-remaining warning threshold, custom export hooks and opt-in Web Audio cues. |
- codes
- Array<string | BackupCodeItem>
- Recovery codes as plain strings or { code, used?, usedAt? } objects.
- issuer / account / filename= "Hairline" / — / "recovery-codes.txt"
- string
- Metadata written into downloaded .txt exports and print sheets.
- defaultVeiled / allowCopyIndividual= true / true
- boolean
- Start veiled behind Bayer grain and allow one-click copying of individual revealed codes.
- onRegenerate / onToggleUsed
- () => Promise<void> | void / (code, used) => void
- Enable the inline two-step Regenerate confirmation and per-code used toggling.
- lowThreshold / onDownload / onPrint / sound= 2 / built-in / built-in / false
- number / fn / fn / boolean
- Low-remaining warning threshold, custom export hooks and opt-in Web Audio cues.
Accessibility and motion
- Veiled slots paint static 1.5px 8×8 Bayer canvases at rest (0 rAF loops / 0% CPU) and run a brief ~0.5s emerald sweep only when Copy all, Download .txt or Regenerate fires.
- generateBackupCodes() omits 0, O, 1, I and L so printed or handwritten recovery codes cannot be misread.
- Under prefers-reduced-motion: reduce, Bayer sweeps stay still while all reveal, copy, export and regenerate flows work unchanged.
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, Number roll.
Source
"use client";import * as React from "react";import { AlertTriangle, Check, Copy, Download, Eye, EyeOff, Loader2, Printer, RefreshCw, ShieldCheck,} from "lucide-react";import { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS, interactionIcon, useInteractionActivity, useInteractionReducedMotion,} from "./ui-interaction-motion";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * BACKUP CODES: 2FA recovery codes vault with Bayer veiling * * veil active recovery codes sit behind a 1.5px 8×8 Bayer * optical veil by default (0% CPU at rest, crisp dark * and light) while already-used codes remain visibly * struck through so remaining count is auditable even * on screen share * * copy Copy all writes all unused codes directly to the * clipboard even while veiled and sweeps an emerald * Bayer wavefront across the veiled slots; individual * revealed codes copy with one click * * infra ships real .txt Blob export, print sheet helper, * cryptographically clean generateBackupCodes(), low- * remaining amber warning and an inline two-step * Regenerate confirmation with zero browser dialogs * ───────────────────────────────────────────────────────── */export interface BackupCodeItem { /** Formatted recovery code (e.g. "k7m2-9x4p"). */ code: string; /** Whether this recovery code has already been redeemed. */ used?: boolean; /** Optional label shown when used (e.g. "Used 14 Nov"). */ usedAt?: string;}export interface BackupCodesProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> { /** Recovery codes as strings or structured objects. */ codes: Array<string | BackupCodeItem>; /** Service or organisation name written into exported .txt and print headers (default "Hairline"). */ issuer?: string; /** Account email or handle written into exported .txt and print headers. */ account?: string; /** Filename for the downloaded plain-text export (default "recovery-codes.txt"). */ filename?: string; /** Start with unused codes veiled behind 8×8 Bayer grain (default true). */ defaultVeiled?: boolean; /** Allow clicking a single revealed code to copy it (default true). */ allowCopyIndividual?: boolean; /** Optional handler to toggle a code's used status (enables interactive audit buttons). */ onToggleUsed?: (code: string, used: boolean) => void; /** Optional handler to generate a fresh batch of codes (enables two-step inline Regenerate). */ onRegenerate?: () => Promise<unknown> | unknown; /** Optional override for Download .txt action. */ onDownload?: (content: string) => void; /** Optional override for Print action. */ onPrint?: () => void; /** Warn in amber when unused codes fall at or below this count (default 2). */ lowThreshold?: number; /** Card header title (default "Recovery codes"). */ title?: string; /** Opt-in Web Audio cues (from ui-sounds.ts). */ sound?: boolean;}// Crockford-inspired unambiguous alphabet (omits 0, O, 1, I, L)const CODE_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz";/** Generate cryptographically clean `xxxx-xxxx` recovery codes. */export function generateBackupCodes(count = 8): BackupCodeItem[] { const out: BackupCodeItem[] = []; const bytes = new Uint8Array(8); for (let i = 0; i < count; i++) { if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") { crypto.getRandomValues(bytes); } else { for (let j = 0; j < 8; j++) bytes[j] = Math.floor(Math.random() * 256); } let s = ""; for (let j = 0; j < 8; j++) { if (j === 4) s += "-"; s += CODE_ALPHABET[bytes[j] % CODE_ALPHABET.length]; } out.push({ code: s, used: false }); } return out;}/** Format recovery codes into a clean plain-text `.txt` sheet for safe offline storage. */export function formatBackupCodesFile( codes: Array<string | BackupCodeItem>, meta?: { issuer?: string; account?: string },): string { const issuer = meta?.issuer || "Account"; const dateStr = new Date().toISOString().slice(0, 10); const items = codes.map((c) => (typeof c === "string" ? { code: c, used: false } : c)); const unused = items.filter((i) => !i.used); const lines = [ `${issuer} — Two-Factor Recovery Codes`, ...(meta?.account ? [`Account: ${meta.account}`] : []), `Saved: ${dateStr}`, `Unused: ${unused.length} of ${items.length}`, "", "Each code can be used once to sign in if you lose access to your authenticator.", "Store this file in a password manager or locked physical copy.", "", ...items.map((item, idx) => `${String(idx + 1).padStart(2, "0")}. ${item.code}${item.used ? " [USED]" : ""}`), "", ]; return lines.join("\n");}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;}function clamp(v: number, lo: number, hi: number) { return v < lo ? lo : v > hi ? hi : v;}/** * 1.5px 8×8 Bayer cell: * mode="veil" -> static optical veil at rest (0% CPU) + emerald sweep on flashToken * mode="burst" -> transparent at rest (0% CPU) + staggered emerald Bayer materialise curtain on flashToken */function BayerCodeVeil({ seed, flashToken, delayMs, mode = "veil", active, reduced, className = "pointer-events-none block h-5 w-full rounded-[4px] [image-rendering:pixelated]",}: { seed: number; flashToken: number; delayMs: number; mode?: "veil" | "burst"; active: boolean; reduced: boolean; className?: string;}) { const canvasRef = React.useRef<HTMLCanvasElement | null>(null); const lastFlashRef = React.useRef(flashToken); React.useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext("2d"); if (!ctx) return; const isDark = () => document.documentElement.classList.contains("dark"); let w = 0; let h = 0; let img: ImageData | null = null; let u32: Uint32Array | null = null; const resize = () => { const rect = canvas.getBoundingClientRect(); const cssW = Math.max(80, Math.round(rect.width)); const cssH = Math.max(20, Math.round(rect.height)); w = Math.max(40, Math.round(cssW / 1.5)); h = Math.max(12, Math.round(cssH / 1.5)); if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; } img = ctx.createImageData(w, h); u32 = new Uint32Array(img.data.buffer); }; const draw = (sweepProgress: number | null) => { if (!img || !u32 || w === 0 || h === 0) return; if (mode === "burst" && sweepProgress === null) { ctx.clearRect(0, 0, w, h); return; } const dark = isDark(); const baseRgb: [number, number, number] = dark ? [168, 176, 192] : [72, 80, 96]; const accentRgb: [number, number, number] = dark ? [52, 211, 153] : [16, 185, 129]; const baseAlpha = dark ? 150 : 122; u32.fill(0); for (let y = 0; y < h; y++) { const ny = y / Math.max(1, h - 1); for (let x = 0; x < w; x++) { const nx = x / Math.max(1, w - 1); const thr = BAYER8[((y & 7) << 3) | (x & 7)]; if (mode === "burst" && sweepProgress !== null) { const front = sweepProgress * 1.5 - 0.25; const env = Math.sin(sweepProgress * Math.PI); const band = Math.exp(-Math.pow((nx - front) / 0.24, 2)); const density = clamp(band * env * 0.94, 0, 0.96); if (density > thr) { const mix = clamp(band * 1.15, 0, 1); const r = Math.round(baseRgb[0] + (accentRgb[0] - baseRgb[0]) * mix); const g = Math.round(baseRgb[1] + (accentRgb[1] - baseRgb[1]) * mix); const b = Math.round(baseRgb[2] + (accentRgb[2] - baseRgb[2]) * mix); u32[y * w + x] = packRgba(r, g, b, Math.round(230 * env)); } continue; } const wave = 0.5 + 0.16 * Math.sin(nx * 6.5 + seed * 1.7 + ny * 1.9) + 0.09 * Math.cos(nx * 13.0 - seed * 2.3); let density = clamp(wave * 0.62, 0.14, 0.72); let r = baseRgb[0]; let g = baseRgb[1]; let b = baseRgb[2]; let a = baseAlpha; if (sweepProgress !== null) { const front = sweepProgress * 1.4 - 0.2; const pulse = Math.exp(-Math.pow((nx - front) / 0.2, 2)) * Math.sin(sweepProgress * Math.PI); if (pulse > 0.04) { density = clamp(density + pulse * 0.45, 0, 0.96); r = Math.round(baseRgb[0] + (accentRgb[0] - baseRgb[0]) * pulse); g = Math.round(baseRgb[1] + (accentRgb[1] - baseRgb[1]) * pulse); b = Math.round(baseRgb[2] + (accentRgb[2] - baseRgb[2]) * pulse); a = Math.round(baseAlpha + (235 - baseAlpha) * pulse); } } if (density > thr) { u32[y * w + x] = packRgba(r, g, b, a); } } } ctx.putImageData(img, 0, 0); }; resize(); draw(null); const ro = new ResizeObserver(() => { resize(); draw(null); }); ro.observe(canvas); const mo = new MutationObserver(() => draw(null)); mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); let raf = 0; let delayTimer = 0; const shouldFlash = flashToken !== lastFlashRef.current; lastFlashRef.current = flashToken; if (shouldFlash && !reduced && active) { const startSweep = () => { const start = performance.now(); const duration = mode === "burst" ? 600 : 520; const step = (now: number) => { const p = clamp((now - start) / duration, 0, 1); draw(p); if (p < 1) raf = window.requestAnimationFrame(step); else draw(null); }; raf = window.requestAnimationFrame(step); }; if (delayMs > 0) { delayTimer = window.setTimeout(startSweep, delayMs); } else { startSweep(); } } return () => { ro.disconnect(); mo.disconnect(); window.clearTimeout(delayTimer); window.cancelAnimationFrame(raf); }; }, [seed, flashToken, delayMs, mode, active, reduced]); return <canvas ref={canvasRef} aria-hidden="true" className={className} />;}export function BackupCodes({ codes, issuer = "Hairline", account, filename = "recovery-codes.txt", defaultVeiled = true, allowCopyIndividual = true, onToggleUsed, onRegenerate, onDownload, onPrint, lowThreshold = 2, title = "Recovery codes", sound = false, className = "", ...props}: BackupCodesProps) { const reduced = useInteractionReducedMotion(); const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>(); const items: BackupCodeItem[] = React.useMemo( () => codes.map((c) => (typeof c === "string" ? { code: c, used: false } : c)), [codes], ); const [allRevealed, setAllRevealed] = React.useState(!defaultVeiled); const [peekedMap, setPeekedMap] = React.useState<Record<string, boolean>>({}); const [copiedCode, setCopiedCode] = React.useState<string | null>(null); const [copiedAll, setCopiedAll] = React.useState(false); const [downloaded, setDownloaded] = React.useState(false); const [confirmRegen, setConfirmRegen] = React.useState(false); const [regenerating, setRegenerating] = React.useState(false); const [regeneratedBanner, setRegeneratedBanner] = React.useState(false); const [flashSeq, setFlashSeq] = React.useState(0); const [regenSeq, setRegenSeq] = React.useState(0); const [liveStatus, setLiveStatus] = React.useState(""); const copyAllTimerRef = React.useRef(0); const copyOneTimerRef = React.useRef(0); const downloadTimerRef = React.useRef(0); const regenBannerTimerRef = React.useRef(0); React.useEffect( () => () => { window.clearTimeout(copyAllTimerRef.current); window.clearTimeout(copyOneTimerRef.current); window.clearTimeout(downloadTimerRef.current); window.clearTimeout(regenBannerTimerRef.current); }, [], ); const unusedItems = React.useMemo(() => items.filter((i) => !i.used), [items]); const isLow = unusedItems.length <= lowThreshold; const isRowRevealed = (item: BackupCodeItem) => Boolean(item.used || allRevealed || peekedMap[item.code]); const handleToggleRevealAll = () => { const next = !allRevealed; setAllRevealed(next); if (!next) setPeekedMap({}); if (sound) playSound(next ? "unfold" : "fold", 0.3); setLiveStatus(next ? "All recovery codes revealed" : "Recovery codes veiled"); }; const handleCopyAll = async () => { const text = unusedItems.map((i) => i.code).join("\n"); if (!text) return; try { await navigator.clipboard?.writeText(text); } catch {} setCopiedAll(true); setFlashSeq((n) => n + 1); if (sound) playSound("success", 0.36); setLiveStatus(`Copied ${unusedItems.length} unused recovery codes`); window.clearTimeout(copyAllTimerRef.current); copyAllTimerRef.current = window.setTimeout(() => setCopiedAll(false), 1800); }; const handleCopySingle = async (code: string) => { if (!allowCopyIndividual) return; try { await navigator.clipboard?.writeText(code); } catch {} setCopiedCode(code); if (sound) playSound("tick", 0.3); setLiveStatus(`Copied recovery code ${code}`); window.clearTimeout(copyOneTimerRef.current); copyOneTimerRef.current = window.setTimeout(() => setCopiedCode(null), 1500); }; const handleDownload = () => { const content = formatBackupCodesFile(items, { issuer, account }); if (onDownload) { onDownload(content); } else { const blob = new Blob([content], { type: "text/plain;charset=utf-8" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); } setDownloaded(true); setFlashSeq((n) => n + 1); if (sound) playSound("success", 0.34); setLiveStatus(`Downloaded ${filename}`); window.clearTimeout(downloadTimerRef.current); downloadTimerRef.current = window.setTimeout(() => setDownloaded(false), 1800); }; const handlePrint = () => { if (onPrint) { onPrint(); return; } const content = formatBackupCodesFile(items, { issuer, account }); const win = window.open("", "_blank", "width=560,height=640"); if (!win) { window.print(); return; } win.document.write( `<!doctype html><html><head><title>${issuer} Recovery Codes</title><style>body{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;padding:32px;line-height:1.6;color:#111}pre{white-space:pre-wrap;font-size:13px}</style></head><body><pre>${content.replace(/</g, "<")}</pre></body></html>`, ); win.document.close(); win.focus(); win.print(); }; const handleConfirmRegenerate = async () => { if (!onRegenerate) return; setRegenerating(true); try { await onRegenerate(); setConfirmRegen(false); setPeekedMap({}); setRegeneratedBanner(true); // Fire BOTH veil sweep & revealed burst curtain after the new codes commit to DOM window.requestAnimationFrame(() => { setFlashSeq((n) => n + 1); setRegenSeq((n) => n + 1); }); if (sound) playSound("success", 0.4); setLiveStatus("Generated fresh recovery codes"); window.clearTimeout(regenBannerTimerRef.current); regenBannerTimerRef.current = window.setTimeout(() => setRegeneratedBanner(false), 2600); } finally { setRegenerating(false); } }; const lowMessage = unusedItems.length === 0 ? "All recovery codes have been used. Regenerate a new set right away." : `Only ${unusedItems.length} recovery code${unusedItems.length === 1 ? "" : "s"} left. Consider regenerating soon.`; return ( <div ref={rootRef} role="region" aria-label={title} data-veiled={!allRevealed ? "true" : "false"} data-unused={unusedItems.length} data-regenerating={regenerating ? "true" : "false"} className={`@container flex w-full max-w-[480px] flex-col overflow-hidden rounded-[16px] border border-border bg-card text-card-foreground 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)] ${className}`} {...props} > {/* Hairline header */} <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border/80 bg-muted/20 px-4 py-3"> <div className="flex flex-wrap items-center gap-2"> <ShieldCheck className="size-4 text-muted-foreground" strokeWidth={1.9} /> <div className="flex items-center gap-2"> <span className="text-[13px] font-medium tracking-[-0.01em] text-foreground">{title}</span> <span className={`inline-flex items-center gap-1 font-mono text-[11px] tabular-nums transition-colors ${ isLow ? "font-medium text-amber-600 dark:text-amber-400" : "text-muted-foreground" }`} > <NumberRoll value={unusedItems.length} /> <span>of</span> <NumberRoll value={items.length} /> <span>unused</span> </span> </div> <span aria-hidden={!regeneratedBanner || undefined} className="grid" style={{ gridTemplateColumns: regeneratedBanner ? "1fr" : "0fr", opacity: regeneratedBanner ? 1 : 0, transition: reduced ? "none" : `grid-template-columns 340ms ${EASE_OUT}, opacity 220ms ${EASE_OUT}`, }} > <span className="min-w-0 overflow-hidden"> <span className="inline-flex w-max items-center gap-1 whitespace-nowrap rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 text-[10.5px] font-medium text-emerald-700 dark:text-emerald-300"> <Check className="size-2.5" strokeWidth={2.5} /> New codes issued </span> </span> </span> </div> <button type="button" onClick={handleToggleRevealAll} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span className="relative flex size-3.5 shrink-0 items-center justify-center"> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!allRevealed, reduced)}> <Eye className="size-3.5" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(allRevealed, reduced)}> <EyeOff className="size-3.5" strokeWidth={1.9} /> </span> </span> <TextMorph>{allRevealed ? "Hide codes" : "Reveal codes"}</TextMorph> </button> </div> {/* Low remaining warning banner (smooth grid-template-rows fold!) */} <div aria-hidden={!isLow || undefined} className={`grid ${!isLow ? "pointer-events-none" : ""}`} style={{ gridTemplateRows: isLow ? "1fr" : "0fr", opacity: isLow ? 1 : 0, transition: reduced ? "none" : `grid-template-rows 360ms ${EASE_OUT}, opacity 240ms ${EASE_OUT}`, }} > <div className="min-h-0 overflow-clip"> <div role="status" className="flex items-center gap-2 border-b border-amber-500/25 bg-amber-500/[0.08] px-4 py-2 text-[11.5px] text-amber-800 dark:text-amber-200" > <AlertTriangle className="size-3.5 shrink-0 text-amber-600 dark:text-amber-400" strokeWidth={2} /> <TextMorph animateWidth={false}>{lowMessage}</TextMorph> </div> </div> </div> {/* 2-column hairline code grid (keyed stably by index so Bayer canvases animate cleanly across regenerations!) */} <div className="grid grid-cols-1 gap-2 p-3.5 @[420px]:grid-cols-2"> {items.map((item, idx) => { const revealed = isRowRevealed(item); const isCopied = copiedCode === item.code; if (item.used) { return ( <div key={idx} data-code-slot={idx} data-used="true" className="relative flex h-10 items-center justify-between gap-2 overflow-hidden rounded-[10px] border border-border/60 bg-muted/25 px-3 text-muted-foreground/65" > <div className="flex min-w-0 items-center gap-2"> <span className="font-mono text-[10px] tabular-nums opacity-60">{String(idx + 1).padStart(2, "0")}</span> <span className="truncate font-mono text-[13px] tracking-[0.04em] line-through">{item.code}</span> </div> {onToggleUsed ? ( <button type="button" aria-label={`Restore code ${idx + 1}`} onClick={() => onToggleUsed(item.code, false)} className={`shrink-0 cursor-pointer rounded-[5px] border border-border/70 bg-background px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground hover:text-foreground ${INTERACTION_FOCUS}`} > Used </button> ) : ( <span className="shrink-0 rounded-[5px] border border-border/70 px-1.5 py-0.5 text-[10px] font-medium"> {item.usedAt ?? "Used"} </span> )} </div> ); } if (!revealed) { return ( <button key={idx} type="button" data-code-slot={idx} data-veiled="true" aria-label={`Reveal recovery code ${idx + 1}`} onClick={() => { setPeekedMap((prev) => ({ ...prev, [item.code]: true })); if (sound) playSound("unfold", 0.25); }} className={`group flex h-10 w-full cursor-pointer items-center gap-2 rounded-[10px] border border-border/85 bg-background px-2.5 text-left transition-colors hover:border-foreground/25 ${INTERACTION_FOCUS}`} > <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/65"> {String(idx + 1).padStart(2, "0")} </span> <div className="min-w-0 flex-1"> <BayerCodeVeil seed={idx + 1} flashToken={flashSeq} delayMs={idx * 28} mode="veil" active={onScreen} reduced={reduced} /> </div> </button> ); } return ( <div key={idx} data-code-slot={idx} data-veiled="false" className="group relative flex h-10 items-center justify-between gap-1.5 overflow-hidden rounded-[10px] border border-border/85 bg-background px-2.5 transition-colors hover:border-foreground/20" > {/* Staggered 8×8 Bayer materialise curtain when fresh codes are regenerated while revealed */} <BayerCodeVeil seed={idx + 1} flashToken={regenSeq} delayMs={idx * 34} mode="burst" active={onScreen} reduced={reduced} className="pointer-events-none absolute inset-1 z-20 h-[calc(100%_-_8px)] w-[calc(100%_-_8px)] rounded-[6px] [image-rendering:pixelated]" /> <button type="button" disabled={!allowCopyIndividual} aria-label={isCopied ? `Copied recovery code ${idx + 1}` : `Copy recovery code ${idx + 1}`} onClick={() => void handleCopySingle(item.code)} className={`relative z-10 flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-left disabled:cursor-default ${INTERACTION_FOCUS}`} > <span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/65"> {String(idx + 1).padStart(2, "0")} </span> <span className="truncate font-mono text-[13px] font-medium tracking-[0.04em] text-foreground"> <TextMorph duration={420}>{item.code}</TextMorph> </span> </button> <div className="relative z-10 flex shrink-0 items-center gap-1"> {onToggleUsed && ( <button type="button" aria-label={`Mark code ${idx + 1} as used`} title="Mark as used" onClick={() => onToggleUsed(item.code, true)} className={`cursor-pointer rounded-[5px] px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground/75 opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 ${INTERACTION_FOCUS}`} > Use </button> )} {allowCopyIndividual && ( <button type="button" aria-label={isCopied ? `Copied ${item.code}` : `Copy ${item.code}`} onClick={() => void handleCopySingle(item.code)} className={`relative flex size-6 cursor-pointer items-center justify-center rounded-[6px] hover:bg-accent ${ isCopied ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground/70 hover:text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!isCopied, reduced)}> <Copy className="size-3" strokeWidth={2} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(isCopied, reduced)}> <Check className="size-3" strokeWidth={2.4} /> </span> </button> )} </div> </div> ); })} </div> {/* Hairline action bar OR inline two-step regenerate confirmation */} <div className="border-t border-border/80 bg-muted/15 px-3.5 py-2.5"> {confirmRegen ? ( <div className="flex flex-wrap items-center justify-between gap-2" data-confirm-regenerate="true"> <span className="text-[12px] text-foreground">Invalidate old codes and issue {items.length} new ones?</span> <div className="flex items-center gap-1.5"> <button type="button" disabled={regenerating} onClick={() => setConfirmRegen(false)} className={`inline-flex h-7 cursor-pointer items-center rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > Cancel </button> <button type="button" disabled={regenerating} onClick={() => void handleConfirmRegenerate()} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] bg-primary px-2.5 text-[11.5px] font-medium text-primary-foreground hover:opacity-90 disabled:opacity-60 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > {regenerating && <Loader2 className="size-3 animate-spin" strokeWidth={2.2} />} <TextMorph>{regenerating ? "Regenerating…" : "Confirm"}</TextMorph> </button> </div> </div> ) : ( <div className="flex flex-wrap items-center justify-between gap-2"> <div className="flex flex-wrap items-center gap-1.5"> <button type="button" disabled={unusedItems.length === 0} onClick={() => void handleCopyAll()} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium hover:bg-accent disabled:opacity-40 ${ copiedAll ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-300" : "text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span className="relative flex size-3.5 shrink-0 items-center justify-center"> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!copiedAll, reduced)}> <Copy className="size-3.5 text-muted-foreground" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(copiedAll, reduced)}> <Check className="size-3.5" strokeWidth={2.3} /> </span> </span> <TextMorph>{copiedAll ? "Copied" : "Copy all"}</TextMorph> </button> <button type="button" onClick={handleDownload} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium hover:bg-accent ${ downloaded ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-300" : "text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span className="relative flex size-3.5 shrink-0 items-center justify-center"> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!downloaded, reduced)}> <Download className="size-3.5 text-muted-foreground" strokeWidth={1.9} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(downloaded, reduced)}> <Check className="size-3.5" strokeWidth={2.3} /> </span> </span> <TextMorph>{downloaded ? "Saved .txt" : "Download .txt"}</TextMorph> </button> <button type="button" onClick={handlePrint} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <Printer className="size-3.5" strokeWidth={1.9} /> Print </button> </div> {onRegenerate && ( <button type="button" onClick={() => { setConfirmRegen(true); if (sound) playSound("tick", 0.25); }} className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <RefreshCw className="size-3" strokeWidth={2} /> Regenerate </button> )} </div> )} </div> <span className="sr-only" role="status" aria-live="polite"> {liveStatus} </span> </div> );}export default BackupCodes;Registry item: /r/backup-codes.json


