{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "settings-02",
  "description": "API keys with their access, last use and creator, with unused keys flagged and a new key shown once with a copy button.",
  "registryDependencies": [
    "button",
    "input",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/details.json",
    "https://www.dashboardblocks.com/r/radix/settings.json",
    "https://www.dashboardblocks.com/r/radix/status-label.json",
    "https://www.dashboardblocks.com/r/radix/format.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/settings/settings-02.tsx",
      "content": "'use client'\n\nimport {\n  BlockReady,\n  BlockStateProvider,\n  BlockStateRows,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport { Details } from '@/registry/components/dashboardblocks/details'\nimport {\n  CopyButton,\n  daysBetween,\n  maskSecret,\n} from '@/registry/components/dashboardblocks/settings'\nimport { StatusLabel } from '@/registry/components/dashboardblocks/status-label'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { formatDate, formatRelativeTime } from '@/registry/lib/dashboardblocks/format'\nimport { type FormEvent, type RefObject, useEffect, useId, useRef, useState } from 'react'\nimport { flushSync } from 'react-dom'\n\nimport { Button } from '@/components/ui/button'\nimport { Input } from '@/components/ui/input'\n\ntype KeyScope = 'read' | 'write'\n\ninterface ApiKey {\n  createdAt: Date\n  createdBy: string\n  id: string\n  lastUsedAt?: Date\n  masked: string\n  name: string\n  scope: KeyScope\n}\n\ninterface Settings2Props extends BlockStateProps {\n  /** Creates a key and returns it with its secret, which is shown once. */\n  createKey: (name: string, scope: KeyScope) => { key: ApiKey; secret: string }\n  /** @default a sentence counting the keys and any unused ones */\n  description?: string\n  /** Leave out, or pass none, to show the empty state. */\n  keys?: ApiKey[]\n  /** Pass a fixed date, so the block renders the same on the server and in the browser. */\n  now: Date\n  onRevoke?: (id: string) => void\n  /** @default 90 */\n  staleAfterDays?: number\n  title: string\n}\n\nconst NOW = new Date(Date.UTC(2026, 8, 26, 16, 0))\nconst daysAgo = (days: number) => new Date(NOW.getTime() - days * 86_400_000)\n\nconst exampleProps: Settings2Props = {\n  createKey: (name, scope) => {\n    let seed = 2_166_136_261\n    for (const char of name + scope)\n      seed = Math.imul(seed ^ char.charCodeAt(0), 16_777_619)\n    const secret = `sk_live_${Array.from({ length: 32 }, () => {\n      seed = Math.imul(seed ^ (seed >>> 15), 2_246_822_507) + 1\n      return ((seed >>> 0) % 36).toString(36)\n    }).join('')}`\n    return {\n      key: {\n        createdAt: NOW,\n        createdBy: 'Amara Okafor',\n        id: `key-${name}`,\n        masked: maskSecret(secret),\n        name,\n        scope,\n      },\n      secret,\n    }\n  },\n  keys: [\n    {\n      createdAt: daysAgo(210),\n      createdBy: 'Liam Carter',\n      id: 'k1',\n      lastUsedAt: new Date(NOW.getTime() - 4 * 60_000),\n      masked: 'sk_live_…9f2a',\n      name: 'Production backend',\n      scope: 'write',\n    },\n    {\n      createdAt: daysAgo(64),\n      createdBy: 'Sofia Rossi',\n      id: 'k2',\n      lastUsedAt: daysAgo(1),\n      masked: 'sk_live_…c41e',\n      name: 'Analytics export',\n      scope: 'read',\n    },\n    {\n      createdAt: daysAgo(320),\n      createdBy: 'Mateo García',\n      id: 'k3',\n      lastUsedAt: daysAgo(131),\n      masked: 'sk_live_…07bd',\n      name: 'Old staging',\n      scope: 'write',\n    },\n    {\n      createdAt: daysAgo(12),\n      createdBy: 'Liam Carter',\n      id: 'k4',\n      masked: 'sk_live_…e8d0',\n      name: 'CI pipeline',\n      scope: 'read',\n    },\n  ],\n  now: NOW,\n  title: 'API keys',\n}\n\nconst scopeLabel: Record<KeyScope, string> = {\n  read: 'Read only',\n  write: 'Read and write',\n}\n\nconst Settings2 = (props: Settings2Props) => {\n  const {\n    createKey,\n    now,\n    onRevoke,\n    staleAfterDays = 90,\n    errorMessage,\n    status,\n    title,\n  } = props\n  const id = useId()\n  const [keys, setKeys] = useState(props.keys ?? [])\n  const unused = keys.filter(\n    (key) => daysBetween(key.lastUsedAt ?? key.createdAt, now) >= staleAfterDays,\n  ).length\n  const description =\n    props.description ??\n    `${keys.length} ${keys.length === 1 ? 'key' : 'keys'} can call the API${unused > 0 ? `, ${unused} unused for ${staleAfterDays} days or more` : ''}. Treat them like passwords.`\n  const [creating, setCreating] = useState(false)\n  const [name, setName] = useState('')\n  const [nameError, setNameError] = useState<string | null>(null)\n  const [scope, setScope] = useState<KeyScope>('read')\n  const [revealed, setRevealed] = useState<{ name: string; secret: string } | null>(null)\n  const createButton = useRef<HTMLButtonElement>(null)\n  const nameInput = useRef<HTMLInputElement>(null)\n  const revealedPanel = useRef<HTMLDivElement>(null)\n  const focusAfterRender = useRef<RefObject<HTMLElement | null> | null>(null)\n\n  useEffect(() => {\n    focusAfterRender.current?.current?.focus()\n    focusAfterRender.current = null\n  })\n\n  const create = (event: FormEvent<HTMLFormElement>) => {\n    event.preventDefault()\n    const trimmed = name.trim()\n    if (!trimmed) {\n      flushSync(() => setNameError('Enter a name for the key, such as where it’s used.'))\n      return nameInput.current?.focus()\n    }\n    const { key, secret } = createKey(trimmed, scope)\n    setKeys((current) => [key, ...current])\n    setRevealed({ name: key.name, secret })\n    setCreating(false)\n    focusAfterRender.current = revealedPanel\n    setName('')\n    setScope('read')\n  }\n\n  return (\n    <BlockStateProvider errorMessage={errorMessage} state={getBlockState(status, keys)}>\n      <section className='@container flex flex-col gap-3'>\n        <header className='flex items-start justify-between gap-3'>\n          <div className='flex min-w-0 flex-col gap-0.5'>\n            <h2 className='font-semibold tracking-tight'>{title}</h2>\n            <BlockReady className='text-sm'>\n              <p className='text-muted-foreground text-sm'>{description}</p>\n            </BlockReady>\n          </div>\n          {!creating && (\n            <Button\n              ref={createButton}\n              variant='outline'\n              size='sm'\n              disabled={status !== undefined}\n              onClick={() => {\n                setCreating(true)\n                setRevealed(null)\n                focusAfterRender.current = nameInput\n              }}\n            >\n              <IconPlaceholder\n                lucide='PlusIcon'\n                tabler='IconPlus'\n                hugeicons='PlusSignIcon'\n                phosphor='PlusIcon'\n                remixicon='RiAddLine'\n                data-icon='inline-start'\n              />\n              Create key\n            </Button>\n          )}\n        </header>\n        <div className='flex flex-col gap-4'>\n          {creating && (\n            <form\n              method='post'\n              onSubmit={create}\n              className='flex flex-col gap-3 rounded-lg border p-4'\n            >\n              <div className='flex flex-col gap-2'>\n                <label htmlFor={`${id}-name`} className='text-sm font-medium'>\n                  Key name\n                </label>\n                <Input\n                  ref={nameInput}\n                  id={`${id}-name`}\n                  autoComplete='off'\n                  placeholder='e.g. Production backend'\n                  value={name}\n                  onChange={(event) => {\n                    setName(event.target.value)\n                    setNameError(null)\n                  }}\n                  aria-invalid={nameError ? true : undefined}\n                  aria-describedby={nameError ? `${id}-name-error` : undefined}\n                />\n                {nameError && (\n                  <p\n                    id={`${id}-name-error`}\n                    role='alert'\n                    className='text-destructive text-sm'\n                  >\n                    {nameError}\n                  </p>\n                )}\n              </div>\n              <fieldset className='flex flex-col gap-2'>\n                <legend className='mb-2 text-sm font-medium'>Access</legend>\n                <div className='flex flex-wrap gap-x-4 gap-y-2'>\n                  {(Object.keys(scopeLabel) as KeyScope[]).map((option) => (\n                    <label key={option} className='flex items-center gap-2 text-sm'>\n                      <input\n                        type='radio'\n                        name={`${id}-scope`}\n                        value={option}\n                        checked={scope === option}\n                        onChange={() => setScope(option)}\n                        className='accent-primary size-4'\n                      />\n                      {scopeLabel[option]}\n                    </label>\n                  ))}\n                </div>\n              </fieldset>\n              <div className='flex justify-end gap-2'>\n                <Button\n                  type='button'\n                  variant='ghost'\n                  onClick={() => {\n                    setCreating(false)\n                    setNameError(null)\n                    focusAfterRender.current = createButton\n                  }}\n                >\n                  Cancel\n                </Button>\n                <Button type='submit'>Create key</Button>\n              </div>\n            </form>\n          )}\n\n          {revealed && (\n            <div\n              ref={revealedPanel}\n              role='group'\n              aria-labelledby={`${id}-revealed`}\n              tabIndex={-1}\n              className='flex flex-col gap-2 rounded-lg border p-4 outline-none'\n            >\n              <p id={`${id}-revealed`} className='text-sm font-medium'>\n                <StatusLabel variant='text' tone='good'>\n                  Created\n                </StatusLabel>{' '}\n                “{revealed.name}”\n              </p>\n              <p className='text-muted-foreground text-sm'>\n                Copy the key now. You won’t be able to see it again.\n              </p>\n              <div className='bg-background flex items-center gap-2 rounded-md border py-1 pr-1 pl-3'>\n                <span className='min-w-0 flex-1 truncate font-mono text-xs'>\n                  {revealed.secret}\n                </span>\n                <CopyButton label='Copy API key' value={revealed.secret} />\n              </div>\n              <Button\n                variant='ghost'\n                size='sm'\n                className='self-end'\n                onClick={() => {\n                  setRevealed(null)\n                  focusAfterRender.current = createButton\n                }}\n              >\n                Done\n              </Button>\n            </div>\n          )}\n\n          {status || keys.length === 0 ? (\n            <div className='border-t'>\n              <BlockStateRows rows={4} />\n            </div>\n          ) : (\n            <ul className='flex flex-col divide-y border-t'>\n              {keys.map((key) => {\n                const idle = daysBetween(key.lastUsedAt ?? key.createdAt, now)\n                const stale = idle >= staleAfterDays\n                return (\n                  <li key={key.id} className='flex items-center gap-3 py-2.5'>\n                    <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n                      <span className='flex min-w-0 flex-wrap items-baseline gap-x-2'>\n                        <span className='truncate text-sm font-medium'>{key.name}</span>\n                        {stale && (\n                          <StatusLabel variant='text' tone='warning' className='text-xs'>\n                            Unused for {idle} days\n                          </StatusLabel>\n                        )}\n                      </span>\n                      <Details className='text-muted-foreground text-xs'>\n                        <span className='font-mono'>{key.masked}</span>\n                        {scopeLabel[key.scope]}\n                      </Details>\n                      <Details className='text-muted-foreground text-xs'>\n                        {key.lastUsedAt ? (\n                          <>\n                            Used{' '}\n                            <time dateTime={key.lastUsedAt.toISOString()}>\n                              {formatRelativeTime(key.lastUsedAt, now, { style: 'long' })}\n                            </time>\n                          </>\n                        ) : (\n                          'Never used'\n                        )}\n                        <>\n                          Created by {key.createdBy} on{' '}\n                          <time dateTime={key.createdAt.toISOString()}>\n                            {formatDate(key.createdAt, 'date')}\n                          </time>\n                        </>\n                      </Details>\n                    </div>\n                    <Button\n                      variant='outline'\n                      size='sm'\n                      aria-label={`Revoke ${key.name}`}\n                      onClick={() => {\n                        setKeys((current) => current.filter((item) => item.id !== key.id))\n                        onRevoke?.(key.id)\n                      }}\n                    >\n                      Revoke\n                    </Button>\n                  </li>\n                )\n              })}\n            </ul>\n          )}\n        </div>\n      </section>\n    </BlockStateProvider>\n  )\n}\n\nexport {\n  Settings2,\n  exampleProps as settings2ExampleProps,\n  type ApiKey,\n  type KeyScope,\n  type Settings2Props,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/settings/settings-02.tsx"
    }
  ],
  "meta": {
    "shows": "API keys with their access, last use and creator, with unused keys flagged and a new key shown once with a copy button.",
    "size": "full",
    "usedWith": [
      "settings-05",
      "security-02"
    ],
    "component": "Settings2",
    "props": "{ createKey: (name: string, scope: \"read\" | \"write\") => { key: { createdAt: Date; createdBy: string; id: string; lastUsedAt?: Date; masked: string; name: string; scope: \"read\" | \"write\" }; secret: string }; description?: string; keys?: { createdAt: Date; createdBy: string; id: string; lastUsedAt?: Date; masked: string; name: string; scope: \"read\" | \"write\" }[]; now: Date; onRevoke?: (id: string) => void; staleAfterDays?: number; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
