{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "app-auth-code",
  "type": "registry:block",
  "title": "App, one-time code",
  "description": "Enter a six-digit code: six boxes that behave as one field. Typing moves forward, Backspace moves back, arrow keys move, pasting fills every box, and the first box asks for the one-time code autofill. Idle, verifying, error and resent states.",
  "categories": [
    "app"
  ],
  "dependencies": [
    "zod@^4.6.5"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/banner.json",
    "https://ui.klarhimmel.com/r/block-kit.json",
    "https://ui.klarhimmel.com/r/button.json",
    "https://ui.klarhimmel.com/r/editing.json",
    "https://ui.klarhimmel.com/r/kit-app.json",
    "https://ui.klarhimmel.com/r/kit-form.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/blocks/app-auth-code/spec.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-auth-code/spec.ts",
      "content": "import { z } from 'zod';\nimport { defineSpec, formFields, req, t } from '../_shared/schema';\n\nconst schema = z.object({\n  eyebrow: t(60).optional(),\n  title: t(120),\n  description: t(300).optional(),\n  /** Names the group of six boxes. */\n  codeLabel: t(40),\n  /** Each box is named \"Digit 1 of 6\": digitLabel + number + `of` + 6. */\n  digitLabel: t(20),\n  of: t(10),\n  submit: t(30),\n  verifying: t(30),\n  resend: req(30),\n  /** idle, verifying (the button waits, the boxes are read-only), error (the group is marked and described), resent (a confirmation). */\n  state: z.enum(['idle', 'verifying', 'error', 'resent']),\n  messages: z.object({ error: t(120), resent: t(120) }),\n  ...formFields,\n});\n\nexport const spec = defineSpec({\n  type: 'app-auth-code',\n  aliases: ['app/auth-code'],\n  name: 'App, one-time code',\n  category: 'app',\n  role: 'body',\n  description: 'Enter a six-digit code: six boxes that behave as one field. Typing moves forward, Backspace moves back, arrow keys move, pasting fills every box, and the first box asks for the one-time code autofill. Idle, verifying, error and resent states.',\n  schema,\n  defaults: {\n    \"eyebrow\": \"Name the section\",\n    \"title\": \"Check your email\",\n    \"description\": \"Say where the code was sent and how long it works.\",\n    \"codeLabel\": \"Name the code\",\n    \"digitLabel\": \"Digit\",\n    \"of\": \"of\",\n    \"submit\": \"Verify\",\n    \"verifying\": \"Verifying…\",\n    \"resend\": \"Send a new code\",\n    \"state\": \"idle\",\n    \"messages\": {\n      \"error\": \"Say that the code is wrong or has expired and what to do next.\",\n      \"resent\": \"Say a new code was sent.\"\n    }\n  },\n});\n"
    },
    {
      "path": "src/blocks/app-auth-code/index.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-auth-code/index.tsx",
      "content": "import { useId, useRef, useState, type ClipboardEvent, type KeyboardEvent } from 'react';\nimport { Text, withHeadingLevel } from '../../editing';\nimport { cn } from '../../lib/utils';\nimport { Banner } from '../../ui/banner';\nimport { Button } from '../../ui/button';\nimport { Container, Section, SectionHeader, useEditing } from '../_shared/kit';\nimport { AppPanel, StateSlot, Swap, useSynced } from '../_shared/app-kit';\nimport { FormExtras, useFormProps } from '../_shared/form-kit';\nimport { spec } from './spec';\nimport type { BlockProps } from '../types';\nimport type { z } from 'zod';\n\nexport { spec };\ntype Props = z.infer<typeof spec.schema>;\n\nconst LENGTH = 6;\n\nfunction AppAuthCode({ props }: BlockProps<Props>) {\n  const id = useId();\n  const editing = useEditing();\n  const form = useFormProps(props);\n  const boxes = useRef<(HTMLInputElement | null)[]>([]);\n  const [digits, setDigits] = useState<string[]>(Array(LENGTH).fill(''));\n  const [again, setAgain] = useSynced(false, props.state); // \"Send a new code\" has been pressed in this block\n  const state = again && props.state !== 'verifying' ? 'resent' : props.state;\n  const invalid = state === 'error';\n  const locked = state === 'verifying';\n  const complete = digits.every(Boolean);\n  const focus = (i: number) => boxes.current[Math.max(0, Math.min(LENGTH - 1, i))]?.focus();\n  /** Writes `text` (digits only) from box `from` on; focus lands on the box after the last one written. */\n  const put = (from: number, text: string) => {\n    const clean = text.replace(/\\D/g, '').slice(0, LENGTH - from);\n    if (!clean) return;\n    setDigits((d) => d.map((v, i) => (i >= from && i < from + clean.length ? clean[i - from]! : v)));\n    focus(from + clean.length);\n  };\n  const onKey = (i: number, e: KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === 'Backspace' && !digits[i]) {\n      e.preventDefault();\n      setDigits((d) => d.map((v, k) => (k === i - 1 ? '' : v)));\n      focus(i - 1);\n    } else if (e.key === 'ArrowLeft') {\n      e.preventDefault();\n      focus(i - 1);\n    } else if (e.key === 'ArrowRight') {\n      e.preventDefault();\n      focus(i + 1);\n    }\n  };\n  const onPaste = (i: number, e: ClipboardEvent<HTMLInputElement>) => {\n    e.preventDefault();\n    put(i, e.clipboardData.getData('text'));\n  };\n  return (\n    <Section labelledBy={id}>\n      <Container width=\"narrow\" className=\"max-w-md\">\n        <SectionHeader id={id} eyebrow={props.eyebrow} title={props.title} description={props.description} />\n        <AppPanel className=\"mt-8\">\n          <form {...form} aria-busy={locked || undefined} className=\"flex flex-col gap-5 p-6 @xl:p-8\">\n            <StateSlot show={state === 'resent'}>\n              <Banner tone=\"info\">\n                <Text path={['messages', 'resent']} value={props.messages.resent} as=\"span\" />\n              </Banner>\n            </StateSlot>\n            <StateSlot show={invalid}>\n              <p id={`${id}-e`} role=\"alert\" className=\"rounded-kh-lg border border-kh-danger px-4 py-3 text-kh-small\">\n                <Text path={['messages', 'error']} value={props.messages.error} as=\"span\" />\n              </p>\n            </StateSlot>\n            <div role=\"group\" aria-labelledby={`${id}-l`} aria-describedby={invalid ? `${id}-e` : undefined} className=\"flex flex-col gap-2\">\n              <p id={`${id}-l`} className=\"text-kh-small font-medium\">\n                <Text path={['codeLabel']} value={props.codeLabel} as=\"span\" />\n              </p>\n              <div className=\"flex gap-2\">\n                {digits.map((v, i) => (\n                  <input\n                    key={i}\n                    ref={(el) => {\n                      boxes.current[i] = el;\n                    }}\n                    value={v}\n                    inputMode=\"numeric\"\n                    pattern=\"[0-9]*\"\n                    autoComplete={i === 0 ? 'one-time-code' : 'off'}\n                    aria-label={`${props.digitLabel} ${i + 1} ${props.of} ${LENGTH}`}\n                    aria-invalid={invalid || undefined}\n                    readOnly={locked}\n                    // A whole code (SMS autofill, a keyboard suggestion) can land in any box as one string: spread it.\n                    // Typing over a filled box arrives as the old digit plus the new one: keep only the new one.\n                    onChange={(e) => {\n                      const raw = e.target.value;\n                      if (raw === '') return setDigits((d) => d.map((x, k) => (k === i ? '' : x)));\n                      put(i, raw.length === 2 && v && raw.includes(v) ? raw.replace(v, '') : raw);\n                    }}\n                    onKeyDown={(e) => onKey(i, e)}\n                    onPaste={(e) => onPaste(i, e)}\n                    onFocus={(e) => e.currentTarget.select()}\n                    className={cn(\n                      'min-h-12 w-full min-w-0 rounded-kh border bg-kh-surface text-center text-kh-heading font-semibold tabular-nums text-kh-ink shadow-kh-1',\n                      'focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-(--kh-focus)',\n                      invalid ? 'border-kh-danger' : 'border-kh-line-strong',\n                    )}\n                  />\n                ))}\n              </div>\n              {editing && (\n                <p className=\"text-kh-caption text-kh-muted\">\n                  <Text path={['digitLabel']} value={props.digitLabel} as=\"span\" /> 1 <Text path={['of']} value={props.of} as=\"span\" /> {LENGTH}\n                </p>\n              )}\n              <input type=\"hidden\" name=\"code\" value={digits.join('')} />\n            </div>\n            <FormExtras {...props} />\n            <Button type=\"submit\" full disabled={locked || !complete}>\n              <Swap show={!locked}>\n                <Text path={['submit']} value={props.submit} as=\"span\" />\n              </Swap>\n              <Swap show={locked}>\n                <Text path={['verifying']} value={props.verifying} as=\"span\" />\n              </Swap>\n            </Button>\n            <Button\n              type=\"button\"\n              variant=\"ghost\"\n              full\n              disabled={locked}\n              onClick={() => {\n                setDigits(Array(LENGTH).fill(''));\n                setAgain(true);\n                focus(0);\n              }}\n            >\n              <Text path={['resend']} value={props.resend} as=\"span\" />\n            </Button>\n          </form>\n        </AppPanel>\n      </Container>\n    </Section>\n  );\n}\n\nexport default withHeadingLevel(AppAuthCode);\n"
    }
  ]
}
