{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "model-picker",
  "title": "Model picker",
  "description": "Model dropdown grouped by provider with icon slots, speed and quality meters that grow in, context window and price per million tokens, a gliding highlight and full keyboard support with type-ahead.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/ai/model-picker.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\nimport { Check, ChevronDown } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\n/*\n * Model picker: a trigger showing the current model and a listbox of models grouped by provider, each row with\n * a provider icon slot, speed and quality meters, context window and price per million tokens. Full keyboard\n * support (arrows, Home/End, type-ahead, Enter, Esc) and a highlight that glides between rows.\n */\n\nconst CSS = `\n.pc-model-tile::before{content:attr(data-letter)}\n.pc-model-bar{transform-origin:bottom;animation:pc-model-bar .4s var(--pc-ease-out) both;animation-delay:calc(var(--i) * 40ms)}\n@keyframes pc-model-bar{from{transform:scaleY(.2);opacity:0}}\n@media (prefers-reduced-motion:reduce){.pc-model-bar{animation:none}}\n`\n\nexport type ModelOption = {\n  id: string\n  name: string\n  /** Groups rows and picks the icon slot (providerIcons[provider]). */\n  provider: string\n  description?: string\n  /** 1 (slow) to 5 (fastest). */\n  speed?: 1 | 2 | 3 | 4 | 5\n  /** 1 to 5. */\n  quality?: 1 | 2 | 3 | 4 | 5\n  /** Context window in tokens, shown compact (\"200K\"). */\n  context?: number\n  /** USD per 1M tokens. */\n  price?: { input: number; output: number }\n  /** Small badge text such as \"New\" or \"Recommended\". */\n  badge?: string\n  /** Overrides the provider icon for this model. */\n  icon?: React.ReactNode\n  disabled?: boolean\n}\n\nexport type ModelPickerLabels = {\n  chooseModel: string\n  speed: string\n  quality: string\n  context: string\n  perMillion: string\n  selected: string\n}\nconst DEFAULT_LABELS: ModelPickerLabels = { chooseModel: \"Choose a model\", speed: \"Speed\", quality: \"Quality\", context: \"Context\", perMillion: \"per 1M tokens\", selected: \"Selected\" }\n\nexport type ModelPickerProps = Omit<React.ComponentProps<\"div\">, \"onChange\" | \"defaultValue\"> & {\n  models: ModelOption[]\n  /** Selected model id (controlled). */\n  value?: string\n  defaultValue?: string\n  onValueChange?: (id: string, model: ModelOption) => void\n  /** Icon per provider name, e.g. { OpenAI: <OpenAiLogo />, Anthropic: <AnthropicLogo /> }. Missing ones get a lettered tile. */\n  providerIcons?: Record<string, React.ReactNode>\n  /** Trigger look: a bordered field or a quiet ghost button for toolbars. */\n  variant?: \"outline\" | \"ghost\"\n  size?: \"sm\" | \"md\"\n  /** Group rows under provider headings. */\n  groupByProvider?: boolean\n  showMeters?: boolean\n  showContext?: boolean\n  showPrice?: boolean\n  /** Which trigger edge the menu aligns to. */\n  align?: \"start\" | \"end\"\n  /** Locale for the context window and prices. */\n  locale?: string\n  placeholder?: string\n  disabled?: boolean\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<ModelPickerLabels>\n}\n\nconst HUES = [\"var(--chart-1)\", \"var(--chart-2)\", \"var(--chart-3)\", \"var(--chart-4)\", \"var(--chart-5)\"]\nfunction hueOf(name: string) {\n  let h = 0\n  for (const ch of name) h = (h * 31 + ch.charCodeAt(0)) % 997\n  return HUES[h % HUES.length] ?? HUES[0]\n}\n\nfunction ProviderTile({ provider, icon, className }: { provider: string; icon?: React.ReactNode; className?: string }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\"grid shrink-0 place-items-center rounded-md text-[11px] font-bold text-white [&_svg]:size-[70%]\", !icon && \"pc-model-tile\", className)}\n      data-letter={icon ? undefined : provider.trim().charAt(0).toUpperCase()}\n      style={icon ? undefined : { background: `linear-gradient(135deg, ${hueOf(provider)}, color-mix(in oklab, ${hueOf(provider)} 60%, black))` }}\n    >\n      {icon}\n    </span>\n  )\n}\n\nfunction Meter({ value, label, open }: { value: number; label: string; open: boolean }) {\n  return (\n    <span className=\"inline-flex items-center gap-1.5\" title={`${label} ${value}/5`}>\n      <span className=\"text-[10px] font-medium tracking-wide text-muted-foreground uppercase\" aria-hidden=\"true\">\n        {label}\n      </span>\n      <span className=\"sr-only\">{`${label} ${value} of 5`}</span>\n      <span className=\"flex items-end gap-px\" aria-hidden=\"true\">\n        {[1, 2, 3, 4, 5].map((n) => (\n          <span key={n} className={cn(\"w-[3px] rounded-[1px]\", open && \"pc-model-bar\", n <= value ? \"bg-foreground\" : \"bg-foreground/15\")} style={{ height: 4 + n * 1.5, [\"--i\" as string]: n }} />\n        ))}\n      </span>\n    </span>\n  )\n}\n\n/** Dropdown to choose an AI model, with provider icons, speed/quality meters, context size and pricing. */\nexport function ModelPicker({\n  models,\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  providerIcons,\n  variant = \"outline\",\n  size = \"md\",\n  groupByProvider = true,\n  showMeters = true,\n  showContext = true,\n  showPrice = true,\n  align = \"start\",\n  locale = \"en-US\",\n  placeholder,\n  disabled,\n  labels,\n  className,\n  ...props\n}: ModelPickerProps) {\n  const l = useLabels(\"model-picker\", DEFAULT_LABELS, labels)\n  const reduce = useReducedMotion() ?? false\n  const uid = React.useId()\n  const [inner, setInner] = React.useState(defaultValue ?? models[0]?.id ?? \"\")\n  const value = valueProp ?? inner\n  const current = models.find((m) => m.id === value)\n  const [open, setOpen] = React.useState(false)\n  const [active, setActive] = React.useState(0)\n  const [above, setAbove] = React.useState(false)\n  const [side, setSide] = React.useState(align)\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const triggerRef = React.useRef<HTMLButtonElement>(null)\n  const listRef = React.useRef<HTMLUListElement>(null)\n  const typed = React.useRef({ text: \"\", at: 0 })\n\n  const groups = React.useMemo(() => {\n    if (!groupByProvider) return [{ provider: \"\", items: models }]\n    const map = new Map<string, ModelOption[]>()\n    for (const m of models) map.set(m.provider, [...(map.get(m.provider) ?? []), m])\n    return [...map].map(([provider, items]) => ({ provider, items }))\n  }, [models, groupByProvider])\n  const flat = React.useMemo(() => groups.flatMap((g) => g.items), [groups])\n\n  const compact = React.useMemo(() => new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }), [locale])\n  const money = React.useMemo(() => new Intl.NumberFormat(locale, { style: \"currency\", currency: \"USD\", minimumFractionDigits: 0, maximumFractionDigits: 2 }), [locale])\n\n  const select = (m: ModelOption) => {\n    if (m.disabled) return\n    if (valueProp === undefined) setInner(m.id)\n    onValueChange?.(m.id, m)\n    setOpen(false)\n    triggerRef.current?.focus()\n  }\n\n  const show = () => {\n    const idx = Math.max(0, flat.findIndex((m) => m.id === value))\n    setActive(idx)\n    const r = triggerRef.current?.getBoundingClientRect()\n    if (r) {\n      setAbove(window.innerHeight - r.bottom < 380 && r.top > 380)\n      // Keep the menu on screen: flip to the other edge when the preferred one would overflow.\n      const w = Math.min(340, window.innerWidth - 32)\n      const fitsStart = r.left + w <= window.innerWidth - 8\n      const fitsEnd = r.right - w >= 8\n      const rtl = getComputedStyle(triggerRef.current!).direction === \"rtl\"\n      const startFits = rtl ? fitsEnd : fitsStart\n      const endFits = rtl ? fitsStart : fitsEnd\n      setSide(align === \"start\" ? (startFits || !endFits ? \"start\" : \"end\") : endFits || !startFits ? \"end\" : \"start\")\n    }\n    setOpen(true)\n  }\n\n  React.useEffect(() => {\n    if (!open) return\n    listRef.current?.focus({ preventScroll: true })\n    const onDown = (e: PointerEvent) => {\n      if (!rootRef.current?.contains(e.target as Node)) setOpen(false)\n    }\n    document.addEventListener(\"pointerdown\", onDown)\n    return () => document.removeEventListener(\"pointerdown\", onDown)\n  }, [open])\n\n  React.useEffect(() => {\n    if (!open) return\n    listRef.current?.querySelector<HTMLElement>(`[data-index=\"${active}\"]`)?.scrollIntoView({ block: \"nearest\" })\n  }, [active, open])\n\n  const move = (dir: 1 | -1) => {\n    if (!flat.length) return\n    let i = active\n    for (let n = 0; n < flat.length; n++) {\n      i = (i + dir + flat.length) % flat.length\n      if (!flat[i]?.disabled) break\n    }\n    setActive(i)\n  }\n\n  const onListKey = (e: React.KeyboardEvent) => {\n    switch (e.key) {\n      case \"ArrowDown\":\n        e.preventDefault()\n        move(1)\n        break\n      case \"ArrowUp\":\n        e.preventDefault()\n        move(-1)\n        break\n      case \"Home\":\n        e.preventDefault()\n        setActive(flat.findIndex((m) => !m.disabled))\n        break\n      case \"End\":\n        e.preventDefault()\n        setActive(flat.length - 1 - [...flat].reverse().findIndex((m) => !m.disabled))\n        break\n      case \"Enter\":\n      case \" \": {\n        e.preventDefault()\n        const m = flat[active]\n        if (m) select(m)\n        break\n      }\n      case \"Escape\":\n        e.preventDefault()\n        setOpen(false)\n        triggerRef.current?.focus()\n        break\n      case \"Tab\":\n        setOpen(false)\n        break\n      default:\n        if (e.key.length === 1 && !e.metaKey && !e.ctrlKey) {\n          const now = Date.now()\n          typed.current = { text: (now - typed.current.at < 600 ? typed.current.text : \"\") + e.key.toLowerCase(), at: now }\n          const i = flat.findIndex((m) => !m.disabled && m.name.toLowerCase().startsWith(typed.current.text))\n          if (i > -1) setActive(i)\n        }\n    }\n  }\n\n  const onTriggerKey = (e: React.KeyboardEvent) => {\n    if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\" || e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault()\n      show()\n    }\n  }\n\n  const sm = size === \"sm\"\n  const price = (m: ModelOption) => (m.price ? `${money.format(m.price.input)} · ${money.format(m.price.output)}` : null)\n\n  return (\n    <div ref={rootRef} className={cn(\"relative inline-block\", className)} {...props}>\n      <GooduiTokens />\n      <style href=\"pc-model-picker\" precedence=\"default\">\n        {CSS}\n      </style>\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        disabled={disabled}\n        aria-haspopup=\"listbox\"\n        aria-expanded={open}\n        aria-controls={open ? `${uid}-list` : undefined}\n        aria-label={current ? `${l.chooseModel}: ${current.name}` : l.chooseModel}\n        onClick={() => (open ? setOpen(false) : show())}\n        onKeyDown={onTriggerKey}\n        className={cn(\n          \"pc-press pc-press-soft inline-flex max-w-full items-center gap-2 rounded-lg font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50\",\n          sm ? \"h-8 px-2 text-xs\" : \"h-10 px-3 text-sm\",\n          variant === \"outline\" ? \"border bg-background hover:bg-muted/60\" : \"hover:bg-muted\",\n          open && (variant === \"outline\" ? \"bg-muted/60\" : \"bg-muted\"),\n        )}\n      >\n        {current ? (\n          <>\n            <ProviderTile provider={current.provider} icon={current.icon ?? providerIcons?.[current.provider]} className={sm ? \"size-4 text-[9px]\" : \"size-5\"} />\n            <span className=\"truncate\">{current.name}</span>\n          </>\n        ) : (\n          <span className=\"text-muted-foreground\">{placeholder ?? l.chooseModel}</span>\n        )}\n        <ChevronDown className={cn(\"shrink-0 text-muted-foreground transition-transform duration-200\", sm ? \"size-3.5\" : \"size-4\", open && \"rotate-180\")} aria-hidden=\"true\" />\n      </button>\n\n      <AnimatePresence>\n        {open && (\n          <motion.ul\n            ref={listRef}\n            id={`${uid}-list`}\n            role=\"listbox\"\n            tabIndex={-1}\n            aria-label={l.chooseModel}\n            aria-activedescendant={flat[active] ? `${uid}-${flat[active].id}` : undefined}\n            onKeyDown={onListKey}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: above ? 6 : -6 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={reduce ? { opacity: 0, transition: { duration: 0.1 } } : { opacity: 0, scale: 0.97, transition: { duration: 0.12 } }}\n            transition={reduce ? { duration: 0 } : spring.snap}\n            className={cn(\n              \"absolute z-50 max-h-[min(380px,70vh)] w-[min(340px,calc(100vw-2rem))] overflow-y-auto rounded-xl border bg-popover p-1 text-popover-foreground shadow-[var(--pc-e3)] shadow-black/10 outline-none dark:shadow-black/40\",\n              above ? \"bottom-full mb-1.5 origin-bottom\" : \"top-full mt-1.5 origin-top\",\n              side === \"end\" ? \"end-0\" : \"start-0\",\n            )}\n          >\n            {groups.map((g) => (\n              <React.Fragment key={g.provider}>\n                {g.provider && <li className=\"px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase\" role=\"presentation\">{g.provider}</li>}\n                {g.items.map((m) => {\n                  const i = flat.indexOf(m)\n                  const selected = m.id === value\n                  return (\n                    <motion.li\n                      key={m.id}\n                      id={`${uid}-${m.id}`}\n                      role=\"option\"\n                      aria-selected={selected}\n                      aria-disabled={m.disabled || undefined}\n                      data-index={i}\n                      initial={reduce ? false : { opacity: 0, y: -4 }}\n                      animate={{ opacity: 1, y: 0 }}\n                      transition={reduce ? { duration: 0 } : { delay: Math.min(i, 8) * 0.025, duration: 0.18 }}\n                      onPointerMove={() => !m.disabled && setActive(i)}\n                      onClick={() => select(m)}\n                      className={cn(\"relative cursor-pointer rounded-lg px-2 py-2\", m.disabled && \"cursor-not-allowed opacity-45\")}\n                    >\n                      {i === active && !m.disabled && <motion.span layoutId={`${uid}-hl`} className=\"absolute inset-0 rounded-lg bg-muted\" transition={reduce ? { duration: 0 } : spring.snap} />}\n                      <div className=\"relative flex items-start gap-2.5\">\n                        <ProviderTile provider={m.provider} icon={m.icon ?? providerIcons?.[m.provider]} className=\"mt-0.5 size-6\" />\n                        <div className=\"min-w-0 flex-1\">\n                          <div className=\"flex items-center gap-1.5\">\n                            <span className=\"truncate text-sm font-medium\">{m.name}</span>\n                            {m.badge && <span className=\"rounded-full bg-foreground px-1.5 py-px text-[10px] font-semibold text-background\">{m.badge}</span>}\n                            <span className=\"ms-auto flex shrink-0 items-center gap-2 text-[11px] text-muted-foreground tabular-nums\">\n                              {showContext && m.context !== undefined && <span title={l.context}>{compact.format(m.context)}</span>}\n                              {showPrice && price(m) && <span title={l.perMillion}>{price(m)}</span>}\n                            </span>\n                          </div>\n                          {m.description && <div className=\"truncate text-xs text-muted-foreground\">{m.description}</div>}\n                          {showMeters && (m.speed !== undefined || m.quality !== undefined) && (\n                            <div className=\"mt-1.5 flex items-center gap-4\">\n                              {m.speed !== undefined && <Meter value={m.speed} label={l.speed} open={open} />}\n                              {m.quality !== undefined && <Meter value={m.quality} label={l.quality} open={open} />}\n                              {selected && (\n                                <span className=\"ms-auto inline-flex items-center gap-1 text-[11px] font-medium text-foreground\">\n                                  <Check className=\"size-3.5\" aria-hidden=\"true\" />\n                                  <span className=\"sr-only\">{l.selected}</span>\n                                </span>\n                              )}\n                            </div>\n                          )}\n                        </div>\n                      </div>\n                    </motion.li>\n                  )\n                })}\n              </React.Fragment>\n            ))}\n          </motion.ul>\n        )}\n      </AnimatePresence>\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/model-picker.tsx"
    }
  ],
  "categories": [
    "components",
    "ai"
  ],
  "type": "registry:component"
}