{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "auth-04",
  "description": "An email verification code form with a resend that waits between emails and a way to fix a mistyped address.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/announcements.json",
    "button",
    "input",
    "https://www.dashboardblocks.com/r/radix/auth.json",
    "https://www.dashboardblocks.com/r/radix/rolling-text.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/auth/auth-04.tsx",
      "content": "'use client'\n\nimport {\n  Announcements,\n  useAnnouncements,\n} from '@/registry/components/dashboardblocks/announcements'\nimport {\n  AuthIcon,\n  AuthLayout,\n  AuthResendButton,\n  AuthReveal,\n  OtpInput,\n} from '@/registry/components/dashboardblocks/auth'\nimport { RollingText } from '@/registry/components/dashboardblocks/rolling-text'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  type FormEvent,\n  startTransition,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from 'react'\n\nimport { Button } from '@/components/ui/button'\nimport { Input } from '@/components/ui/input'\n\ninterface Auth4Props {\n  email: string\n  focusOnMount?: boolean\n  onChangeEmail?: (email: string) => void | Promise<void>\n  onResend?: () => void | Promise<void>\n  onVerified?: () => void\n  onVerify?: (code: string) => boolean | Promise<boolean>\n  /** Seconds before another email can be sent. @default 60 */\n  resendAfter?: number\n}\n\nconst exampleProps: Auth4Props = {\n  email: 'amara@acme.co',\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\ntype Stage = 'code' | 'checking' | 'editing' | 'changing' | 'verified'\n\nconst Auth4 = (props: Auth4Props) => {\n  const {\n    focusOnMount = false,\n    onChangeEmail,\n    onResend,\n    onVerified,\n    onVerify,\n    resendAfter = 60,\n  } = props\n  const id = useId()\n  const [email, setEmail] = useState(props.email)\n  const [code, setCode] = useState('')\n  const [stage, setStage] = useState<Stage>('code')\n  const [error, setError] = useState<string | null>(null)\n  const [sendError, setSendError] = useState<string | null>(null)\n  const [status, setStatus] = useState('')\n  const [said, announce] = useAnnouncements()\n  const [cooldown, setCooldown] = useState(0)\n  const [resending, setResending] = useState(false)\n  const [draft, setDraft] = useState(props.email)\n  const [failures, setFailures] = useState(0)\n  const checking = stage === 'checking'\n  const editing = stage === 'editing' || stage === 'changing'\n  const verified = stage === 'verified'\n  const formsRef = useRef<HTMLDivElement>(null)\n\n  useEffect(() => {\n    if (cooldown <= 0) return\n    const timer = setTimeout(() => setCooldown((seconds) => seconds - 1), 1000)\n    return () => clearTimeout(timer)\n  }, [cooldown])\n\n  useEffect(() => {\n    if (failures && !checking)\n      formsRef.current?.querySelector<HTMLElement>('[aria-invalid=\"true\"]')?.focus()\n  }, [failures, checking])\n\n  const fail = (message: string) => {\n    setError(message)\n    setFailures((count) => count + 1)\n  }\n\n  const say = (text: string) => {\n    setStatus(text)\n    announce(text)\n  }\n\n  const verify = async (value: string) => {\n    if (stage !== 'code') return\n    if (!/^\\d{6}$/.test(value)) return fail('Enter all 6 digits from the email.')\n    setStage('checking')\n    setError(null)\n    setSendError(null)\n    try {\n      const ok = onVerify ? await onVerify(value) : value === '123456'\n      startTransition(() => {\n        if (ok) {\n          setStage('verified')\n          announce('Email verified')\n          onVerified?.()\n        } else {\n          setStage('code')\n          setCode('')\n          fail('That code didn’t work. Check the newest email, or send a new code.')\n        }\n      })\n    } catch {\n      startTransition(() => {\n        setStage('code')\n        fail('We couldn’t check the code. Check your connection and try again.')\n      })\n    }\n  }\n\n  const resend = async () => {\n    if (resending || editing || verified) return\n    setResending(true)\n    setError(null)\n    setSendError(null)\n    setStatus('')\n    try {\n      await onResend?.()\n      startTransition(() => {\n        setResending(false)\n        setCooldown(resendAfter)\n        say(`We sent a new code to ${email}.`)\n      })\n    } catch {\n      startTransition(() => {\n        setResending(false)\n        setSendError('We couldn’t send the email. Check your connection and try again.')\n      })\n    }\n  }\n\n  const saveEmail = async (event: FormEvent<HTMLFormElement>) => {\n    event.preventDefault()\n    if (stage !== 'editing') return\n    const address = draft.trim().toLowerCase()\n    if (!EMAIL.test(address)) return fail('Enter an email address.')\n    setStage('changing')\n    setError(null)\n    setSendError(null)\n    try {\n      await onChangeEmail?.(address)\n      startTransition(() => {\n        setEmail(address)\n        setStage('code')\n        setCode('')\n        setCooldown(resendAfter)\n        say(`We sent a code to ${address}.`)\n      })\n    } catch {\n      startTransition(() => {\n        setStage('editing')\n        fail('We couldn’t change the address. Check your connection and try again.')\n      })\n    }\n  }\n\n  return (\n    <AuthLayout\n      media={\n        verified ? (\n          <AuthIcon tone='done' />\n        ) : (\n          <AuthIcon>\n            <IconPlaceholder\n              lucide='MailIcon'\n              tabler='IconMail'\n              hugeicons='MailIcon'\n              phosphor='EnvelopeIcon'\n              remixicon='RiMailLine'\n              aria-hidden\n            />\n          </AuthIcon>\n        )\n      }\n      title={<RollingText text={verified ? 'Email verified' : 'Check your email'} wrap />}\n      description={\n        <RollingText\n          wrap\n          text={\n            verified\n              ? 'Taking you to your workspace…'\n              : `We sent a 6-digit code to ${email}. It expires in 10 minutes.`\n          }\n        />\n      }\n    >\n      <AuthReveal open={!verified}>\n        <div ref={formsRef} className='flex flex-col gap-4'>\n          {editing ? (\n            <form\n              method='post'\n              noValidate\n              onSubmit={(event) => void saveEmail(event)}\n              className='flex flex-col gap-2'\n            >\n              <label htmlFor={`${id}-email`} className='text-sm font-medium'>\n                Email\n              </label>\n              <Input\n                id={`${id}-email`}\n                type='email'\n                autoComplete='email'\n                value={draft}\n                onChange={(event) => setDraft(event.target.value)}\n                aria-invalid={error ? true : undefined}\n                aria-describedby={error ? `${id}-error` : undefined}\n              />\n              <div className='mt-2 flex flex-col gap-2'>\n                <Button type='submit' disabled={stage === 'changing'}>\n                  {stage === 'changing' ? 'Sending' : 'Send code'}\n                </Button>\n                <Button\n                  type='button'\n                  variant='ghost'\n                  disabled={stage === 'changing'}\n                  onClick={() => {\n                    setStage('code')\n                    setDraft(email)\n                    setError(null)\n                    setSendError(null)\n                  }}\n                >\n                  Cancel\n                </Button>\n              </div>\n            </form>\n          ) : (\n            <form\n              method='post'\n              noValidate\n              onSubmit={(event) => {\n                event.preventDefault()\n                void verify(code)\n              }}\n              className='flex flex-col gap-4'\n            >\n              <OtpInput\n                aria-label='Code from the email'\n                aria-describedby={error ? `${id}-error` : undefined}\n                focusOnMount={focusOnMount}\n                value={code}\n                onChange={(next) => {\n                  setCode(next)\n                  setError(null)\n                  setSendError(null)\n                }}\n                onComplete={(next) => void verify(next)}\n                invalid={Boolean(error)}\n                disabled={checking}\n              />\n              <Button type='submit' disabled={checking}>\n                {checking ? 'Checking' : 'Verify email'}\n              </Button>\n            </form>\n          )}\n          {!editing && (\n            <div className='flex flex-col gap-4'>\n              <p className='text-muted-foreground text-sm text-pretty'>\n                Not in your inbox? Check your spam folder, or send it again.\n              </p>\n              <div className='-mx-2.5 flex items-center justify-between gap-2'>\n                <Button\n                  type='button'\n                  variant='ghost'\n                  size='sm'\n                  disabled={checking || resending}\n                  onClick={() => {\n                    setStage('editing')\n                    setError(null)\n                    setSendError(null)\n                  }}\n                >\n                  <IconPlaceholder\n                    lucide='PencilIcon'\n                    tabler='IconPencil'\n                    hugeicons='PencilEdit02Icon'\n                    phosphor='PencilSimpleIcon'\n                    remixicon='RiPencilLine'\n                    data-icon='inline-start'\n                    aria-hidden\n                  />\n                  Use another email\n                </Button>\n                <AuthResendButton\n                  cooldown={cooldown}\n                  total={resendAfter}\n                  pending={resending}\n                  onClick={() => void resend()}\n                />\n              </div>\n            </div>\n          )}\n          {(error ?? sendError) && (\n            <p id={`${id}-error`} role='alert' className='text-destructive text-sm'>\n              {error ?? sendError}\n            </p>\n          )}\n          {status && <p className='text-muted-foreground text-sm'>{status}</p>}\n        </div>\n      </AuthReveal>\n      <Announcements said={said} />\n    </AuthLayout>\n  )\n}\n\nexport { Auth4, exampleProps as auth4ExampleProps, type Auth4Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/auth/auth-04.tsx"
    }
  ],
  "meta": {
    "shows": "An email verification code form with a resend that waits between emails and a way to fix a mistyped address.",
    "size": "page",
    "usedWith": [
      "auth-03"
    ],
    "component": "Auth4",
    "props": "{ email: string; focusOnMount?: boolean; onChangeEmail?: (email: string) => void | Promise<void>; onResend?: () => void | Promise<void>; onVerified?: () => void; onVerify?: (code: string) => boolean | Promise<boolean>; resendAfter?: number }"
  },
  "type": "registry:component"
}
