{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "auth-07",
  "title": "锁屏与重新验证",
  "description": "已登录用户的全屏锁屏：大号时钟、头像问候，用密码或 6 位 PIN 解锁，连续输错会暂时锁定并倒计时恢复。",
  "dependencies": [
    "input-otp",
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "avatar",
    "button",
    "input-otp",
    "https://yiui.dev/r/bar-field.json",
    "https://yiui.dev/r/glyph-field.json",
    "https://yiui.dev/r/greeting.json",
    "https://yiui.dev/r/local-time.json",
    "https://yiui.dev/r/grid-layout.json"
  ],
  "files": [
    {
      "path": "src/registry/blocks/auth-07/auth-07.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { useAnimate, useReducedMotion } from \"motion/react\"\nimport { Check, Loader2, LockKeyhole, TimerOff } from \"lucide-react\"\nimport { Avatar, AvatarFallback, AvatarImage } from \"@/components/ui/avatar\"\nimport { Button } from \"@/components/ui/button\"\nimport { cn } from \"@/lib/utils\"\nimport { useControllableState } from \"@/hooks/use-controllable-state\"\nimport { GlyphField } from \"@/components/ui/glyph-field/glyph-field\"\nimport { Greeting } from \"@/components/ui/greeting/greeting\"\nimport {\n  GridContainer,\n  GridCrosshair,\n  GridSection,\n} from \"@/components/ui/grid-layout/grid-layout\"\nimport { DEFAULT_LABELS, formatLabel } from \"./config\"\nimport { Auth07Clock, Auth07PasswordField, Auth07PinField } from \"./form-parts\"\nimport type { Auth07Method, Auth07Props } from \"./types\"\nimport { useUnlockAttempts } from \"./use-auth-form\"\n\nconst ALL_METHODS: Auth07Method[] = [\"password\", \"pin\"]\n\n/** 锁屏与重新验证：已登录用户用密码或 PIN 解锁，连续失败会暂时锁定。真实认证由回调接入。 */\nfunction Auth07({\n  user,\n  onUnlock,\n  onSuccess,\n  onSwitchAccount,\n  onSignOut,\n  reason = \"locked\",\n  methods: methodsProp = ALL_METHODS,\n  method: methodProp,\n  defaultMethod,\n  onMethodChange,\n  pinLength = 6,\n  maxAttempts = 5,\n  lockSeconds = 30,\n  timeZone,\n  locale = \"zh-CN\",\n  labels: labelsProp,\n  className,\n  ...props\n}: Auth07Props) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp }\n  // 去掉未知值和重复项，保留调用方给的顺序：第一项就是默认方式\n  const validMethods = methodsProp.filter(\n    (item, index) =>\n      ALL_METHODS.includes(item) && methodsProp.indexOf(item) === index,\n  )\n  const methods = validMethods.length ? validMethods : ALL_METHODS\n  const [methodState, setMethod] = useControllableState<Auth07Method>({\n    prop: methodProp,\n    defaultProp: defaultMethod ?? methods[0]!,\n    onChange: onMethodChange,\n  })\n  // 受控值不在可用列表里时退回第一项，避免显示一个不能用的输入\n  const method = methods.includes(methodState) ? methodState : methods[0]!\n  const length = Math.max(4, Math.min(8, Math.floor(pinLength) || 6))\n  const attempts = useUnlockAttempts({\n    maxAttempts: Math.max(1, Math.floor(maxAttempts) || 5),\n    lockSeconds: Math.max(1, Math.floor(lockSeconds) || 30),\n  })\n  const [password, setPassword] = React.useState(\"\")\n  const [pin, setPin] = React.useState(\"\")\n  const [capsLock, setCapsLock] = React.useState(false)\n  const [unlocked, setUnlocked] = React.useState(false)\n  const [failCount, setFailCount] = React.useState(0)\n  const passwordRef = React.useRef<HTMLInputElement>(null)\n  const pinRef = React.useRef<HTMLInputElement>(null)\n  const successRef = React.useRef<HTMLHeadingElement>(null)\n  const [fieldScope, animate] = useAnimate<HTMLDivElement>()\n  const reduced = useReducedMotion()\n  const id = React.useId()\n  const messageId = `${id}-message`\n  const disabled = attempts.pending || attempts.locked\n\n  // 打开、切换方式、失败重试与锁定结束后，焦点都回到当前方式的输入\n  React.useEffect(() => {\n    if (unlocked || attempts.locked) return\n    ;(method === \"pin\" ? pinRef : passwordRef).current?.focus()\n  }, [method, failCount, attempts.locked, unlocked])\n  React.useEffect(() => {\n    if (unlocked) successRef.current?.focus()\n  }, [unlocked])\n  React.useEffect(() => {\n    if (!failCount || reduced || !fieldScope.current) return\n    void animate(\n      fieldScope.current,\n      { x: [0, -8, 8, -5, 5, -2, 0] },\n      { duration: 0.32, ease: \"easeOut\" },\n    )\n  }, [failCount, reduced, animate, fieldScope])\n\n  async function submit(currentMethod: Auth07Method, secret: string) {\n    if (disabled || unlocked) return\n    if (currentMethod === \"pin\" ? secret.length !== length : !secret) {\n      ;(currentMethod === \"pin\" ? pinRef : passwordRef).current?.focus()\n      return\n    }\n    const ok = await attempts.run(() =>\n      onUnlock({ method: currentMethod, secret }),\n    )\n    setPassword(\"\")\n    setPin(\"\")\n    if (ok) {\n      setUnlocked(true)\n      onSuccess?.({ method: currentMethod })\n    } else {\n      setFailCount((count) => count + 1)\n    }\n  }\n\n  function switchMethod(next: Auth07Method) {\n    setMethod(next)\n    attempts.clearFailure()\n    setCapsLock(false)\n  }\n\n  const failure = attempts.failure\n  const errorText =\n    failure && !attempts.locked\n      ? formatLabel(labels.attempts, {\n          message:\n            failure.message ||\n            (method === \"pin\" ? labels.wrongPin : labels.wrongPassword),\n          count: failure.remaining,\n        })\n      : \"\"\n  const state = unlocked\n    ? \"unlocked\"\n    : attempts.locked\n      ? \"locked\"\n      : attempts.pending\n        ? \"pending\"\n        : errorText\n          ? \"error\"\n          : \"idle\"\n  const otherMethod = methods.find((item) => item !== method)\n  const ReasonIcon = reason === \"expired\" ? TimerOff : LockKeyhole\n\n  return (\n    <div\n      data-slot=\"auth-07\"\n      data-method={method}\n      data-state={state}\n      data-reason={reason}\n      className={cn(\n        \"relative isolate flex min-h-svh w-full flex-col overflow-hidden bg-background text-foreground\",\n        className,\n      )}\n      {...props}\n    >\n      {/* 背景字符场：中间留白，只在四周低对比度地流动 */}\n      <GlyphField\n        aria-hidden=\"true\"\n        glyphs=\"hex\"\n        fade=\"center\"\n        density={0.5}\n        fontSize={13}\n        speed={0.015}\n        className=\"absolute inset-0 min-h-0 opacity-50\"\n      />\n      <GridContainer className=\"relative flex max-w-sm flex-1 flex-col justify-center py-12\">\n        <GridSection\n          topLine\n          crosshair\n          data-slot=\"auth-07-panel\"\n          className=\"bg-background\"\n        >\n          {/* 上沿是本行自己画的 screen-line-top，十字要比默认位置下移 1px 才压在线上 */}\n          <GridCrosshair position=\"top-left\" className=\"-top-[5px]\" />\n          <GridCrosshair position=\"top-right\" className=\"-top-[5px]\" />\n          <div className=\"px-4 pt-10 pb-8 sm:px-6\">\n            <Auth07Clock\n              timeZone={timeZone}\n              locale={locale}\n              label={labels.clock}\n            />\n          </div>\n          <div className=\"flex flex-col items-center gap-3 border-t border-dashed border-edge px-4 pt-7 text-center sm:px-6\">\n            <Avatar data-slot=\"auth-07-avatar\" className=\"size-14\">\n              {user.avatar ? <AvatarImage src={user.avatar} alt=\"\" /> : null}\n              <AvatarFallback className=\"text-lg font-medium text-foreground\">\n                {Array.from(user.name.trim())[0] ?? \"\"}\n              </AvatarFallback>\n            </Avatar>\n            <div className=\"flex flex-col items-center gap-1\">\n              <h1 className=\"text-lg font-medium tracking-tight\">\n                <Greeting name={user.name} suffix=\"\" />\n              </h1>\n              {/* 解锁后原因已不成立，只留问候 */}\n              {unlocked ? null : (\n                <p\n                  data-slot=\"auth-07-reason\"\n                  className=\"flex items-center gap-1.5 text-sm text-muted-foreground\"\n                >\n                  <ReasonIcon aria-hidden=\"true\" className=\"size-3.5\" />\n                  {reason === \"expired\" ? labels.expired : labels.locked}\n                </p>\n              )}\n            </div>\n          </div>\n          <div className=\"px-4 pt-6 pb-7 sm:px-6\">\n            {unlocked ? (\n              <div\n                data-slot=\"auth-07-success\"\n                className=\"flex flex-col items-center gap-2 py-2 text-center\"\n              >\n                <span className=\"flex size-10 items-center justify-center rounded-full border border-edge bg-primary/10 text-primary\">\n                  <Check aria-hidden=\"true\" className=\"size-5\" />\n                </span>\n                <h2\n                  ref={successRef}\n                  tabIndex={-1}\n                  className=\"font-medium outline-none\"\n                >\n                  {labels.unlocked}\n                </h2>\n                <p role=\"status\" className=\"text-sm text-muted-foreground\">\n                  {formatLabel(labels.unlockedDescription, { name: user.name })}\n                </p>\n              </div>\n            ) : (\n              <form\n                noValidate\n                aria-label={labels.form}\n                data-slot=\"auth-07-form\"\n                onSubmit={(event) => {\n                  event.preventDefault()\n                  void submit(method, method === \"pin\" ? pin : password)\n                }}\n                className=\"flex flex-col gap-2\"\n              >\n                {/* 给密码管理器识别账号用，不显示 */}\n                {method === \"password\" ? (\n                  <input\n                    type=\"text\"\n                    name=\"username\"\n                    autoComplete=\"username\"\n                    value={user.email ?? user.name}\n                    readOnly\n                    hidden\n                  />\n                ) : null}\n                <div ref={fieldScope} data-slot=\"auth-07-field\">\n                  {method === \"pin\" ? (\n                    <Auth07PinField\n                      inputRef={pinRef}\n                      length={length}\n                      value={pin}\n                      onChange={(value) => {\n                        setPin(value)\n                        attempts.clearFailure()\n                      }}\n                      onComplete={(value) => void submit(\"pin\", value)}\n                      label={formatLabel(labels.pin, { length })}\n                      invalid={!!errorText}\n                      describedBy={messageId}\n                      disabled={disabled}\n                    />\n                  ) : (\n                    <Auth07PasswordField\n                      inputRef={passwordRef}\n                      label={labels.password}\n                      value={password}\n                      onValueChange={(value) => {\n                        setPassword(value)\n                        attempts.clearFailure()\n                      }}\n                      onCapsLockChange={setCapsLock}\n                      showLabel={labels.showPassword}\n                      hideLabel={labels.hidePassword}\n                      invalid={!!errorText}\n                      describedBy={messageId}\n                      disabled={disabled}\n                    />\n                  )}\n                </div>\n                {/* 预留一行，错误、倒计时、大写锁定提示出现时按钮不跳动 */}\n                <div\n                  data-slot=\"auth-07-message\"\n                  className=\"flex min-h-5 flex-col gap-1 text-xs leading-5\"\n                >\n                  {attempts.locked ? (\n                    <>\n                      {/* 倒计时只给眼睛看；读屏在锁定开始时播报一次 */}\n                      <p\n                        id={messageId}\n                        data-slot=\"auth-07-lockout\"\n                        className=\"text-destructive tabular-nums\"\n                      >\n                        {formatLabel(labels.lockedOut, {\n                          seconds: attempts.remaining,\n                        })}\n                      </p>\n                      <p role=\"alert\" className=\"sr-only\">\n                        {formatLabel(labels.lockedOut, {\n                          seconds: attempts.lockTotal,\n                        })}\n                      </p>\n                    </>\n                  ) : errorText ? (\n                    <p\n                      id={messageId}\n                      role=\"alert\"\n                      data-slot=\"auth-07-error\"\n                      className=\"text-destructive\"\n                    >\n                      {errorText}\n                    </p>\n                  ) : null}\n                  {method === \"password\" && capsLock && !attempts.locked ? (\n                    <p\n                      role=\"status\"\n                      data-slot=\"auth-07-caps-lock\"\n                      className=\"text-muted-foreground\"\n                    >\n                      {labels.capsLock}\n                    </p>\n                  ) : null}\n                </div>\n                <Button\n                  type=\"submit\"\n                  size=\"lg\"\n                  className=\"w-full\"\n                  disabled={disabled}\n                >\n                  {attempts.pending ? (\n                    <>\n                      <Loader2 aria-hidden=\"true\" className=\"animate-spin\" />\n                      {labels.unlocking}\n                    </>\n                  ) : (\n                    labels.unlock\n                  )}\n                </Button>\n                {otherMethod ? (\n                  <Button\n                    type=\"button\"\n                    variant=\"link\"\n                    size=\"lg\"\n                    data-slot=\"auth-07-switch-method\"\n                    disabled={attempts.pending}\n                    className=\"self-center text-muted-foreground hover:text-foreground\"\n                    onClick={() => switchMethod(otherMethod)}\n                  >\n                    {otherMethod === \"pin\" ? labels.usePin : labels.usePassword}\n                  </Button>\n                ) : null}\n              </form>\n            )}\n          </div>\n        </GridSection>\n        {(onSwitchAccount || onSignOut) && !unlocked ? (\n          <div\n            data-slot=\"auth-07-footer\"\n            className=\"flex items-center justify-center gap-2 pt-4 text-sm\"\n          >\n            {onSwitchAccount ? (\n              <Button\n                type=\"button\"\n                variant=\"link\"\n                size=\"lg\"\n                className=\"text-muted-foreground hover:text-foreground\"\n                onClick={onSwitchAccount}\n              >\n                {labels.switchAccount}\n              </Button>\n            ) : null}\n            {onSwitchAccount && onSignOut ? (\n              <span\n                aria-hidden=\"true\"\n                className=\"size-1 rounded-full bg-edge\"\n              />\n            ) : null}\n            {onSignOut ? (\n              <Button\n                type=\"button\"\n                variant=\"link\"\n                size=\"lg\"\n                className=\"text-muted-foreground hover:text-foreground\"\n                onClick={onSignOut}\n              >\n                {labels.signOut}\n              </Button>\n            ) : null}\n          </div>\n        ) : null}\n      </GridContainer>\n    </div>\n  )\n}\n\nexport { Auth07 }\nexport type {\n  Auth07Method,\n  Auth07Props,\n  Auth07Reason,\n  Auth07User,\n} from \"./types\"\nexport type { Auth07Labels } from \"./config\"\n",
      "type": "registry:component",
      "target": "@components/auth-07/auth-07.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/hooks/use-now.ts",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\n// 全页面共用一个对齐整秒的定时器：多个时钟同时挂载也只有一个 setTimeout 在跑，\n// 并且所有实例的秒数在同一帧跳动。\nconst listeners = new Set<() => void>()\nlet timer: number | undefined\n\nfunction schedule() {\n  timer = window.setTimeout(\n    () => {\n      listeners.forEach((listener) => listener())\n      if (listeners.size) schedule()\n    },\n    1005 - (Date.now() % 1000),\n  ) // 多等 5ms，避免定时器提前触发时读到上一秒\n}\n\nfunction subscribe(listener: () => void) {\n  listeners.add(listener)\n  if (listeners.size === 1) schedule()\n  return () => {\n    listeners.delete(listener)\n    if (!listeners.size) window.clearTimeout(timer)\n  }\n}\n\n/**\n * 当前时间的毫秒时间戳，按 `step` 对齐（默认每秒）。\n * 服务端渲染与水合期间返回 `null`，水合完成后才给出真实时间，\n * 静态导出的 HTML 因此永远不会带着过期的时间。\n *\n * @param step 对齐粒度（毫秒）；快照不变时组件不会重新渲染，所以只显示分钟的组件传 `60_000` 即可\n */\nfunction useNow(step = 1000): number | null {\n  return React.useSyncExternalStore(\n    subscribe,\n    () => Math.floor(Date.now() / step) * step,\n    () => null,\n  )\n}\n\nexport { useNow }\n",
      "type": "registry:hook",
      "target": "hooks/use-now.ts"
    },
    {
      "path": "src/registry/blocks/auth-07/page.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { Button } from \"@/components/ui/button\"\nimport { Auth07 } from \"@/components/auth-07/auth-07\"\n\n/** 演示后端仅用于体验界面，接入时替换为真实的会话验证接口。 */\nexport default function LockScreenPage() {\n  // 换一个 key 就是重新锁定：组件回到初始状态\n  const [session, setSession] = React.useState(0)\n  const [unlocked, setUnlocked] = React.useState(false)\n  const [notice, setNotice] = React.useState(\"\")\n  return (\n    <main data-slot=\"auth-07-demo\" className=\"relative bg-background\">\n      <div className=\"absolute inset-x-0 top-0 z-20 flex items-center justify-between gap-3 px-4 pt-3 text-xs text-muted-foreground\">\n        <p>演示密码 yiui2026 · PIN 123456</p>\n        {unlocked ? (\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            onClick={() => {\n              setUnlocked(false)\n              setNotice(\"\")\n              setSession((value) => value + 1)\n            }}\n          >\n            重新锁定\n          </Button>\n        ) : null}\n      </div>\n      <Auth07\n        key={session}\n        user={{ name: \"林薇\", email: \"linwei@example.com\" }}\n        maxAttempts={3}\n        lockSeconds={5}\n        onUnlock={async ({ method, secret }) => {\n          await new Promise((resolve) => setTimeout(resolve, 350))\n          if (method === \"password\" && secret !== \"yiui2026\")\n            throw new Error(\"密码错误\")\n          if (method === \"pin\" && secret !== \"123456\")\n            throw new Error(\"PIN 错误\")\n        }}\n        onSuccess={() => setUnlocked(true)}\n        onSwitchAccount={() => setNotice(\"接入后在这里打开账号选择页\")}\n        onSignOut={() => setNotice(\"接入后在这里清除会话并返回登录页\")}\n      />\n      <p\n        role=\"status\"\n        className=\"absolute inset-x-0 bottom-3 z-20 px-4 text-center text-xs text-muted-foreground\"\n      >\n        {notice}\n      </p>\n    </main>\n  )\n}\n",
      "type": "registry:page",
      "target": "app/lock/page.tsx"
    },
    {
      "path": "src/registry/blocks/auth-07/types.ts",
      "content": "import type * as React from \"react\"\nimport type { Auth07Labels } from \"./config\"\n\ntype Auth07Method = \"password\" | \"pin\"\ntype Auth07Reason = \"locked\" | \"expired\"\ntype Auth07User = {\n  /** 显示在问候语里；没有头像时取第一个字作为占位 */\n  name: string\n  email?: string\n  /** 头像地址 */\n  avatar?: string\n}\n\ntype Auth07Props = Omit<React.ComponentProps<\"div\">, \"onSuccess\"> & {\n  /** 当前登录的用户。 */\n  user: Auth07User\n  /**\n   * 验证密码或 PIN，失败时抛出 Error；错误对象带数字属性 `retryAfter`（秒）时立即锁定这么久。\n   */\n  onUnlock: (values: { method: Auth07Method; secret: string }) => Promise<void>\n  /** 验证成功后的通知。 */\n  onSuccess?: (values: { method: Auth07Method }) => void\n  /** 切换账号；未传时不显示入口。 */\n  onSwitchAccount?: () => void\n  /** 退出登录；未传时不显示入口。 */\n  onSignOut?: () => void\n  /** 锁屏原因：手动锁定或会话过期。@default \"locked\" */\n  reason?: Auth07Reason\n  /** 可用的验证方式，只有一种时不显示切换链接。@default [\"password\", \"pin\"] */\n  methods?: Auth07Method[]\n  /** 受控的验证方式。 */\n  method?: Auth07Method\n  /** 初始验证方式；默认取 `methods` 的第一项。 */\n  defaultMethod?: Auth07Method\n  /** 验证方式变化通知。 */\n  onMethodChange?: (method: Auth07Method) => void\n  /** PIN 位数，范围 4–8。@default 6 */\n  pinLength?: number\n  /** 连续失败多少次后锁定。@default 5 */\n  maxAttempts?: number\n  /** 锁定秒数。@default 30 */\n  lockSeconds?: number\n  /** 时钟使用的 IANA 时区；未传时在挂载后取浏览器时区。 */\n  timeZone?: string\n  /** 时间与日期的区域格式。@default \"zh-CN\" */\n  locale?: string\n  /** 覆盖默认中文文案。 */\n  labels?: Partial<Auth07Labels>\n}\n\nexport type { Auth07Method, Auth07Props, Auth07Reason, Auth07User }\n",
      "type": "registry:component",
      "target": "@components/auth-07/types.ts"
    },
    {
      "path": "src/registry/blocks/auth-07/config.ts",
      "content": "const DEFAULT_LABELS = {\n  /** 根节点的读屏名称 */\n  region: \"锁屏\",\n  /** 时钟区的读屏名称 */\n  clock: \"当前时间\",\n  /** reason=\"locked\" 时的原因说明 */\n  locked: \"屏幕已锁定\",\n  /** reason=\"expired\" 时的原因说明 */\n  expired: \"登录已过期，请重新验证身份\",\n  /** 验证表单的读屏名称 */\n  form: \"验证身份\",\n  password: \"密码\",\n  /** PIN 输入的读屏名称；{length} 为位数 */\n  pin: \"PIN 码，共 {length} 位\",\n  showPassword: \"显示密码\",\n  hidePassword: \"隐藏密码\",\n  capsLock: \"大写锁定已开启\",\n  unlock: \"解锁\",\n  unlocking: \"验证中…\",\n  usePin: \"改用 PIN\",\n  usePassword: \"改用密码\",\n  switchAccount: \"切换账号\",\n  signOut: \"退出登录\",\n  /** 回调抛出的错误没有 message 时使用 */\n  wrongPassword: \"密码错误\",\n  wrongPin: \"PIN 错误\",\n  /** 验证失败后的提示；{message} 为回调抛出的原因，{count} 为剩余次数 */\n  attempts: \"{message}，还可以尝试 {count} 次\",\n  /** 锁定期间的倒计时；{seconds} 为剩余秒数 */\n  lockedOut: \"尝试次数过多，请 {seconds} 秒后再试\",\n  unlocked: \"已解锁\",\n  /** 解锁后的说明；{name} 为用户名 */\n  unlockedDescription: \"欢迎回来，{name}\",\n}\ntype Auth07Labels = 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 { Auth07Labels }\n",
      "type": "registry:component",
      "target": "@components/auth-07/config.ts"
    },
    {
      "path": "src/registry/blocks/auth-07/use-auth-form.ts",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\ntype UnlockFailure = {\n  /** 回调抛出的原因，没有时为空字符串 */\n  message: string\n  /** 本次失败后还能再试几次；进入锁定时为 0 */\n  remaining: number\n}\n\n/** 错误对象上的 `retryAfter`（秒），只接受有限正数。 */\nfunction readRetryAfter(caught: unknown) {\n  if (typeof caught !== \"object\" || caught === null) return 0\n  const value = (caught as { retryAfter?: unknown }).retryAfter\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0\n    ? Math.ceil(value)\n    : 0\n}\n\n/**\n * 解锁请求：同步锁拦截回车与 PIN 自动提交的重复请求，累计失败次数，\n * 达到上限或服务端给出 `retryAfter` 时锁定一段时间，到时自动恢复并清零。\n */\nfunction useUnlockAttempts({\n  maxAttempts,\n  lockSeconds,\n}: {\n  maxAttempts: number\n  lockSeconds: number\n}) {\n  const lock = React.useRef(false)\n  const failures = React.useRef(0)\n  const [pending, setPending] = React.useState(false)\n  const [failure, setFailure] = React.useState<UnlockFailure | null>(null)\n  const [deadline, setDeadline] = React.useState(0)\n  const [remaining, setRemaining] = React.useState(0)\n  // 进入锁定时的总秒数：读屏只在锁定开始时播报一次，不跟着倒计时逐秒念\n  const [lockTotal, setLockTotal] = React.useState(0)\n\n  React.useEffect(() => {\n    if (!deadline) return\n    const tick = () => {\n      const left = Math.max(0, Math.ceil((deadline - Date.now()) / 1000))\n      setRemaining(left)\n      if (left === 0) {\n        failures.current = 0\n        setDeadline(0)\n        setLockTotal(0)\n        setFailure(null)\n      }\n    }\n    tick()\n    const timer = window.setInterval(tick, 250)\n    return () => window.clearInterval(timer)\n  }, [deadline])\n\n  function startLock(seconds: number) {\n    setRemaining(seconds)\n    setLockTotal(seconds)\n    // 只在失败回调里读取时间，不参与服务端渲染\n    setDeadline(Date.now() + seconds * 1000)\n  }\n\n  const locked = deadline > 0\n\n  async function run(action: () => Promise<void>) {\n    if (lock.current || locked) return false\n    lock.current = true\n    setPending(true)\n    setFailure(null)\n    try {\n      await action()\n      failures.current = 0\n      return true\n    } catch (caught) {\n      const retryAfter = readRetryAfter(caught)\n      failures.current += 1\n      const left = Math.max(0, maxAttempts - failures.current)\n      setFailure({\n        message: caught instanceof Error ? caught.message : \"\",\n        remaining: retryAfter ? 0 : left,\n      })\n      if (retryAfter) startLock(retryAfter)\n      else if (left === 0) startLock(lockSeconds)\n      return false\n    } finally {\n      lock.current = false\n      setPending(false)\n    }\n  }\n\n  return {\n    pending,\n    failure,\n    clearFailure: () => setFailure(null),\n    locked,\n    remaining,\n    lockTotal,\n    run,\n  }\n}\n\nexport { readRetryAfter, useUnlockAttempts }\nexport type { UnlockFailure }\n",
      "type": "registry:component",
      "target": "@components/auth-07/use-auth-form.ts"
    },
    {
      "path": "src/registry/blocks/auth-07/form-parts.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { OTPInputContext } from \"input-otp\"\nimport { Eye, EyeOff } from \"lucide-react\"\nimport { Button } from \"@/components/ui/button\"\nimport { InputOTP, InputOTPGroup } from \"@/components/ui/input-otp\"\nimport { cn } from \"@/lib/utils\"\nimport { useNow } from \"@/hooks/use-now\"\nimport { BarField } from \"@/components/ui/bar-field/bar-field\"\nimport { LocalTime } from \"@/components/ui/local-time/local-time\"\n\nfunction subscribeNothing() {\n  return () => {}\n}\n\n/** 浏览器时区；服务端与水合期间为 null，挂载后才读取，首屏 HTML 因此不带任何时区信息。 */\nfunction useBrowserTimeZone() {\n  return React.useSyncExternalStore(\n    subscribeNothing,\n    () => Intl.DateTimeFormat().resolvedOptions().timeZone,\n    () => null,\n  )\n}\n\nconst dateFormatters = new Map<string, Intl.DateTimeFormat>()\nfunction formatDate(now: number, locale: string, timeZone: string) {\n  const key = `${locale}|${timeZone}`\n  let formatter = dateFormatters.get(key)\n  if (!formatter) {\n    formatter = new Intl.DateTimeFormat(locale, {\n      timeZone,\n      month: \"long\",\n      day: \"numeric\",\n      weekday: \"long\",\n    })\n    dateFormatters.set(key, formatter)\n  }\n  return formatter.format(now)\n}\n\n/** 大号时:分与日期星期；挂载前用同尺寸的占位，不读取当前时间。 */\nfunction Auth07Clock({\n  timeZone: timeZoneProp,\n  locale,\n  label,\n}: {\n  timeZone?: string\n  locale: string\n  label: string\n}) {\n  const browserZone = useBrowserTimeZone()\n  const timeZone = timeZoneProp ?? browserZone\n  const now = useNow(60_000)\n  const date = now !== null && timeZone ? formatDate(now, locale, timeZone) : \"\"\n  return (\n    <div\n      data-slot=\"auth-07-clock\"\n      data-ready={date ? \"\" : undefined}\n      role=\"group\"\n      aria-label={label}\n      className=\"flex flex-col items-center gap-1.5\"\n    >\n      <p className=\"text-5xl leading-none font-light tracking-tight tabular-nums sm:text-7xl\">\n        {timeZone ? (\n          <LocalTime\n            timeZone={timeZone}\n            locale={locale}\n            showSeconds={false}\n            showDifference={false}\n          />\n        ) : (\n          <span\n            data-slot=\"auth-07-clock-placeholder\"\n            aria-hidden=\"true\"\n            className=\"text-muted-foreground\"\n          >\n            --:--\n          </span>\n        )}\n      </p>\n      {/* 日期行固定一行高度，挂载前后不跳动 */}\n      <p className=\"h-5 text-sm text-muted-foreground\">{date}</p>\n    </div>\n  )\n}\n\n/** 方条密码框：显示/隐藏切换，按键时检测大写锁定。 */\nfunction Auth07PasswordField({\n  inputRef,\n  label,\n  value,\n  onValueChange,\n  onCapsLockChange,\n  showLabel,\n  hideLabel,\n  invalid,\n  describedBy,\n  disabled,\n}: {\n  inputRef: React.Ref<HTMLInputElement>\n  label: string\n  value: string\n  onValueChange: (value: string) => void\n  onCapsLockChange: (on: boolean) => void\n  showLabel: string\n  hideLabel: string\n  invalid: boolean\n  describedBy?: string\n  disabled: boolean\n}) {\n  const [visible, setVisible] = React.useState(false)\n  const detect = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    // 合成事件（自动填充等）没有修饰键状态，跳过\n    if (typeof event.getModifierState === \"function\")\n      onCapsLockChange(event.getModifierState(\"CapsLock\"))\n  }\n  return (\n    <BarField\n      inputRef={inputRef}\n      name=\"password\"\n      type={visible ? \"text\" : \"password\"}\n      autoComplete=\"current-password\"\n      label={label}\n      size=\"lg\"\n      value={value}\n      onValueChange={onValueChange}\n      onKeyDown={detect}\n      onKeyUp={detect}\n      onBlur={() => onCapsLockChange(false)}\n      aria-invalid={invalid || undefined}\n      aria-describedby={describedBy}\n      disabled={disabled}\n      suffix={\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon-lg\"\n          disabled={disabled}\n          onClick={() => setVisible((current) => !current)}\n          aria-label={visible ? hideLabel : showLabel}\n          aria-pressed={visible}\n          className=\"shrink-0 text-muted-foreground hover:text-foreground\"\n        >\n          {visible ? <EyeOff aria-hidden=\"true\" /> : <Eye aria-hidden=\"true\" />}\n        </Button>\n      }\n    />\n  )\n}\n\n/** PIN 的一格：只显示圆点，不显示数字。 */\nfunction Auth07PinSlot({\n  index,\n  invalid,\n}: {\n  index: number\n  invalid: boolean\n}) {\n  const context = React.useContext(OTPInputContext)\n  const slot = context?.slots[index]\n  return (\n    <div\n      data-slot=\"auth-07-pin-slot\"\n      data-active={slot?.isActive || undefined}\n      data-filled={slot?.char ? \"\" : undefined}\n      aria-invalid={invalid || undefined}\n      className={cn(\n        \"relative flex h-9 min-w-0 flex-1 items-center justify-center border-y border-r border-edge bg-muted/60 transition-colors first:rounded-l-md first:border-l last:rounded-r-md pointer-coarse:h-11\",\n        \"data-active:z-10 data-active:border-foreground/25 data-active:bg-background\",\n        \"aria-invalid:border-destructive\",\n      )}\n    >\n      {slot?.char ? (\n        <span\n          aria-hidden=\"true\"\n          className=\"size-2.5 rounded-full bg-foreground\"\n        />\n      ) : null}\n      {slot?.hasFakeCaret ? (\n        <span\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-0 flex items-center justify-center\"\n        >\n          <span className=\"h-4 w-px animate-caret-blink bg-foreground duration-1000\" />\n        </span>\n      ) : null}\n    </div>\n  )\n}\n\n/** 数字 PIN：输满自动提交，格子里只显示圆点。 */\nfunction Auth07PinField({\n  inputRef,\n  length,\n  value,\n  onChange,\n  onComplete,\n  label,\n  invalid,\n  describedBy,\n  disabled,\n}: {\n  inputRef: React.Ref<HTMLInputElement>\n  length: number\n  value: string\n  onChange: (value: string) => void\n  onComplete: (value: string) => void\n  label: string\n  invalid: boolean\n  describedBy?: string\n  disabled: boolean\n}) {\n  return (\n    <div data-slot=\"auth-07-pin\">\n      <InputOTP\n        ref={inputRef}\n        maxLength={length}\n        value={value}\n        onChange={onChange}\n        onComplete={onComplete}\n        pattern=\"^[0-9]*$\"\n        inputMode=\"numeric\"\n        autoComplete=\"off\"\n        aria-label={label}\n        aria-invalid={invalid || undefined}\n        aria-describedby={describedBy}\n        disabled={disabled}\n        containerClassName=\"w-full\"\n      >\n        <InputOTPGroup className=\"w-full rounded-md\">\n          {Array.from({ length }, (_, index) => (\n            <Auth07PinSlot key={index} index={index} invalid={invalid} />\n          ))}\n        </InputOTPGroup>\n      </InputOTP>\n    </div>\n  )\n}\n\nexport { Auth07Clock, Auth07PasswordField, Auth07PinField }\n",
      "type": "registry:component",
      "target": "@components/auth-07/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"
}
