{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "auth-03",
  "title": "手机号验证码登录",
  "description": "窄单列短信登录：输入手机号、验证短信两步完成，支持协议确认、重发倒计时与异步错误。",
  "dependencies": [
    "motion",
    "zod"
  ],
  "registryDependencies": [
    "button",
    "checkbox",
    "input-otp",
    "https://yiui.dev/r/phone-input.json",
    "https://yiui.dev/r/grid-layout.json"
  ],
  "files": [
    {
      "path": "src/registry/blocks/auth-03/auth-03.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\nimport { Button } from \"@/components/ui/button\"\nimport { Checkbox } from \"@/components/ui/checkbox\"\nimport { cn } from \"@/lib/utils\"\nimport { useControllableState } from \"@/hooks/use-controllable-state\"\nimport {\n  GridContainer,\n  GridSection,\n  GridSeparator,\n} from \"@/components/ui/grid-layout/grid-layout\"\nimport { PhoneInput, maskPhone } from \"@/components/ui/phone-input/phone-input\"\nimport { DEFAULT_LABELS, formatLabel } from \"./config\"\nimport { Auth03CodeInput } from \"./form-parts\"\nimport { createPhoneSchema } from \"./schemas\"\nimport type { Auth03Props, Auth03Step } from \"./types\"\nimport { useAsyncAction } from \"./use-auth-form\"\n\n/** 短信为唯一主任务的两步登录界面；真实认证由回调接入。 */\nfunction Auth03({\n  onSendCode,\n  onVerify,\n  onSuccess,\n  onAlternative,\n  codeLength = 6,\n  resendSeconds = 60,\n  requireAgreement = true,\n  agreementLinks,\n  brand,\n  labels: labelsProp,\n  step: stepProp,\n  defaultStep = \"phone\",\n  onStepChange,\n  className,\n  ...props\n}: Auth03Props) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp }\n  const [step, setStep] = useControllableState<Auth03Step>({\n    prop: stepProp,\n    defaultProp: defaultStep,\n    onChange: onStepChange,\n  })\n  const [phone, setPhone] = React.useState(\"\")\n  const [sentPhone, setSentPhone] = React.useState(\"\")\n  const [code, setCode] = React.useState(\"\")\n  const [agreed, setAgreed] = React.useState(false)\n  const [agreementError, setAgreementError] = React.useState(false)\n  const [phoneError, setPhoneError] = React.useState(\"\")\n  const [success, setSuccess] = React.useState(false)\n  const [deadline, setDeadline] = React.useState(0)\n  const [remaining, setRemaining] = React.useState(0)\n  const sending = useAsyncAction(labels.failed)\n  const verifying = useAsyncAction(labels.failed)\n  const agreementRef = React.useRef<HTMLButtonElement>(null)\n  const titleRef = React.useRef<HTMLHeadingElement>(null)\n  const previous = React.useRef({ step, success })\n  const reduced = useReducedMotion()\n  const id = React.useId()\n  const length = Math.max(1, Math.min(12, Math.floor(codeLength) || 6))\n  const pending = sending.pending || verifying.pending\n  React.useEffect(() => {\n    if (previous.current.step !== step || previous.current.success !== success)\n      titleRef.current?.focus()\n    previous.current = { step, success }\n  }, [step, success])\n  React.useEffect(() => {\n    if (!deadline) return\n    const tick = () =>\n      setRemaining(Math.max(0, Math.ceil((deadline - Date.now()) / 1000)))\n    tick()\n    const timer = window.setInterval(tick, 250)\n    return () => window.clearInterval(timer)\n  }, [deadline])\n  async function send() {\n    if (pending) return\n    if (step === \"phone\") {\n      if (requireAgreement && !agreed) {\n        setAgreementError(true)\n        agreementRef.current?.focus()\n        return\n      }\n      const result = createPhoneSchema(labels).safeParse(phone)\n      if (!result.success) {\n        setPhoneError(result.error.issues[0]?.message ?? labels.phoneError)\n        return\n      }\n    }\n    const target = step === \"code\" ? sentPhone || phone : phone\n    if (!createPhoneSchema(labels).safeParse(target).success) {\n      setStep(\"phone\")\n      setPhoneError(labels.phoneError)\n      return\n    }\n    if (remaining > 0 && target === sentPhone) return\n    if (await sending.run(() => onSendCode(target))) {\n      setSentPhone(target)\n      setCode(\"\")\n      verifying.setError(\"\")\n      const seconds = Math.max(0, resendSeconds)\n      setRemaining(seconds)\n      // 仅在发送成功的事件回调中读取时间，不参与服务端渲染。\n      // eslint-disable-next-line react-hooks/purity\n      setDeadline(Date.now() + seconds * 1000)\n      setStep(\"code\")\n    }\n  }\n  async function verify(value: string) {\n    if (pending || success || value.length !== length) return\n    if (!sentPhone) {\n      setStep(\"phone\")\n      return\n    }\n    if (\n      await verifying.run(() => onVerify({ phone: sentPhone, code: value }))\n    ) {\n      setSuccess(true)\n      onSuccess?.()\n    }\n  }\n  return (\n    <div\n      data-slot=\"auth-03\"\n      data-step={step}\n      data-state={success ? \"success\" : \"idle\"}\n      className={cn(\n        \"w-full overflow-x-clip bg-background text-foreground\",\n        className,\n      )}\n      {...props}\n    >\n      <GridContainer className=\"max-w-md\">\n        <GridSection className=\"px-4 py-8 sm:px-6\">\n          {brand && (\n            <div className=\"mb-8 flex items-center gap-2 text-sm font-medium\">\n              {brand.logo}\n              {brand.name}\n            </div>\n          )}\n          <h1 className=\"text-2xl font-semibold tracking-tight\">\n            {labels.title}\n          </h1>\n          <p className=\"mt-2 text-sm leading-7 text-muted-foreground\">\n            {labels.description}\n          </p>\n        </GridSection>\n        <GridSection\n          className=\"grid grid-cols-2 gap-3 px-4 py-3 text-xs sm:px-6\"\n          aria-label={labels.steps}\n        >\n          {[\"phone\", \"code\"].map((item) => (\n            <span\n              key={item}\n              aria-current={step === item ? \"step\" : undefined}\n              className={cn(\n                \"border-b border-edge pb-2\",\n                step === item\n                  ? \"border-primary text-foreground\"\n                  : \"text-muted-foreground\",\n              )}\n            >\n              <span\n                aria-hidden=\"true\"\n                className=\"mr-1.5 font-mono tabular-nums\"\n              >\n                {item === \"phone\" ? \"01\" : \"02\"}\n              </span>\n              {item === \"phone\" ? labels.phoneStep : labels.codeStep}\n            </span>\n          ))}\n        </GridSection>\n        <GridSection className=\"px-4 py-8 sm:px-6\">\n          <motion.div\n            key={success ? \"success\" : step}\n            data-slot=\"auth-03-step\"\n            initial={false}\n            animate={\n              reduced ? { opacity: 1, y: 0 } : { opacity: [0.7, 1], y: [4, 0] }\n            }\n            transition={{ duration: reduced ? 0 : 0.18 }}\n          >\n            <h2\n              ref={titleRef}\n              tabIndex={-1}\n              className=\"mb-5 text-lg font-medium outline-none focus-visible:underline\"\n            >\n              {success\n                ? labels.success\n                : step === \"phone\"\n                  ? labels.phoneTitle\n                  : labels.codeTitle}\n            </h2>\n            {success ? (\n              <p role=\"status\" className=\"text-sm text-muted-foreground\">\n                {labels.successDescription}\n              </p>\n            ) : step === \"phone\" ? (\n              <form\n                noValidate\n                onSubmit={(event) => {\n                  event.preventDefault()\n                  void send()\n                }}\n                className=\"space-y-5\"\n              >\n                <PhoneInput\n                  label={labels.phone}\n                  value={phone}\n                  onValueChange={(value) => {\n                    setPhone(value)\n                    setPhoneError(\"\")\n                    sending.setError(\"\")\n                  }}\n                  size=\"lg\"\n                  error={phoneError || sending.error}\n                  disabled={pending}\n                  required\n                  labels={{\n                    invalid: labels.phoneError,\n                    required: labels.phoneError,\n                  }}\n                />\n                <div className=\"space-y-2\">\n                  <div className=\"flex items-start gap-3 text-xs leading-6\">\n                    <Checkbox\n                      ref={agreementRef}\n                      id={`${id}-agreement`}\n                      checked={agreed}\n                      onCheckedChange={(value) => {\n                        setAgreed(value)\n                        setAgreementError(false)\n                      }}\n                      aria-invalid={agreementError || undefined}\n                      aria-describedby={\n                        agreementError ? `${id}-agreement-error` : undefined\n                      }\n                      className=\"mt-1\"\n                    />\n                    <div>\n                      <label htmlFor={`${id}-agreement`}>\n                        {labels.agreement}\n                      </label>\n                      {agreementLinks?.terms ? (\n                        <a\n                          href={agreementLinks.terms}\n                          className=\"underline underline-offset-4\"\n                        >\n                          {labels.terms}\n                        </a>\n                      ) : (\n                        labels.terms\n                      )}\n                      {labels.and}\n                      {agreementLinks?.privacy ? (\n                        <a\n                          href={agreementLinks.privacy}\n                          className=\"underline underline-offset-4\"\n                        >\n                          {labels.privacy}\n                        </a>\n                      ) : (\n                        labels.privacy\n                      )}\n                    </div>\n                  </div>\n                  {agreementError && (\n                    <p\n                      role=\"alert\"\n                      id={`${id}-agreement-error`}\n                      className=\"text-xs text-destructive\"\n                    >\n                      {labels.agreementError}\n                    </p>\n                  )}\n                </div>\n                <Button\n                  type=\"submit\"\n                  size=\"lg\"\n                  className=\"w-full\"\n                  disabled={pending || (remaining > 0 && phone === sentPhone)}\n                >\n                  {sending.pending\n                    ? labels.sending\n                    : remaining > 0 && phone === sentPhone\n                      ? formatLabel(labels.countdown, { seconds: remaining })\n                      : labels.send}\n                </Button>\n              </form>\n            ) : (\n              <form\n                noValidate\n                onSubmit={(event) => {\n                  event.preventDefault()\n                  void verify(code)\n                }}\n                className=\"space-y-5\"\n              >\n                {/* 脱敏号码和「修改号码」放在同一行，窄屏放不下时自然换行 */}\n                <div className=\"flex flex-wrap items-baseline gap-x-3 gap-y-1 text-sm\">\n                  <p className=\"font-mono text-muted-foreground\">\n                    {formatLabel(labels.sent, {\n                      phone: maskPhone(sentPhone || phone),\n                    })}\n                  </p>\n                  {/* 例外：行内文字链接，高度跟随文字，不占按钮的三档高度 */}\n                  <Button\n                    type=\"button\"\n                    variant=\"link\"\n                    size=\"sm\"\n                    disabled={pending}\n                    className=\"h-auto px-0 pointer-coarse:h-auto\"\n                    onClick={() => {\n                      setStep(\"phone\")\n                      setCode(\"\")\n                      verifying.setError(\"\")\n                      sending.setError(\"\")\n                    }}\n                  >\n                    {labels.edit}\n                  </Button>\n                </div>\n                <div className=\"space-y-2\">\n                  <Auth03CodeInput\n                    length={length}\n                    value={code}\n                    label={formatLabel(labels.code, { length })}\n                    disabled={pending}\n                    error={!!verifying.error}\n                    describedBy={\n                      verifying.error ? `${id}-code-error` : undefined\n                    }\n                    onChange={(value) => {\n                      setCode(value)\n                      verifying.setError(\"\")\n                    }}\n                    onComplete={(value) => void verify(value)}\n                  />\n                  {verifying.error && (\n                    <p\n                      role=\"alert\"\n                      id={`${id}-code-error`}\n                      className=\"text-xs text-destructive\"\n                    >\n                      {verifying.error}\n                    </p>\n                  )}\n                </div>\n                <Button\n                  size=\"lg\"\n                  type=\"submit\"\n                  className=\"w-full\"\n                  disabled={pending || code.length !== length}\n                >\n                  {verifying.pending ? labels.verifying : labels.verify}\n                </Button>\n                <Button\n                  size=\"lg\"\n                  type=\"button\"\n                  variant=\"link\"\n                  className=\"w-full\"\n                  disabled={pending || remaining > 0}\n                  onClick={() => void send()}\n                >\n                  {sending.pending\n                    ? labels.sending\n                    : remaining > 0\n                      ? formatLabel(labels.countdown, { seconds: remaining })\n                      : labels.resend}\n                </Button>\n                {sending.error && (\n                  <div\n                    role=\"alert\"\n                    className=\"space-y-2 text-xs text-destructive\"\n                  >\n                    <p>{sending.error}</p>\n                    <p>{labels.limit}</p>\n                  </div>\n                )}\n              </form>\n            )}\n          </motion.div>\n        </GridSection>\n        <GridSeparator />\n        <GridSection className=\"px-4 py-5 text-center sm:px-6\">\n          <Button\n            type=\"button\"\n            variant=\"link\"\n            size=\"lg\"\n            onClick={() => onAlternative?.(\"password\")}\n          >\n            {labels.alternative}\n          </Button>\n        </GridSection>\n      </GridContainer>\n    </div>\n  )\n}\nexport { Auth03 }\nexport type { Auth03Props, Auth03Step }\nexport type { Auth03Labels } from \"./config\"\n",
      "type": "registry:component",
      "target": "@components/auth-03/auth-03.tsx"
    },
    {
      "path": "src/registry/hooks/use-controllable-state.ts",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\ntype UseControllableStateParams<T> = {\n  /** 受控值；传入后组件不再维护内部状态 */\n  prop?: T\n  /** 非受控时的初始值 */\n  defaultProp: T\n  /** 值变化时回调（受控与非受控都会触发） */\n  onChange?: (value: T) => void\n}\n\n/**\n * 同时支持受控与非受控的状态 hook。\n * 约定见 component-conventions 技能第 4 节：open/defaultOpen/onOpenChange 等成对 props 都用它实现。\n */\nfunction useControllableState<T>({\n  prop,\n  defaultProp,\n  onChange,\n}: UseControllableStateParams<T>) {\n  const [uncontrolled, setUncontrolled] = React.useState(defaultProp)\n  const isControlled = prop !== undefined\n  const value = isControlled ? prop : uncontrolled\n\n  // 用 ref 保存最新的回调和值，保证 setValue 引用稳定\n  const onChangeRef = React.useRef(onChange)\n  const valueRef = React.useRef(value)\n  React.useEffect(() => {\n    onChangeRef.current = onChange\n    valueRef.current = value\n  })\n\n  const setValue = React.useCallback(\n    (next: React.SetStateAction<T>) => {\n      const resolved =\n        typeof next === \"function\"\n          ? (next as (prev: T) => T)(valueRef.current)\n          : next\n      if (Object.is(resolved, valueRef.current)) return\n      valueRef.current = resolved\n      if (!isControlled) setUncontrolled(resolved)\n      onChangeRef.current?.(resolved)\n    },\n    [isControlled],\n  )\n\n  return [value, setValue] as const\n}\n\nexport { useControllableState }\n",
      "type": "registry:hook",
      "target": "hooks/use-controllable-state.ts"
    },
    {
      "path": "src/registry/blocks/auth-03/page.tsx",
      "content": "\"use client\"\nimport * as React from \"react\"\nimport { Auth03 } from \"@/components/auth-03/auth-03\"\n/** 演示后端仅用于体验界面，接入时替换为真实短信和认证服务。 */\nexport default function LoginPage() {\n  const [notice, setNotice] = React.useState(\"\")\n  return (\n    <main\n      data-slot=\"auth-03-demo\"\n      className=\"flex min-h-screen flex-col justify-center bg-background px-4 py-8 text-foreground\"\n    >\n      <p className=\"mb-4 text-center text-xs text-muted-foreground\">\n        演示验证码：123456\n      </p>\n      <Auth03\n        brand={{ name: \"云间工作台\" }}\n        onSendCode={async (phone) => {\n          await new Promise((resolve) => setTimeout(resolve, 350))\n          if (phone.endsWith(\"0000\")) throw new Error(\"发送太频繁，请稍后再试\")\n        }}\n        onVerify={async ({ code }) => {\n          await new Promise((resolve) => setTimeout(resolve, 350))\n          if (code !== \"123456\") throw new Error(\"验证码错误，请重新输入\")\n        }}\n        onAlternative={() => setNotice(\"请在接入后打开账号密码登录页面\")}\n      />\n      <p\n        role=\"status\"\n        className=\"mt-4 text-center text-xs text-muted-foreground\"\n      >\n        {notice}\n      </p>\n    </main>\n  )\n}\n",
      "type": "registry:page",
      "target": "app/login-sms/page.tsx"
    },
    {
      "path": "src/registry/blocks/auth-03/schemas.ts",
      "content": "import { z } from \"zod\"\nimport type { Auth03Labels } from \"./config\"\nfunction createPhoneSchema(labels: Auth03Labels) {\n  return z.string().regex(/^1[3-9]\\d{9}$/, labels.phoneError)\n}\nexport { createPhoneSchema }\n",
      "type": "registry:component",
      "target": "@components/auth-03/schemas.ts"
    },
    {
      "path": "src/registry/blocks/auth-03/types.ts",
      "content": "import type * as React from \"react\"\nimport type { Auth03Labels } from \"./config\"\ntype Auth03Step = \"phone\" | \"code\"\ntype Auth03Props = Omit<React.ComponentProps<\"div\">, \"onSuccess\"> & {\n  /** 发送短信，失败时抛出 Error；号码为不带区号的 11 位数字。 */\n  onSendCode: (phone: string) => Promise<void>\n  /** 验证短信，失败时抛出 Error。 */\n  onVerify: (values: { phone: string; code: string }) => Promise<void>\n  /** 验证成功后的通知。 */\n  onSuccess?: () => void\n  /** 其他登录入口，由接入方处理导航。 */\n  onAlternative?: (method: \"password\") => void\n  /** 验证码位数。@default 6 */\n  codeLength?: number\n  /** 重发间隔秒数。@default 60 */\n  resendSeconds?: number\n  /** 是否必须同意协议。@default true */\n  requireAgreement?: boolean\n  /** 协议链接；未提供时仅显示协议名称。 */\n  agreementLinks?: { terms?: string; privacy?: string }\n  /** 品牌名称和标志。 */\n  brand?: { name: string; logo?: React.ReactNode }\n  /** 覆盖默认中文文案。 */\n  labels?: Partial<Auth03Labels>\n  /** 受控步骤。 */\n  step?: Auth03Step\n  /** 初始步骤。@default \"phone\" */\n  defaultStep?: Auth03Step\n  /** 步骤变化通知。 */\n  onStepChange?: (step: Auth03Step) => void\n}\nexport type { Auth03Props, Auth03Step }\n",
      "type": "registry:component",
      "target": "@components/auth-03/types.ts"
    },
    {
      "path": "src/registry/blocks/auth-03/config.ts",
      "content": "const DEFAULT_LABELS = {\n  title: \"手机号验证码登录\",\n  description: \"无需记住密码，通过短信安全登录。\",\n  steps: \"登录步骤\",\n  /** 步骤条上的短名，前面会自动加 01 / 02 编号 */\n  phoneStep: \"手机号\",\n  codeStep: \"验证码\",\n  /** 当前步骤的标题，切换步骤时焦点落在这里 */\n  phoneTitle: \"输入手机号\",\n  codeTitle: \"输入短信验证码\",\n  phone: \"手机号（+86）\",\n  send: \"获取验证码\",\n  sending: \"发送中…\",\n  agreement: \"我已阅读并同意\",\n  terms: \"《用户协议》\",\n  and: \"和\",\n  privacy: \"《隐私政策》\",\n  agreementError: \"请先阅读并同意用户协议和隐私政策\",\n  phoneError: \"请输入正确的 11 位手机号\",\n  sent: \"验证码已发送至 +86 {phone}\",\n  edit: \"修改号码\",\n  code: \"验证码，共 {length} 位\",\n  verify: \"验证并登录\",\n  verifying: \"验证中…\",\n  resend: \"重新发送验证码\",\n  countdown: \"{seconds} 秒后可重新发送\",\n  failed: \"请求失败，请稍后重试\",\n  success: \"登录成功\",\n  successDescription: \"身份验证已完成。\",\n  alternative: \"账号密码登录\",\n  limit: \"若已达到当天发送次数上限，请改用其他登录方式。\",\n}\ntype Auth03Labels = typeof DEFAULT_LABELS\nfunction formatLabel(\n  template: string,\n  values: Record<string, string | number>,\n) {\n  return template.replace(/\\{(\\w+)\\}/g, (_, key: string) =>\n    String(values[key] ?? \"\"),\n  )\n}\nexport { DEFAULT_LABELS, formatLabel }\nexport type { Auth03Labels }\n",
      "type": "registry:component",
      "target": "@components/auth-03/config.ts"
    },
    {
      "path": "src/registry/blocks/auth-03/use-auth-form.ts",
      "content": "\"use client\"\nimport * as React from \"react\"\n/** 用同步锁拦截自动提交与回车的重复请求。 */\nfunction useAsyncAction(fallback: string) {\n  const lock = React.useRef(false)\n  const [pending, setPending] = React.useState(false)\n  const [error, setError] = React.useState(\"\")\n  async function run(action: () => Promise<void>) {\n    if (lock.current) return false\n    lock.current = true\n    setPending(true)\n    setError(\"\")\n    try {\n      await action()\n      return true\n    } catch (caught) {\n      setError(caught instanceof Error ? caught.message : fallback)\n      return false\n    } finally {\n      lock.current = false\n      setPending(false)\n    }\n  }\n  return { pending, error, setError, run }\n}\nexport { useAsyncAction }\n",
      "type": "registry:component",
      "target": "@components/auth-03/use-auth-form.ts"
    },
    {
      "path": "src/registry/blocks/auth-03/form-parts.tsx",
      "content": "\"use client\"\nimport {\n  InputOTP,\n  InputOTPGroup,\n  InputOTPSlot,\n} from \"@/components/ui/input-otp\"\nfunction Auth03CodeInput({\n  length,\n  value,\n  error,\n  describedBy,\n  label,\n  disabled,\n  onChange,\n  onComplete,\n}: {\n  length: number\n  value: string\n  error: boolean\n  describedBy?: string\n  label: string\n  disabled: boolean\n  onChange: (value: string) => void\n  onComplete: (value: string) => void\n}) {\n  return (\n    <div data-slot=\"auth-03-code-input\">\n      <InputOTP\n        maxLength={length}\n        value={value}\n        onChange={onChange}\n        onComplete={onComplete}\n        pattern=\"^[0-9]*$\"\n        autoComplete=\"one-time-code\"\n        inputMode=\"numeric\"\n        aria-label={label}\n        aria-invalid={error || undefined}\n        aria-describedby={describedBy}\n        disabled={disabled}\n        containerClassName=\"w-full\"\n      >\n        <InputOTPGroup className=\"w-full\">\n          {Array.from({ length }, (_, index) => (\n            <InputOTPSlot\n              key={index}\n              index={index}\n              aria-invalid={error || undefined}\n              className=\"h-9 min-w-0 flex-1 border-edge text-base data-[active=true]:border-foreground/25 data-[active=true]:bg-muted/40 data-[active=true]:ring-0 pointer-coarse:h-11\"\n            />\n          ))}\n        </InputOTPGroup>\n      </InputOTP>\n    </div>\n  )\n}\nexport { Auth03CodeInput }\n",
      "type": "registry:component",
      "target": "@components/auth-03/form-parts.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-edge": "var(--edge)"
    },
    "light": {
      "edge": "color-mix(in oklch, var(--foreground) 12%, transparent)"
    },
    "dark": {
      "edge": "color-mix(in oklch, var(--foreground) 18%, transparent)"
    }
  },
  "meta": {
    "iframeHeight": "800px"
  },
  "type": "registry:block"
}
