{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"toggle-group","type":"registry:block","title":"Toggle group","description":"A segmented language switcher with a selection pill that slides between options, roving arrow-key focus, and a snippet that swaps in with a short slide.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/toggle-group/toggle-group.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useId, useRef, useState, type KeyboardEvent } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\n/* ------------------------------------------------------------------ */\n/* types                                                               */\n/* ------------------------------------------------------------------ */\n\nexport type ToggleGroupOption = {\n  id: string;\n  label: string;\n  /** File name shown above the snippet. */\n  fileName: string;\n  /** Short note under the snippet. */\n  note: string;\n  /** Lines of code, one string per line. */\n  lines: string[];\n};\n\nexport type ToggleGroupProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  options?: ToggleGroupOption[];\n  defaultValue?: string;\n  /** Accessible name for the control. Defaults to \"Choose a language\". */\n  groupLabel?: string;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data                                             */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_OPTIONS: ToggleGroupOption[] = [\n  {\n    id: \"curl\",\n    label: \"cURL\",\n    fileName: \"create-charge.sh\",\n    note: \"Replace the key with your own.\",\n    lines: [\n      \"curl https://api.halo.cloud/v3/charges \\\\\",\n      '  -H \"Authorization: Bearer $HALO_KEY\" \\\\',\n      '  -H \"Content-Type: application/json\" \\\\',\n      '  -d \\'{\"amount\": 1284, \"currency\": \"usd\"}\\'',\n    ],\n  },\n  {\n    id: \"node\",\n    label: \"Node\",\n    fileName: \"create-charge.ts\",\n    note: \"The SDK retries once on a network error.\",\n    lines: [\n      'const { Halo } = require(\"@halo-cloud/node\");',\n      \"\",\n      \"const halo = new Halo(process.env.HALO_KEY);\",\n      \"const charge = await halo.charges.create({\",\n      '  amount: 1284, currency: \"usd\",',\n      \"});\",\n    ],\n  },\n  {\n    id: \"python\",\n    label: \"Python\",\n    fileName: \"create_charge.py\",\n    note: \"Amounts are in the smallest currency unit.\",\n    lines: [\n      \"import os\",\n      \"from halo import Halo\",\n      \"\",\n      \"halo = Halo(os.environ[\\\"HALO_KEY\\\"])\",\n      \"charge = halo.charges.create(\",\n      \"    amount=1284, currency=\\\"usd\\\"\",\n      \")\",\n    ],\n  },\n];\n\n/* ------------------------------------------------------------------ */\n/* tiny syntax colouring (tokens only, no highlighter)                 */\n/* ------------------------------------------------------------------ */\n\nconst KEYWORDS = /^(import|from|const|await|new|return|def)$/;\n\nfunction CodeLine({ line }: { line: string }) {\n  if (!line) {\n    return <span className=\"block h-4\" aria-hidden=\"true\" />;\n  }\n\n  const parts = line.split(/(\"[^\"]*\"|'[^']*'|\\b(?:import|from|const|await|new|return|def)\\b)/g);\n\n  return (\n    <span className=\"block min-h-4 whitespace-pre\">\n      {parts.map((part, index) => {\n        if (!part) return null;\n        if (part.startsWith('\"') || part.startsWith(\"'\")) {\n          return (\n            <span key={index} className=\"text-success\">\n              {part}\n            </span>\n          );\n        }\n        if (KEYWORDS.test(part)) {\n          return (\n            <span key={index} className=\"text-foreground\">\n              {part}\n            </span>\n          );\n        }\n        return (\n          <span key={index} className=\"text-muted-foreground\">\n            {part}\n          </span>\n        );\n      })}\n    </span>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* block                                                               */\n/* ------------------------------------------------------------------ */\n\nexport function ToggleGroup({\n  className,\n  title = \"Send a charge\",\n  description = \"One request, three languages. Pick the one you ship.\",\n  options = DEFAULT_OPTIONS,\n  defaultValue,\n  groupLabel = \"Choose a language\",\n}: ToggleGroupProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const inView = useInView(ref, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const pillId = useId();\n  const buttons = useRef<Array<HTMLButtonElement | null>>([]);\n\n  const safeOptions = options.length > 0 ? options : DEFAULT_OPTIONS;\n  const [value, setValue] = useState(() => {\n    const initial =\n      safeOptions.find((option) => option.id === defaultValue) ?? safeOptions[0];\n    return initial?.id ?? \"\";\n  });\n\n  const active =\n    safeOptions.find((option) => option.id === value) ?? safeOptions[0];\n\n  const handleKeyDown = (\n    event: KeyboardEvent<HTMLButtonElement>,\n    index: number\n  ) => {\n    const keys = [\"ArrowRight\", \"ArrowDown\", \"ArrowLeft\", \"ArrowUp\", \"Home\", \"End\"];\n    if (!keys.includes(event.key)) return;\n    event.preventDefault();\n\n    let next = index;\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\") {\n      next = (index + 1) % safeOptions.length;\n    } else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\") {\n      next = (index - 1 + safeOptions.length) % safeOptions.length;\n    } else if (event.key === \"Home\") {\n      next = 0;\n    } else if (event.key === \"End\") {\n      next = safeOptions.length - 1;\n    }\n\n    const option = safeOptions[next];\n    if (!option) return;\n    setValue(option.id);\n    buttons.current[next]?.focus();\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.div\n        ref={ref}\n        initial={reduce ? false : { opacity: 0, y: 16 }}\n        animate={inView || reduce ? { opacity: 1, y: 0 } : { opacity: 0, y: 16 }}\n        transition={{ duration: reduce ? 0 : 0.6, ease: EASE }}\n        className={cn(\n          \"w-full rounded-xl border border-border bg-card p-5 text-card-foreground sm:p-6\",\n          className\n        )}\n      >\n        <div className=\"flex flex-wrap items-start justify-between gap-3\">\n          <div className=\"min-w-0\">\n            <h2 className=\"text-[15px] font-semibold tracking-tight\">{title}</h2>\n            <p className=\"mt-0.5 text-[13px] text-muted-foreground\">{description}</p>\n          </div>\n          <span className=\"shrink-0 rounded-full border border-border px-2.5 py-1 text-[11.5px] font-medium text-muted-foreground\">\n            API v3\n          </span>\n        </div>\n\n        <div\n          role=\"radiogroup\"\n          aria-label={groupLabel}\n          className=\"mt-5 inline-flex w-fit max-w-full items-center gap-0.5 overflow-x-auto rounded-lg border border-border bg-muted/40 p-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n        >\n          {safeOptions.map((option, index) => {\n            const selected = option.id === active?.id;\n            return (\n              <button\n                key={option.id}\n                ref={(node) => {\n                  buttons.current[index] = node;\n                }}\n                type=\"button\"\n                role=\"radio\"\n                aria-checked={selected}\n                tabIndex={selected ? 0 : -1}\n                onClick={() => setValue(option.id)}\n                onKeyDown={(event) => handleKeyDown(event, index)}\n                className={cn(\n                  \"relative shrink-0 rounded-[6px] px-3 py-1.5 text-[12px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card\",\n                  selected\n                    ? \"text-foreground\"\n                    : \"text-muted-foreground hover:text-foreground\"\n                )}\n              >\n                {selected ? (\n                  <motion.span\n                    layoutId={`toggle-group-pill-${pillId}`}\n                    aria-hidden=\"true\"\n                    className=\"absolute inset-0 rounded-[6px] border border-border bg-card shadow-sm\"\n                    transition={\n                      reduce\n                        ? { duration: 0 }\n                        : { type: \"spring\", stiffness: 420, damping: 34 }\n                    }\n                  />\n                ) : null}\n                <span className=\"relative\">{option.label}</span>\n              </button>\n            );\n          })}\n        </div>\n\n        <div className=\"mt-3 min-w-0 overflow-hidden rounded-lg border border-border bg-background\">\n          <div className=\"flex items-center justify-between gap-3 border-b border-border px-3 py-2\">\n            <span className=\"min-w-0 truncate font-mono text-[11px] text-muted-foreground\">\n              {active?.fileName}\n            </span>\n            <span className=\"shrink-0 font-mono text-[10.5px] text-muted-foreground\">\n              application/json\n            </span>\n          </div>\n\n          <div\n            data-scroll-x\n            className=\"relative min-h-[148px] min-w-0 overflow-x-auto p-3 font-mono text-[11.5px] leading-[1.55] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:p-4\"\n            tabIndex={0}\n            aria-label={`${active?.label ?? \"Code\"} example`}\n          >\n            <AnimatePresence initial={false} mode=\"wait\">\n              <motion.pre\n                key={active?.id}\n                initial={reduce ? false : { opacity: 0, y: 8 }}\n                animate={{ opacity: 1, y: 0 }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6 }}\n                transition={{ duration: reduce ? 0 : 0.24, ease: EASE }}\n                className=\"m-0 flex gap-3\"\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className=\"select-none text-right text-muted-foreground/50\"\n                >\n                  {active?.lines.map((_, index) => (\n                    <span key={index} className=\"block min-h-4 tabular-nums\">\n                      {index + 1}\n                    </span>\n                  ))}\n                </span>\n                <code className=\"min-w-0\">\n                  {active?.lines.map((line, index) => (\n                    <CodeLine key={index} line={line} />\n                  ))}\n                </code>\n              </motion.pre>\n            </AnimatePresence>\n          </div>\n\n          <div className=\"flex flex-wrap items-center justify-between gap-2 border-t border-border px-3 py-2\">\n            <span className=\"min-w-0 text-[11px] text-muted-foreground\">\n              {active?.note}\n            </span>\n            <span className=\"shrink-0 font-mono text-[10.5px] tabular-nums text-success\">\n              201 Created\n            </span>\n          </div>\n        </div>\n\n        <p className=\"mt-4 flex items-center gap-1.5 text-[11px] text-muted-foreground\">\n          <span aria-hidden=\"true\" className=\"h-1.5 w-1.5 rounded-full bg-foreground/60\" />\n          Use the arrow keys to switch; the pill moves with the selection.\n        </p>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default ToggleGroup;\n"}]}