{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "token-select",
  "title": "Token Select",
  "description": "Searchable token picker (pill trigger plus dialog) for tokens in the token list standard (tokenlists.org, the format of Uniswap's lists), on one chain. Search by symbol, name or pasted address; quick picks from recent tokens (localStorage) and a popular list; the connected account's balances read in one batch, with held tokens sorted first; arrow-key navigation; a loading skeleton measured from the real rows (skullet) while the list downloads; and pagination (50 rows per page, infinite scroll plus a Show more button) so 400-token lists stay fast. Accepts balances from an indexer via the balances prop, which skips RPC reads. Pair it with useTokenList. Exports TokenSelectDialog, filterTokens, useTokenBalances and the Token type. On small screens the picker opens as a bottom drawer (mode: auto, dialog or drawer).",
  "dependencies": [
    "wagmi",
    "viem",
    "lucide-react",
    "skullet"
  ],
  "registryDependencies": [
    "button",
    "@0xui/responsive-dialog",
    "@0xui/token-icon",
    "@0xui/token-amount",
    "@0xui/token-list",
    "@0xui/0xui-utils"
  ],
  "files": [
    {
      "path": "registry/default/components/token-select.tsx",
      "content": "// Docs: https://0xui.io/components/token-select.md\nimport { ChevronDownIcon, SearchIcon } from \"lucide-react\";\nimport {\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type ReactNode,\n} from \"react\";\nimport { Skeleton } from \"skullet/react\";\nimport { erc20Abi, formatUnits, type Address } from \"viem\";\nimport { useBalance, useChainId, useConnection, useReadContracts } from \"wagmi\";\nimport {\n  ResponsiveDialog,\n  type ResponsiveDialogMode,\n} from \"@/components/responsive-dialog\";\nimport { TokenAmount } from \"@/components/token-amount\";\nimport { TokenIcon } from \"@/components/token-icon\";\nimport { Button } from \"@/components/ui/button\";\nimport { truncateAddress } from \"@/lib/0xui-utils\";\nimport { NATIVE_TOKEN_ADDRESS, getTokenPrice, isNativeToken, type TokenInfo, type TokenPrices } from \"@/lib/token-list\";\nimport { cn } from \"@/lib/utils\";\n\n/** A token-list entry (https://tokenlists.org). Same as `TokenInfo`. */\nexport type Token = TokenInfo;\nexport { NATIVE_TOKEN_ADDRESS, getTokenPrice, isNativeToken, type TokenPrices };\n\nconst key = (token: Pick<Token, \"address\">) => token.address.toLowerCase();\n\n/**\n * Search tokens by symbol, name or exact address. Symbol prefix matches\n * rank first, then other symbol matches, then name matches.\n */\nexport function filterTokens(tokens: readonly Token[], query: string) {\n  const q = query.trim().toLowerCase();\n  if (!q) return [...tokens];\n  if (/^0x[0-9a-f]{40}$/.test(q)) return tokens.filter((t) => key(t) === q);\n  const rank = (t: Token) => {\n    const symbol = t.symbol.toLowerCase();\n    if (symbol === q) return 0;\n    if (symbol.startsWith(q)) return 1;\n    if (symbol.includes(q)) return 2;\n    if (t.name.toLowerCase().includes(q)) return 3;\n    return -1;\n  };\n  return tokens\n    .map((token) => ({ token, rank: rank(token) }))\n    .filter((t) => t.rank >= 0)\n    .sort((a, b) => a.rank - b.rank)\n    .map((t) => t.token);\n}\n\n/**\n * Balances for a list of tokens on one chain, for the connected account or\n * `address`. ERC-20 balances are read in one batch. Keys are lowercase\n * token addresses.\n */\nexport function useTokenBalances(\n  tokens: readonly Token[],\n  {\n    chainId,\n    address: addressProp,\n    enabled = true,\n  }: { chainId?: number; address?: Address; enabled?: boolean } = {}\n) {\n  const connection = useConnection();\n  const address = addressProp ?? connection.address;\n  const erc20 = tokens.filter((t) => !isNativeToken(t));\n  const hasNative = tokens.some(isNativeToken);\n\n  const native = useBalance({\n    address,\n    chainId,\n    query: { enabled: enabled && Boolean(address) && hasNative },\n  });\n  const reads = useReadContracts({\n    contracts: erc20.map((token) => ({\n      address: token.address,\n      abi: erc20Abi,\n      functionName: \"balanceOf\" as const,\n      args: [address!] as const,\n      chainId,\n    })),\n    query: { enabled: enabled && Boolean(address) && erc20.length > 0 },\n  });\n\n  const balances = useMemo(() => {\n    const map = new Map<string, bigint>();\n    if (native.data) map.set(key({ address: NATIVE_TOKEN_ADDRESS }), native.data.value);\n    reads.data?.forEach((result, i) => {\n      if (result.status === \"success\") map.set(key(erc20[i]!), result.result as bigint);\n    });\n    return map;\n    // erc20 is derived from tokens.\n  }, [native.data, reads.data, tokens]);\n\n  return {\n    balances,\n    isLoading: native.isLoading || reads.isLoading,\n    // Partial results are still useful; only report failure when nothing loaded.\n    isError: (native.isError || reads.isError) && balances.size === 0,\n  };\n}\n\n/**\n * Tokens the user holds first: priced holdings by value, then other\n * holdings in list order, then everything else in list order. Raw amounts\n * aren't compared: a billion airdropped tokens shouldn't outrank 2 ETH.\n */\nexport function sortByHoldings(\n  tokens: readonly Token[],\n  balances: ReadonlyMap<string, bigint>,\n  prices: TokenPrices = {}\n) {\n  return tokens\n    .map((token, index) => {\n      const balance = balances.get(key(token)) ?? 0n;\n      const price = getTokenPrice(prices, token);\n      const value =\n        balance > 0n && price !== undefined\n          ? Number(formatUnits(balance, token.decimals)) * price\n          : undefined;\n      const group = value !== undefined ? 0 : balance > 0n ? 1 : 2;\n      return { token, index, value: value ?? 0, group };\n    })\n    .sort((a, b) => a.group - b.group || b.value - a.value || a.index - b.index)\n    .map((t) => t.token);\n}\n\n/** Normalize caller-supplied balances to lowercase-address keys. */\nfunction toBalanceMap(balances: ReadonlyMap<string, bigint> | Record<string, bigint>) {\n  const entries = balances instanceof Map ? [...balances] : Object.entries(balances);\n  return new Map(entries.map(([address, value]) => [address.toLowerCase(), value]));\n}\n\n/**\n * Last row of a paginated list: loads the next page when scrolled into\n * view, with a button for keyboard users and browsers without\n * IntersectionObserver.\n */\nfunction LoadMore({\n  shown,\n  total,\n  onLoadMore,\n}: {\n  shown: number;\n  total: number;\n  onLoadMore: () => void;\n}) {\n  const ref = useRef<HTMLLIElement>(null);\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver((entries) => {\n      if (entries.some((e) => e.isIntersecting)) onLoadMore();\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [onLoadMore, shown]);\n\n  return (\n    <li ref={ref} className=\"flex flex-col items-center gap-1 px-2 py-3 text-xs text-muted-foreground\">\n      <span>\n        Showing {shown} of {total}\n      </span>\n      <button type=\"button\" onClick={onLoadMore} className=\"rounded-md px-2 py-1 font-medium text-foreground hover:bg-muted\">\n        Show more\n      </button>\n    </li>\n  );\n}\n\nconst RECENT_LIMIT = 4;\nconst recentKey = (chainId: number) => `0xui:recent-tokens:${chainId}`;\n\nfunction readRecent(chainId: number): string[] {\n  try {\n    return JSON.parse(localStorage.getItem(recentKey(chainId)) ?? \"[]\");\n  } catch {\n    return [];\n  }\n}\n\nfunction saveRecent(chainId: number, token: Token) {\n  try {\n    const next = [key(token), ...readRecent(chainId).filter((a) => a !== key(token))];\n    localStorage.setItem(recentKey(chainId), JSON.stringify(next.slice(0, RECENT_LIMIT)));\n  } catch {\n    // Storage blocked: recents are a convenience.\n  }\n}\n\nexport type TokenSelectDialogProps = {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** Tokens to choose from. Only those on `chainId` are shown. */\n  tokens: readonly Token[];\n  /** Called with the chosen token. The dialog closes itself. */\n  onValueChange: (token: Token) => void;\n  /** Currently selected token, marked in the list. */\n  value?: Token;\n  /** Chain to list tokens for. Defaults to the current chain. */\n  chainId?: number;\n  /** Symbols or addresses shown as quick-pick chips. */\n  popular?: readonly string[];\n  /** Read and show the connected account's balances. */\n  showBalances?: boolean;\n  /** Prices keyed by `chainId:address`, address or symbol. Held tokens are sorted by value when given. */\n  prices?: TokenPrices;\n  /** The token list is still loading, e.g. `useTokenList(…).isLoading`. */\n  isLoading?: boolean;\n  /** Rows per page. More load as you scroll, or with \"Show more\". Keeps 400-token lists fast. */\n  pageSize?: number;\n  /**\n   * Balances from your own source, e.g. an indexer, keyed by token address.\n   * When given, nothing is read over RPC.\n   */\n  balances?: ReadonlyMap<string, bigint> | Record<string, bigint>;\n  title?: ReactNode;\n  /** `auto` is a bottom drawer on small screens and a dialog otherwise. `dialog` and `drawer` force one. */\n  mode?: ResponsiveDialogMode;\n};\n\nconst noop = () => {};\n\n/** Stand-in rows the loading skeleton is measured from. Never shown as text. */\nconst sampleTokens: Token[] = [\"Sample token\", \"Another one\", \"Third token name\", \"Fourth\", \"Fifth token\", \"Sixth one\"].map(\n  (name, index) => ({\n    chainId: 0,\n    address: `0x${String(index + 1).padStart(40, \"0\")}`,\n    name,\n    symbol: \"TKN\",\n    decimals: 18,\n  })\n);\n\n/** One row of the token list. */\nfunction TokenRow({\n  token,\n  balance,\n  selected = false,\n  showAddress = false,\n  onSelect,\n}: {\n  token: Token;\n  balance?: bigint;\n  selected?: boolean;\n  /** Show the contract address next to the name, for address searches. */\n  showAddress?: boolean;\n  onSelect: (token: Token) => void;\n}) {\n  return (\n    <li>\n      <button\n        type=\"button\"\n        aria-current={selected || undefined}\n        onClick={() => onSelect(token)}\n        className={cn(\n          \"flex min-h-12 w-full items-center gap-3 rounded-lg px-2 py-1.5 text-left outline-none\",\n          \"hover:bg-muted focus-visible:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50\",\n          selected && \"bg-muted\"\n        )}\n      >\n        <TokenIcon symbol={token.symbol} src={token.logoURI} size={32} />\n        <span className=\"flex min-w-0 flex-1 flex-col\">\n          <span className=\"truncate text-sm font-medium\">{token.symbol}</span>\n          <span className=\"truncate text-xs text-muted-foreground\">\n            {token.name}\n            {!isNativeToken(token) && showAddress && <> · {truncateAddress(token.address)}</>}\n          </span>\n        </span>\n        {balance !== undefined && balance > 0n && (\n          <TokenAmount value={balance} decimals={token.decimals} compact className=\"text-sm\" />\n        )}\n      </button>\n    </li>\n  );\n}\n\n/** The token picker on its own. Use it to open the picker from your own trigger. */\nexport function TokenSelectDialog({\n  open,\n  onOpenChange,\n  tokens: allTokens,\n  onValueChange,\n  value,\n  chainId: chainIdProp,\n  popular = [],\n  showBalances = true,\n  prices,\n  isLoading = false,\n  pageSize = 50,\n  balances: balancesProp,\n  title = \"Select a token\",\n  mode,\n}: TokenSelectDialogProps) {\n  const currentChainId = useChainId();\n  const chainId = chainIdProp ?? currentChainId;\n  const [query, setQuery] = useState(\"\");\n  const [recent, setRecent] = useState<string[]>([]);\n  const listRef = useRef<HTMLUListElement>(null);\n\n  const tokens = useMemo(\n    () => allTokens.filter((t) => t.chainId === chainId),\n    [allTokens, chainId]\n  );\n  const rpc = useTokenBalances(tokens, {\n    chainId,\n    enabled: open && showBalances && !balancesProp,\n  });\n  const balances = useMemo(\n    () => (balancesProp ? toBalanceMap(balancesProp) : rpc.balances),\n    [balancesProp, rpc.balances]\n  );\n  const [visible, setVisible] = useState(pageSize);\n\n  useEffect(() => {\n    if (open) {\n      setQuery(\"\");\n      setRecent(readRecent(chainId));\n    }\n  }, [open, chainId]);\n\n  // Back to the first page whenever the results change.\n  useEffect(() => setVisible(pageSize), [query, open, pageSize]);\n\n  const results = useMemo(() => {\n    const matches = filterTokens(tokens, query);\n    if (query) return matches;\n    return sortByHoldings(matches, balances, prices);\n  }, [tokens, query, balances, prices]);\n\n  const chips = useMemo(() => {\n    const wanted = [...recent, ...popular.map((p) => p.toLowerCase())];\n    const picked: Token[] = [];\n    for (const w of wanted) {\n      const token = tokens.find((t) => key(t) === w || t.symbol.toLowerCase() === w);\n      if (token && !picked.includes(token)) picked.push(token);\n    }\n    return picked.slice(0, 6);\n  }, [recent, popular, tokens]);\n\n  const select = (token: Token) => {\n    saveRecent(chainId, token);\n    onValueChange(token);\n    onOpenChange(false);\n  };\n\n  // Arrow keys move between the search field and the rows.\n  const onKeyDown = (event: KeyboardEvent) => {\n    if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n    const rows = Array.from(listRef.current?.querySelectorAll(\"button\") ?? []);\n    if (rows.length === 0) return;\n    event.preventDefault();\n    const index = rows.indexOf(document.activeElement as HTMLButtonElement);\n    const next =\n      event.key === \"ArrowDown\"\n        ? rows[Math.min(index + 1, rows.length - 1)]\n        : index <= 0\n          ? undefined\n          : rows[index - 1];\n    if (next) next.focus();\n    else (event.currentTarget.querySelector(\"input\") as HTMLInputElement | null)?.focus();\n  };\n\n  return (\n    <ResponsiveDialog\n      open={open}\n      onOpenChange={onOpenChange}\n      title={title}\n      description=\"Search by name, symbol or address.\"\n      mode={mode}\n      className=\"flex max-h-[min(36rem,85vh)] flex-col sm:max-w-md\"\n      onKeyDown={onKeyDown}\n    >\n\n        <label className=\"flex items-center gap-2 rounded-lg border px-3 focus-within:ring-3 focus-within:ring-ring/50\">\n          <SearchIcon aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n          <input\n            type=\"search\"\n            autoComplete=\"off\"\n            spellCheck={false}\n            aria-label=\"Search tokens\"\n            placeholder=\"Search name, symbol or address\"\n            value={query}\n            onChange={(e) => setQuery(e.target.value)}\n            className=\"h-10 w-full bg-transparent text-sm outline-none\"\n          />\n        </label>\n\n        {!query && chips.length > 0 && (\n          <div role=\"group\" aria-label=\"Quick picks\" className=\"flex flex-wrap gap-2\">\n            {chips.map((token) => (\n              <button\n                key={key(token)}\n                type=\"button\"\n                onClick={() => select(token)}\n                className=\"flex items-center gap-1.5 rounded-full border py-1 pr-3 pl-1 text-sm hover:bg-muted\"\n              >\n                <TokenIcon symbol={token.symbol} src={token.logoURI} size={20} />\n                {token.symbol}\n              </button>\n            ))}\n          </div>\n        )}\n\n        {results.length === 0 && !isLoading ? (\n          <p role=\"status\" className=\"py-6 text-center text-sm text-muted-foreground\">\n            {query ? `No tokens match “${query}”.` : \"No tokens on this network.\"}\n          </p>\n        ) : (\n          <div className=\"-mx-2 flex min-h-0 flex-col gap-0.5 overflow-y-auto\">\n            {results.length > 0 && (\n              <ul ref={listRef} aria-label=\"Tokens\" className=\"flex shrink-0 flex-col gap-0.5\">\n                {results.slice(0, visible).map((token) => (\n                  <TokenRow\n                    key={key(token)}\n                    token={token}\n                    balance={balances.get(key(token))}\n                    selected={value !== undefined && key(value) === key(token)}\n                    showAddress={query.startsWith(\"0x\")}\n                    onSelect={select}\n                  />\n                ))}\n                {results.length > visible && (\n                  <LoadMore\n                    shown={visible}\n                    total={results.length}\n                    onLoadMore={() => setVisible((v) => v + pageSize)}\n                  />\n                )}\n              </ul>\n            )}\n            {/* While the list downloads: sample rows, measured into a skeleton\n                the shape of real ones, under whatever is already known (the\n                native currency, usually). */}\n            {isLoading && (\n              <>\n                <p role=\"status\" className=\"sr-only\">\n                  Loading tokens…\n                </p>\n                <Skeleton loading className=\"shrink-0\">\n                  <ul className=\"flex flex-col gap-0.5\">\n                    {sampleTokens.map((token) => (\n                      <TokenRow key={key(token)} token={token} onSelect={noop} />\n                    ))}\n                  </ul>\n                </Skeleton>\n              </>\n            )}\n          </div>\n        )}\n    </ResponsiveDialog>\n  );\n}\n\nexport type TokenSelectProps = Omit<\n  TokenSelectDialogProps,\n  \"open\" | \"onOpenChange\"\n> &\n  Omit<ComponentProps<typeof Button>, \"value\" | \"onClick\" | \"title\"> & {\n    /** Trigger text when nothing is selected. */\n    placeholder?: string;\n  };\n\n/** Token pill that opens a searchable token picker. */\nexport function TokenSelect({\n  tokens,\n  onValueChange,\n  value,\n  chainId,\n  popular,\n  showBalances,\n  prices,\n  isLoading,\n  pageSize,\n  balances,\n  title,\n  mode,\n  placeholder = \"Select token\",\n  className,\n  variant = \"outline\",\n  ...buttonProps\n}: TokenSelectProps) {\n  const [open, setOpen] = useState(false);\n\n  return (\n    <>\n      <Button\n        type=\"button\"\n        variant={variant}\n        aria-haspopup=\"dialog\"\n        aria-label={value ? `${value.symbol}, change token` : placeholder}\n        onClick={() => setOpen(true)}\n        // A logo sits close to the pill's edge; bare text needs more room on the curve.\n        className={cn(\"h-10 gap-2 rounded-full pr-3\", value ? \"pl-1.5\" : \"pl-4\", className)}\n        {...buttonProps}\n      >\n        {value && <TokenIcon symbol={value.symbol} src={value.logoURI} size={28} />}\n        <span className=\"font-semibold\">{value ? value.symbol : placeholder}</span>\n        <ChevronDownIcon aria-hidden className=\"size-4 opacity-60\" />\n      </Button>\n      <TokenSelectDialog\n        open={open}\n        onOpenChange={setOpen}\n        tokens={tokens}\n        onValueChange={onValueChange}\n        value={value}\n        chainId={chainId}\n        popular={popular}\n        showBalances={showBalances}\n        prices={prices}\n        isLoading={isLoading}\n        pageSize={pageSize}\n        balances={balances}\n        title={title}\n        mode={mode}\n      />\n    </>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/components/token-select.md",
  "categories": [
    "tokens"
  ],
  "type": "registry:component"
}