{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "review-14",
  "title": "Secret request",
  "description": "A masked field for a key that never enters the thread, whose prefix check answers as you type and turns right, then Save folds the card into where the key went and its last four characters.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/drawn-check.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/review/review-14.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useEffect, useId, useImperativeHandle, useRef, useState } from 'react';\n\nimport {\n  typingSteps,\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  pressedSolidOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CircleDashedIcon,\n  CircleIcon,\n  EyeIcon,\n  EyeOffIcon,\n  FileIcon,\n  FileInputIcon,\n  KeyIcon,\n  PencilIcon,\n  TriangleAlertIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { fadePresence } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { DrawnCheck } from '@/registry/ndeko/ui/drawn-check';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\n\nimport { SettledLine } from './_parts/settled-line';\nimport { useFocusHandOff } from './_parts/use-focus-hand-off';\n\ntype SecretPhase = 'editing' | 'saving' | 'saved';\n\nexport type PrefixStatus = 'empty' | 'typing' | 'right' | 'wrong';\n\n/** The control a demonstration holds down. */\nexport type SecretRequestPress = 'save' | 'reveal' | 'paste' | 'replace';\n\nexport type SecretRequestHandle = {\n  save: () => void;\n  replace: () => void;\n  toggleReveal: () => void;\n};\n\nconst SAVING_MS = 700;\n\nconst SAVE_LABELS: Record<MorphState, string> = {\n  idle: 'Save',\n  busy: 'Saving',\n  done: 'Saved',\n};\n\nconst LAST_CHARACTERS = 4;\n\nexport function prefixStatusOf(value: string, expectedPrefix: string) {\n  if (value === '') {\n    return 'empty';\n  }\n  if (value.startsWith(expectedPrefix)) {\n    return 'right';\n  }\n  if (expectedPrefix.startsWith(value)) {\n    return 'typing';\n  }\n  return 'wrong';\n}\n\nfunction spokenWordOf(status: PrefixStatus, expectedPrefix: string) {\n  if (status === 'right') {\n    return 'The prefix is right';\n  }\n  if (status === 'wrong') {\n    return `Wrong prefix, it should start with ${expectedPrefix}`;\n  }\n  return '';\n}\n\nfunction saveStateOf(phase: SecretPhase): MorphState {\n  if (phase === 'saving') {\n    return 'busy';\n  }\n  return 'idle';\n}\n\nfunction viewOf(phase: SecretPhase) {\n  if (phase === 'saved') {\n    return 'saved';\n  }\n  return 'form';\n}\n\nfunction inputTypeOf(isRevealed: boolean) {\n  if (isRevealed) {\n    return 'text';\n  }\n  return 'password';\n}\n\nfunction revealLabelOf(isRevealed: boolean) {\n  if (isRevealed) {\n    return 'Hide the key';\n  }\n  return 'Show the key';\n}\n\nfunction fieldRingOf(status: PrefixStatus) {\n  if (status === 'right') {\n    return 'ring-success/50';\n  }\n  return undefined;\n}\n\nfunction maskedEndOf(lastFour: string) {\n  return `••••${lastFour}`;\n}\n\nfunction shakeOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return { x: 0 };\n  }\n  return { x: [0, -4, 4, -2, 0] };\n}\n\nfunction Prefix({ children }: { children: string }) {\n  return <code className='font-mono'>{children}</code>;\n}\n\nfunction CheckLine({\n  status,\n  expectedPrefix,\n}: {\n  status: PrefixStatus;\n  expectedPrefix: string;\n}) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const shake = shakeOf(shouldReduceMotion);\n\n  if (status === 'right') {\n    return (\n      <span className='text-success-foreground inline-flex items-center gap-1.5'>\n        <DrawnCheck tone='success' entrance='draw' className='size-4' />\n        Prefix is right\n      </span>\n    );\n  }\n  if (status === 'wrong') {\n    return (\n      <motion.span\n        animate={shake}\n        transition={{ duration: 0.24 }}\n        className='text-destructive-ink inline-flex items-center gap-1.5'\n      >\n        <TriangleAlertIcon className='size-3.5 shrink-0' />\n        <span>\n          Wrong prefix, it should start with <Prefix>{expectedPrefix}</Prefix>\n        </span>\n      </motion.span>\n    );\n  }\n  if (status === 'typing') {\n    return (\n      <span className='text-muted-foreground inline-flex items-center gap-1.5'>\n        <CircleIcon className='size-3.5 shrink-0' />\n        Matching so far\n      </span>\n    );\n  }\n  return (\n    <span className='text-muted-foreground inline-flex items-center gap-1.5'>\n      <CircleDashedIcon className='size-3.5 shrink-0' />\n      <span>\n        Should start with <Prefix>{expectedPrefix}</Prefix>\n      </span>\n    </span>\n  );\n}\n\nexport type SecretRequestProps = {\n  /** The name of the variable the key is saved under: `LEDGER_API_KEY`. */\n  name: string;\n  /** What the key is for, in a sentence. */\n  purpose: string;\n  /** The file the key is saved in: `.env.local`. */\n  destination: string;\n  /** How a right key starts: `kl_test_`. */\n  expectedPrefix: string;\n  /** Shorter keys cannot be saved. */\n  minLength?: number;\n  value: string;\n  onValueChange: (value: string) => void;\n  /** Receives the key once, when Save is pressed. The card keeps only its last four characters. */\n  onSave?: (value: string) => void;\n  onReplace?: () => void;\n  /** Putting the card back to its first state: change this number. */\n  resetToken?: number;\n  handleRef?: React.Ref<SecretRequestHandle>;\n  pressed?: SecretRequestPress | null;\n  /** A demonstration is not read aloud. */\n  isDemonstrating?: boolean;\n  className?: string;\n};\n\nexport function SecretRequest({\n  name,\n  purpose,\n  destination,\n  expectedPrefix,\n  minLength = 20,\n  value,\n  onValueChange,\n  onSave,\n  onReplace,\n  resetToken = 0,\n  handleRef,\n  pressed = null,\n  isDemonstrating = false,\n  className,\n}: SecretRequestProps) {\n  const [phase, setPhase] = useState<SecretPhase>('editing');\n  const [isRevealed, setIsRevealed] = useState(false);\n  const [lastFour, setLastFour] = useState('');\n  const [notice, setNotice] = useState('');\n  const [seenToken, setSeenToken] = useState(resetToken);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const inputId = useId();\n  const checkId = useId();\n  const { schedule, clearAll } = useTimeouts();\n  const fade = fadePresence();\n  const view = viewOf(phase);\n  const { rootRef, markIfFocusInside } = useFocusHandOff(view);\n  const status = prefixStatusOf(value, expectedPrefix);\n  const isLongEnough = value.length >= minLength;\n  const isSavable = status === 'right' && isLongEnough;\n  const isBusy = phase === 'saving';\n  const isWrong = status === 'wrong';\n  const spoken = spokenWordOf(status, expectedPrefix);\n  const needsMore = status === 'right' && !isLongEnough;\n\n  useEffect(() => {\n    clearAll();\n  }, [resetToken, clearAll]);\n\n  if (seenToken !== resetToken) {\n    setSeenToken(resetToken);\n    setPhase('editing');\n    setIsRevealed(false);\n    setLastFour('');\n  }\n\n  function save() {\n    if (isBusy) {\n      return;\n    }\n    if (!isSavable) {\n      setNotice(`Check the key first, it should start with ${expectedPrefix}`);\n      return;\n    }\n    const secret = value;\n    setLastFour(secret.slice(-LAST_CHARACTERS));\n    setIsRevealed(false);\n    setPhase('saving');\n    onSave?.(secret);\n    schedule(() => {\n      markIfFocusInside();\n      onValueChange('');\n      setPhase('saved');\n      setNotice(`Saved to ${destination}`);\n    }, SAVING_MS);\n  }\n\n  function replace() {\n    markIfFocusInside();\n    onValueChange('');\n    setLastFour('');\n    setPhase('editing');\n    setNotice('Paste the new key');\n    onReplace?.();\n  }\n\n  function toggleReveal() {\n    setIsRevealed((current) => !current);\n  }\n\n  useImperativeHandle(handleRef, () => ({ save, replace, toggleReveal }));\n\n  async function paste() {\n    try {\n      const text = await navigator.clipboard.readText();\n      onValueChange(text.trim());\n      inputRef.current?.focus();\n    } catch {\n      setNotice('Paste is blocked here, type the key or press Control V');\n    }\n  }\n\n  function changeValue(event: React.ChangeEvent<HTMLInputElement>) {\n    onValueChange(event.target.value);\n  }\n\n  function saveFromKey(event: React.KeyboardEvent<HTMLInputElement>) {\n    const isEnter = event.key === 'Enter';\n    const isComposing = event.nativeEvent.isComposing;\n    if (isEnter && !isComposing) {\n      event.preventDefault();\n      save();\n    }\n  }\n\n  const spokenStatus = spokenUnless(isDemonstrating, spoken);\n  const spokenNotice = spokenUnless(isDemonstrating, notice);\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\n        'surface-raised @container overflow-hidden rounded-xl',\n        className\n      )}\n    >\n      <AnimatedSize>\n        <AnimatePresence initial={false} mode='popLayout'>\n          <motion.div key={view} {...fade}>\n            {view === 'saved' && (\n              <SettledLine\n                icon={<DrawnCheck tone='success' entrance='draw' />}\n                actionLabel='Replace'\n                actionIcon={<PencilIcon />}\n                onAction={replace}\n                isActionPressed={pressed === 'replace'}\n              >\n                <span className='text-muted-foreground'>Saved to </span>\n                <code className='font-mono font-medium'>{destination}</code>\n                <span className='text-muted-foreground'>, ending in </span>\n                <code className='font-mono font-medium tabular-nums'>\n                  {maskedEndOf(lastFour)}\n                </code>\n              </SettledLine>\n            )}\n            {view === 'form' && (\n              <div className='flex flex-col gap-3.5 p-4'>\n                <div className='flex items-start gap-3'>\n                  <span className='keycap-3d text-muted-foreground flex size-8 shrink-0 items-center justify-center rounded-lg'>\n                    <KeyIcon className='size-4' />\n                  </span>\n                  <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n                    <p className='truncate font-mono text-[13px] font-medium'>\n                      {name}\n                    </p>\n                    <p className='text-muted-foreground text-xs leading-5'>\n                      {purpose}\n                    </p>\n                  </div>\n                </div>\n                <p className='text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs'>\n                  Saved to\n                  <Badge variant='outline' className='font-mono'>\n                    <FileIcon />\n                    {destination}\n                  </Badge>\n                  on this machine, never in the chat\n                </p>\n                <div className='flex flex-col gap-1.5'>\n                  <label htmlFor={inputId} className='text-xs font-medium'>\n                    Paste the key\n                  </label>\n                  <div className='flex items-start gap-2'>\n                    <div className='relative min-w-0 flex-1'>\n                      <Input\n                        ref={inputRef}\n                        id={inputId}\n                        type={inputTypeOf(isRevealed)}\n                        value={value}\n                        disabled={isBusy}\n                        autoComplete='off'\n                        autoCapitalize='off'\n                        spellCheck={false}\n                        data-1p-ignore=''\n                        data-lpignore='true'\n                        data-hand-off=''\n                        aria-invalid={isWrong}\n                        aria-describedby={checkId}\n                        onChange={changeValue}\n                        onKeyDown={saveFromKey}\n                        className={cn('pe-9 font-mono', fieldRingOf(status))}\n                      />\n                      <Button\n                        type='button'\n                        variant='ghost'\n                        size='icon-sm'\n                        aria-label={revealLabelOf(isRevealed)}\n                        aria-pressed={isRevealed}\n                        onClick={toggleReveal}\n                        className={cn(\n                          'text-muted-foreground absolute end-0.5 top-0.5 size-7',\n                          pressedQuietOf(pressed === 'reveal')\n                        )}\n                      >\n                        <Swap swapKey={String(isRevealed)}>\n                          {isRevealed && <EyeOffIcon />}\n                          {!isRevealed && <EyeIcon />}\n                        </Swap>\n                      </Button>\n                    </div>\n                    <Button\n                      type='button'\n                      variant='outline'\n                      size='default'\n                      disabled={isBusy}\n                      onClick={paste}\n                      className={pressedQuietOf(pressed === 'paste')}\n                    >\n                      <FileInputIcon />\n                      Paste\n                    </Button>\n                  </div>\n                  <p id={checkId} className='flex min-h-5 items-center text-xs'>\n                    <Swap swapKey={status}>\n                      <CheckLine\n                        status={status}\n                        expectedPrefix={expectedPrefix}\n                      />\n                    </Swap>\n                  </p>\n                </div>\n                <div className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n                  <MorphButton\n                    type='button'\n                    size='sm'\n                    state={saveStateOf(phase)}\n                    labels={SAVE_LABELS}\n                    disabled={!isSavable}\n                    onClick={save}\n                    className={pressedSolidOf(pressed === 'save')}\n                  />\n                  {needsMore && (\n                    <p className='text-muted-foreground text-xs'>\n                      The key looks short, add the rest\n                    </p>\n                  )}\n                </div>\n              </div>\n            )}\n          </motion.div>\n        </AnimatePresence>\n      </AnimatedSize>\n      <LiveRegion message={spokenStatus} />\n      <LiveRegion message={spokenNotice} />\n    </div>\n  );\n}\n\nconst FAKE_KEY = 'kl_test_not-a-real-key-9f3a';\n\nconst WRONG_START = 'pk_te';\n\nfunction restingValueOf(isResting: boolean) {\n  if (isResting) {\n    return FAKE_KEY;\n  }\n  return '';\n}\n\nfunction SecretDemo({ isResting }: { isResting: boolean }) {\n  const [value, setValue] = useState(restingValueOf(isResting));\n  const [round, setRound] = useState(0);\n  const card = useRef<SecretRequestHandle>(null);\n  const { pressed, press } = usePress<SecretRequestPress>();\n\n  function resetDemo() {\n    setValue('');\n    setRound((current) => current + 1);\n  }\n\n  function clearValue() {\n    setValue('');\n  }\n\n  const steps: AutoplayStep[] = [\n    ...typingSteps(WRONG_START, setValue, {\n      startAfter: 1400,\n      characterMs: 150,\n    }),\n    { after: 1700, run: clearValue },\n    ...typingSteps(FAKE_KEY, setValue, { startAfter: 500, characterMs: 85 }),\n    { after: 900, run: () => press('reveal') },\n    { after: PRESS_LEAD_MS, run: () => card.current?.toggleReveal() },\n    { after: 1700, run: () => press('reveal') },\n    { after: PRESS_LEAD_MS, run: () => card.current?.toggleReveal() },\n    { after: 700, run: () => press('save') },\n    { after: PRESS_LEAD_MS, run: () => card.current?.save() },\n    { after: 3000, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2000,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='flex min-h-[16rem] w-full max-w-[28rem] flex-col'>\n      <SecretRequest\n        name='LEDGER_API_KEY'\n        purpose='Lets Reviewer read your test invoices while it checks the totals'\n        destination='.env.local'\n        expectedPrefix='kl_test_'\n        value={value}\n        onValueChange={setValue}\n        resetToken={round}\n        handleRef={card}\n        pressed={pressed}\n        isDemonstrating={isAutoplaying}\n      />\n    </div>\n  );\n}\n\nexport default function Review14() {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const restKey = String(shouldReduceMotion);\n\n  return <SecretDemo key={restKey} isResting={shouldReduceMotion} />;\n}\n",
      "type": "registry:component",
      "target": "components/review/review-14.tsx"
    },
    {
      "path": "registry/ndeko/components/review/_parts/settled-line.tsx",
      "content": "'use client';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\n\ntype SettledLineProps = {\n  icon: React.ReactNode;\n  actionLabel: string;\n  actionIcon?: React.ReactNode;\n  onAction: () => void;\n  /** Shows the action held down, for a demonstration that presses it. */\n  isActionPressed?: boolean;\n  children: React.ReactNode;\n  className?: string;\n};\n\n/** What a card becomes once it is settled: one line that says what happened, and the way back. */\nexport function SettledLine({\n  icon,\n  actionLabel,\n  actionIcon,\n  onAction,\n  isActionPressed = false,\n  children,\n  className,\n}: SettledLineProps) {\n  return (\n    <div\n      className={cn(\n        'flex items-start gap-2.5 py-2.5 ps-3.5 pe-2.5 text-[13px]',\n        className\n      )}\n    >\n      <span className='mt-1 flex shrink-0 items-center'>{icon}</span>\n      <p className='min-w-0 flex-1 py-1 leading-5'>{children}</p>\n      <Button\n        type='button'\n        variant='ghost'\n        size='sm'\n        data-hand-off=''\n        onClick={onAction}\n        className={cn(\n          'text-muted-foreground shrink-0',\n          pressedQuietOf(isActionPressed)\n        )}\n      >\n        {actionIcon}\n        {actionLabel}\n      </Button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/review/_parts/settled-line.tsx"
    },
    {
      "path": "registry/ndeko/components/review/_parts/use-focus-hand-off.ts",
      "content": "'use client';\n\nimport { useCallback, useEffect, useRef } from 'react';\n\n/**\n * When a card turns into another view, the control a person just used is gone and focus would fall\n * to the page. If focus was inside the card, it goes to the last element marked `data-hand-off`\n * once the new view is in place; a demonstration never had focus there, so it never moves it.\n */\nexport function useFocusHandOff(phase: string) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const isPending = useRef(false);\n\n  const markIfFocusInside = useCallback(() => {\n    const root = rootRef.current;\n    if (!root) {\n      return;\n    }\n    isPending.current = root.contains(document.activeElement);\n  }, []);\n\n  useEffect(() => {\n    if (!isPending.current) {\n      return;\n    }\n    isPending.current = false;\n    const root = rootRef.current;\n    if (!root) {\n      return;\n    }\n    const targets = root.querySelectorAll<HTMLElement>('[data-hand-off]');\n    const target = targets[targets.length - 1];\n    target?.focus();\n  }, [phase]);\n\n  return { rootRef, markIfFocusInside };\n}\n",
      "type": "registry:component",
      "target": "components/review/_parts/use-focus-hand-off.ts"
    }
  ],
  "categories": [
    "components",
    "review"
  ],
  "type": "registry:component"
}