{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "json-viewer",
  "type": "registry:component",
  "title": "JSON viewer",
  "description": "Inspect payloads, logs and trace attributes in a collapsible JSON tree with search, copyable paths and full keyboard navigation.",
  "categories": [
    "operations"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/json-viewer.tsx",
      "type": "registry:component",
      "target": "components/overtrue/json-viewer.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconCheck as Check,\n  IconChevronDown as ChevronDown,\n  IconChevronRight as ChevronRight,\n  IconChevronUp as ChevronUp,\n  IconCopy as Copy,\n  IconFoldDown as FoldDown,\n  IconFoldUp as FoldUp,\n  IconRoute as Route,\n  IconSearch as Search,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------------------------------\n * Types\n * -----------------------------------------------------------------------------------------------*/\n\nexport type JsonValueType =\n  | \"object\"\n  | \"array\"\n  | \"string\"\n  | \"number\"\n  | \"bigint\"\n  | \"boolean\"\n  | \"null\"\n  | \"undefined\"\n  | \"date\"\n  | \"function\"\n  | \"symbol\"\n  | \"circular\";\n\nexport interface JsonViewerLabels {\n  tree: string;\n  search: string;\n  clearSearch: string;\n  previousMatch: string;\n  nextMatch: string;\n  noMatches: string;\n  matchCount: (current: number, total: number) => string;\n  expandAll: string;\n  collapseAll: string;\n  copyJson: string;\n  copyPath: string;\n  copyValue: string;\n  copied: string;\n  showMore: string;\n  showLess: string;\n  showMoreItems: (count: number) => string;\n  hiddenItems: (count: number) => string;\n  keys: (count: number) => string;\n  items: (count: number) => string;\n  characters: (count: number) => string;\n  root: string;\n  statusHint: string;\n}\n\nexport type JsonCopyKind = \"value\" | \"path\" | \"json\";\n\nexport interface JsonViewerProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\" | \"defaultValue\" | \"onCopy\"\n> {\n  /** Any JSON-like value. Dates, Maps, Sets, bigints and circular references are handled. */\n  data: unknown;\n  /** Name of the root node and the first segment of every path, e.g. \"payload\". */\n  rootName?: string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Containers shallower than this start expanded. Defaults to 2. */\n  defaultExpandDepth?: number;\n  /** Expanded container paths. Pass with `onExpandedChange` to control expansion. */\n  expanded?: readonly string[] | ReadonlySet<string>;\n  /** Initially expanded paths, instead of `defaultExpandDepth`. */\n  defaultExpanded?: readonly string[];\n  onExpandedChange?: (expanded: string[]) => void;\n  /** Shows the search field. Defaults to true. */\n  showSearch?: boolean;\n  /** Search text. Pass with `onSearchChange` to control it. */\n  search?: string;\n  defaultSearch?: string;\n  onSearchChange?: (search: string) => void;\n  /** Longer strings are cut with an inline Show more. Defaults to 120 characters. */\n  maxStringLength?: number;\n  /** Children rendered per container before Show more. Defaults to 100. */\n  pageSize?: number;\n  /** Sort object keys alphabetically, or with your own comparator. */\n  sortKeys?: boolean | ((a: string, b: string) => number);\n  /** Selected path. Pass `null` for none; leave undefined to let the viewer manage it. */\n  selectedPath?: string | null;\n  defaultSelectedPath?: string | null;\n  /** Called when a node is clicked, or chosen with Enter or Space. */\n  onSelect?: (path: string, value: unknown) => void;\n  /** Draw a leaf value yourself. Return `undefined` to keep the built-in rendering. */\n  renderValue?: (value: unknown, path: string) => React.ReactNode | undefined;\n  /** Copy actions on rows, in the status bar and in the toolbar. Defaults to true. */\n  copyable?: boolean;\n  /** Receives copied text. Without it, copies go to the clipboard. */\n  onCopy?: (text: string, detail: { kind: JsonCopyKind; path: string }) => void;\n  /** Expand all, Collapse all and Copy JSON. Defaults to true. */\n  showToolbar?: boolean;\n  /** Path, type and copy actions for the focused node. Defaults to true. */\n  showStatusBar?: boolean;\n  /** Extra buttons placed before the built-in toolbar actions. */\n  actions?: React.ReactNode;\n  /** Height limit of the tree; it scrolls beyond this. */\n  maxHeight?: number | string;\n  /** Formats the hint shown for ISO-8601 timestamps. */\n  formatDate?: (date: Date) => string;\n  labels?: Partial<JsonViewerLabels>;\n}\n\nconst plural = (count: number, one: string, many: string) =>\n  `${count.toLocaleString()} ${count === 1 ? one : many}`;\n\nconst LABELS: JsonViewerLabels = {\n  tree: \"JSON\",\n  search: \"Search keys and values\",\n  clearSearch: \"Clear search\",\n  previousMatch: \"Previous match\",\n  nextMatch: \"Next match\",\n  noMatches: \"No matches\",\n  matchCount: (current, total) => `${current} of ${total}`,\n  expandAll: \"Expand all\",\n  collapseAll: \"Collapse all\",\n  copyJson: \"Copy JSON\",\n  copyPath: \"Copy path\",\n  copyValue: \"Copy value\",\n  copied: \"Copied\",\n  showMore: \"Show more\",\n  showLess: \"Show less\",\n  showMoreItems: (count) => `Show ${count.toLocaleString()} more`,\n  hiddenItems: (count) => `${count.toLocaleString()} hidden`,\n  keys: (count) => plural(count, \"key\", \"keys\"),\n  items: (count) => plural(count, \"item\", \"items\"),\n  characters: (count) => plural(count, \"character\", \"characters\"),\n  root: \"root\",\n  statusHint: \"Focus a node to see its path\",\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Helpers\n * -----------------------------------------------------------------------------------------------*/\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:shadow-[0_0_14px_-2px_color-mix(in_oklab,var(--color-primary)_45%,transparent)]\";\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst subscribeNothing = () => () => {};\nfunction useMounted() {\n  return React.useSyncExternalStore(\n    subscribeNothing,\n    () => true,\n    () => false,\n  );\n}\n\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/;\nconst ISO_DATE =\n  /^\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\nconst URL_VALUE = /^https?:\\/\\/[^\\s\"]+$/i;\n\n/** Path of a child, e.g. `payload.items[2].sku` or `headers[\"content-type\"]`. */\nexport function jsonChildPath(parent: string, key: string | number, inArray: boolean) {\n  if (inArray) return `${parent}[${key}]`;\n  const name = String(key);\n  if (IDENTIFIER.test(name)) return parent ? `${parent}.${name}` : name;\n  return `${parent}[${JSON.stringify(name)}]`;\n}\n\nfunction typeOf(value: unknown, ancestors: Set<object>): JsonValueType {\n  if (value === null) return \"null\";\n  switch (typeof value) {\n    case \"string\":\n      return \"string\";\n    case \"number\":\n      return \"number\";\n    case \"bigint\":\n      return \"bigint\";\n    case \"boolean\":\n      return \"boolean\";\n    case \"undefined\":\n      return \"undefined\";\n    case \"function\":\n      return \"function\";\n    case \"symbol\":\n      return \"symbol\";\n  }\n  if (value instanceof Date) return \"date\";\n  if (ancestors.has(value as object)) return \"circular\";\n  if (Array.isArray(value) || value instanceof Set) return \"array\";\n  return \"object\";\n}\n\ntype Entry = [key: string | number, value: unknown];\n\nfunction entriesOf(\n  value: unknown,\n  type: JsonValueType,\n  sortKeys: JsonViewerProps[\"sortKeys\"],\n): Entry[] {\n  if (type === \"array\")\n    return (value instanceof Set ? [...value] : (value as unknown[])).map((child, index) => [index, child]);\n  const entries: Entry[] =\n    value instanceof Map\n      ? [...value.entries()].map(([key, child]) => [String(key), child])\n      : Object.keys(value as object).map((key) => [key, (value as Record<string, unknown>)[key]]);\n  if (sortKeys) {\n    const compare =\n      typeof sortKeys === \"function\"\n        ? sortKeys\n        : (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true });\n    entries.sort((a, b) => compare(String(a[0]), String(b[0])));\n  }\n  return entries;\n}\n\n/** Text shown for a leaf, without string quotes. Search matches against this. */\nfunction displayText(value: unknown, type: JsonValueType) {\n  switch (type) {\n    case \"string\":\n      return JSON.stringify(value).slice(1, -1);\n    case \"bigint\":\n      return `${value as bigint}n`;\n    case \"date\": {\n      const time = (value as Date).getTime();\n      return Number.isNaN(time) ? \"Invalid Date\" : (value as Date).toISOString();\n    }\n    case \"function\":\n      return `ƒ ${(value as { name?: string }).name || \"anonymous\"}()`;\n    case \"circular\":\n      return \"[Circular]\";\n    case \"symbol\":\n      return String(value);\n    default:\n      return String(value);\n  }\n}\n\n/** JSON.stringify that survives bigints, Maps, Sets and circular references. */\nexport function toJsonString(value: unknown, space = 2) {\n  const stack: unknown[] = [];\n  const text = JSON.stringify(\n    value,\n    function (this: unknown, _key, current: unknown) {\n      if (typeof current === \"bigint\") return current.toString();\n      if (current instanceof Map) return Object.fromEntries(current);\n      if (current instanceof Set) return [...current];\n      if (typeof current === \"object\" && current !== null) {\n        while (stack.length && stack[stack.length - 1] !== this) stack.pop();\n        if (stack.includes(current)) return \"[Circular]\";\n        stack.push(current);\n      }\n      return current;\n    },\n    space,\n  );\n  return text ?? String(value);\n}\n\nfunction copyText(value: unknown, type: JsonValueType) {\n  if (type === \"object\" || type === \"array\") return toJsonString(value);\n  if (type === \"string\") return value as string;\n  return displayText(value, type);\n}\n\nasync function writeClipboard(text: string) {\n  try {\n    await navigator.clipboard.writeText(text);\n    return true;\n  } catch {\n    try {\n      const area = document.createElement(\"textarea\");\n      area.value = text;\n      area.setAttribute(\"readonly\", \"\");\n      area.style.position = \"fixed\";\n      area.style.opacity = \"0\";\n      document.body.appendChild(area);\n      area.select();\n      const ok = document.execCommand(\"copy\");\n      area.remove();\n      return ok;\n    } catch {\n      return false;\n    }\n  }\n}\n\nfunction formatBytes(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`;\n  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;\n  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\n}\n\nconst defaultDateFormat = (date: Date) =>\n  new Intl.DateTimeFormat(undefined, { dateStyle: \"medium\", timeStyle: \"long\" }).format(date);\n\n/* -------------------------------------------------------------------------------------------------\n * Flattening\n * -----------------------------------------------------------------------------------------------*/\n\ninterface Row {\n  kind: \"node\" | \"close\" | \"more\";\n  /** Unique row id; equals the node path for \"node\" rows. */\n  id: string;\n  path: string;\n  parent: string | null;\n  /** Container paths from the root down to the parent. */\n  ancestors: string[];\n  depth: number;\n  key: string | number | null;\n  inArray: boolean;\n  type: JsonValueType;\n  value: unknown;\n  size: number;\n  expanded: boolean;\n  last: boolean;\n  position: number;\n  setSize: number;\n  hidden: number;\n}\n\ninterface FlattenOptions {\n  isExpanded: (path: string, depth: number) => boolean;\n  limits: ReadonlyMap<string, number>;\n  pageSize: number;\n  sortKeys: JsonViewerProps[\"sortKeys\"];\n}\n\nfunction flatten(data: unknown, rootPath: string, rootName: string | undefined, options: FlattenOptions) {\n  const rows: Row[] = [];\n  const stack = new Set<object>();\n  const visit = (\n    value: unknown,\n    key: string | number | null,\n    path: string,\n    parent: string | null,\n    ancestors: string[],\n    depth: number,\n    inArray: boolean,\n    last: boolean,\n    position: number,\n    setSize: number,\n  ) => {\n    const type = typeOf(value, stack);\n    const container = type === \"object\" || type === \"array\";\n    const entries = container ? entriesOf(value, type, options.sortKeys) : [];\n    const expanded = container && entries.length > 0 && options.isExpanded(path, depth);\n    rows.push({\n      kind: \"node\",\n      id: path,\n      path,\n      parent,\n      ancestors,\n      depth,\n      key,\n      inArray,\n      type,\n      value,\n      size: entries.length,\n      expanded,\n      last,\n      position,\n      setSize,\n      hidden: 0,\n    });\n    if (!expanded) return;\n    stack.add(value as object);\n    const limit = Math.max(options.pageSize, options.limits.get(path) ?? 0);\n    const shown = Math.min(entries.length, limit);\n    const childAncestors = [...ancestors, path];\n    for (let index = 0; index < shown; index++) {\n      const [childKey, child] = entries[index];\n      visit(\n        child,\n        childKey,\n        jsonChildPath(path, childKey, type === \"array\"),\n        path,\n        childAncestors,\n        depth + 1,\n        type === \"array\",\n        index === entries.length - 1,\n        index + 1,\n        entries.length,\n      );\n    }\n    if (shown < entries.length)\n      rows.push({\n        kind: \"more\",\n        id: `${path}\\u0000more`,\n        path,\n        parent: path,\n        ancestors: childAncestors,\n        depth: depth + 1,\n        key: null,\n        inArray: type === \"array\",\n        type,\n        value,\n        size: entries.length,\n        expanded: false,\n        last: true,\n        position: shown + 1,\n        setSize: entries.length,\n        hidden: entries.length - shown,\n      });\n    stack.delete(value as object);\n    rows.push({\n      kind: \"close\",\n      id: `${path}\\u0000close`,\n      path,\n      parent,\n      ancestors,\n      depth,\n      key: null,\n      inArray,\n      type,\n      value,\n      size: entries.length,\n      expanded: true,\n      last,\n      position,\n      setSize,\n      hidden: 0,\n    });\n  };\n  visit(data, rootName ?? null, rootPath, null, [], 0, false, true, 1, 1);\n  return rows;\n}\n\ninterface Match {\n  path: string;\n  /** Each ancestor container with the index of the next step inside it. */\n  chain: { path: string; depth: number; index: number }[];\n}\n\nconst MAX_SEARCH_NODES = 50_000;\n\nfunction findMatches(data: unknown, rootPath: string, rootName: string | undefined, query: string, sortKeys: JsonViewerProps[\"sortKeys\"]) {\n  const matches: Match[] = [];\n  if (!query) return matches;\n  const stack = new Set<object>();\n  let visited = 0;\n  const visit = (value: unknown, key: string | number | null, path: string, depth: number, chain: Match[\"chain\"]) => {\n    if (++visited > MAX_SEARCH_NODES) return;\n    const type = typeOf(value, stack);\n    const keyHit = typeof key === \"string\" && key.toLowerCase().includes(query);\n    const container = type === \"object\" || type === \"array\";\n    const valueHit = !container && displayText(value, type).toLowerCase().includes(query);\n    if (keyHit || valueHit) matches.push({ path, chain });\n    if (!container) return;\n    stack.add(value as object);\n    entriesOf(value, type, sortKeys).forEach(([childKey, child], index) =>\n      visit(child, childKey, jsonChildPath(path, childKey, type === \"array\"), depth + 1, [\n        ...chain,\n        { path, depth, index },\n      ]),\n    );\n    stack.delete(value as object);\n  };\n  visit(data, rootName ?? null, rootPath, 0, []);\n  return matches;\n}\n\nfunction collectContainers(\n  data: unknown,\n  rootPath: string,\n  sortKeys: JsonViewerProps[\"sortKeys\"],\n  include: (path: string, depth: number) => boolean,\n) {\n  const paths: string[] = [];\n  const stack = new Set<object>();\n  let visited = 0;\n  const visit = (value: unknown, path: string, depth: number) => {\n    if (++visited > MAX_SEARCH_NODES) return;\n    const type = typeOf(value, stack);\n    if (type !== \"object\" && type !== \"array\") return;\n    if (include(path, depth)) paths.push(path);\n    stack.add(value as object);\n    for (const [key, child] of entriesOf(value, type, sortKeys))\n      visit(child, jsonChildPath(path, key, type === \"array\"), depth + 1);\n    stack.delete(value as object);\n  };\n  visit(data, rootPath, 0);\n  return paths;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Pieces\n * -----------------------------------------------------------------------------------------------*/\n\nconst styles = `@keyframes json-viewer-sweep{from{background-size:0% 100%}to{background-size:100% 100%}}`;\n\nconst markBase =\n  \"rounded-[3px] bg-no-repeat text-inherit [background-position:left] motion-safe:animate-[json-viewer-sweep_520ms_cubic-bezier(0.22,1,0.36,1)_both]\";\nconst markIdle =\n  \"bg-transparent [background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_38%,transparent),color-mix(in_oklab,var(--color-amber-400)_38%,transparent))] dark:[background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_30%,transparent),color-mix(in_oklab,var(--color-amber-400)_30%,transparent))]\";\nconst markCurrent =\n  \"bg-transparent text-foreground shadow-[0_0_0_1px_color-mix(in_oklab,var(--color-amber-500)_70%,transparent)] [background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_75%,transparent),color-mix(in_oklab,var(--color-amber-400)_75%,transparent))] dark:[background-image:linear-gradient(color-mix(in_oklab,var(--color-amber-400)_55%,transparent),color-mix(in_oklab,var(--color-amber-400)_55%,transparent))]\";\n\nfunction highlight(text: string, query: string, current: boolean): React.ReactNode {\n  if (!query) return text;\n  const lower = text.toLowerCase();\n  let at = lower.indexOf(query);\n  if (at === -1) return text;\n  const parts: React.ReactNode[] = [];\n  let from = 0;\n  while (at !== -1) {\n    if (at > from) parts.push(text.slice(from, at));\n    parts.push(\n      <mark key={at} className={cn(markBase, current ? markCurrent : markIdle)}>\n        {text.slice(at, at + query.length)}\n      </mark>,\n    );\n    from = at + query.length;\n    at = lower.indexOf(query, from);\n  }\n  if (from < text.length) parts.push(text.slice(from));\n  return parts;\n}\n\nconst PAD = 10;\nconst INDENT = 16;\n\nconst typeClass: Partial<Record<JsonValueType, string>> = {\n  string: \"text-[color-mix(in_oklab,var(--color-chart-2)_70%,var(--color-foreground))]\",\n  date: \"text-[color-mix(in_oklab,var(--color-chart-2)_70%,var(--color-foreground))]\",\n  number: \"text-chart-1\",\n  bigint: \"text-chart-1\",\n  boolean: \"text-[color-mix(in_oklab,var(--color-chart-4)_70%,var(--color-foreground))]\",\n  null: \"text-muted-foreground italic\",\n  undefined: \"text-muted-foreground italic\",\n  function: \"text-muted-foreground italic\",\n  symbol: \"text-muted-foreground italic\",\n  circular: \"text-muted-foreground italic\",\n};\n\nfunction Guides({ row, activeContainer }: { row: Row; activeContainer: string | null }) {\n  return row.ancestors.map((ancestor, level) => (\n    <span\n      key={level}\n      aria-hidden=\"true\"\n      className={cn(\n        \"pointer-events-none absolute inset-y-0 w-px transition-colors duration-150 motion-reduce:transition-none\",\n        ancestor === activeContainer ? \"bg-foreground/22\" : \"bg-border/80\",\n      )}\n      style={{ left: PAD + level * INDENT + 7.5 }}\n    />\n  ));\n}\n\n/* -------------------------------------------------------------------------------------------------\n * JsonViewer\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * A collapsible, searchable JSON tree for payloads, logs and trace attributes, with indent guides,\n * typed colors, copyable paths and full tree keyboard support.\n */\nexport function JsonViewer({\n  data,\n  rootName,\n  title,\n  description,\n  defaultExpandDepth = 2,\n  expanded: expandedProp,\n  defaultExpanded,\n  onExpandedChange,\n  showSearch = true,\n  search: searchProp,\n  defaultSearch = \"\",\n  onSearchChange,\n  maxStringLength = 120,\n  pageSize = 100,\n  sortKeys,\n  selectedPath: selectedProp,\n  defaultSelectedPath = null,\n  onSelect,\n  renderValue,\n  copyable = true,\n  onCopy,\n  showToolbar = true,\n  showStatusBar = true,\n  actions,\n  maxHeight,\n  formatDate = defaultDateFormat,\n  labels: labelsProp,\n  className,\n  onKeyDown,\n  ...props\n}: JsonViewerProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const id = React.useId();\n  const mounted = useMounted();\n  const rootPath = rootName ?? \"\";\n\n  // Expansion: controlled as a set of paths, or uncontrolled as a base rule plus overrides.\n  const controlled = React.useMemo(\n    () => (expandedProp ? new Set<string>(expandedProp) : null),\n    [expandedProp],\n  );\n  const [expansion, setExpansion] = React.useState<{\n    base: \"depth\" | \"all\" | \"none\";\n    overrides: ReadonlyMap<string, boolean>;\n  }>(() =>\n    defaultExpanded\n      ? { base: \"none\", overrides: new Map(defaultExpanded.map((path) => [path, true])) }\n      : { base: \"depth\", overrides: new Map() },\n  );\n  const ruleFor = React.useCallback(\n    (state: typeof expansion) => (path: string, depth: number) =>\n      state.overrides.get(path) ??\n      (state.base === \"all\" || (state.base === \"depth\" && depth < defaultExpandDepth)),\n    [defaultExpandDepth],\n  );\n  const isExpanded = React.useMemo(\n    () => (controlled ? (path: string) => controlled.has(path) : ruleFor(expansion)),\n    [controlled, expansion, ruleFor],\n  );\n\n  const commitExpansion = (next: typeof expansion) => {\n    setExpansion(next);\n    onExpandedChange?.(collectContainers(data, rootPath, sortKeys, ruleFor(next)));\n  };\n  const setPaths = (paths: { path: string; depth: number }[], value: boolean) => {\n    const changed = paths.filter(({ path, depth }) => isExpanded(path, depth) !== value);\n    if (!changed.length) return;\n    if (controlled) {\n      const next = new Set(controlled);\n      for (const { path } of changed) {\n        if (value) next.add(path);\n        else next.delete(path);\n      }\n      onExpandedChange?.([...next]);\n      return;\n    }\n    const overrides = new Map(expansion.overrides);\n    for (const { path } of changed) overrides.set(path, value);\n    commitExpansion({ base: expansion.base, overrides });\n  };\n  const expandAll = () => {\n    if (controlled) onExpandedChange?.(collectContainers(data, rootPath, sortKeys, () => true));\n    else commitExpansion({ base: \"all\", overrides: new Map() });\n  };\n  const collapseAll = () => {\n    if (controlled) onExpandedChange?.([rootPath]);\n    else commitExpansion({ base: \"none\", overrides: new Map([[rootPath, true]]) });\n  };\n\n  // Pagination per container, and full strings.\n  const [limits, setLimits] = React.useState<ReadonlyMap<string, number>>(() => new Map());\n  const [fullStrings, setFullStrings] = React.useState<ReadonlySet<string>>(() => new Set());\n\n  // Search\n  const [searchState, setSearchState] = React.useState(defaultSearch);\n  const search = searchProp ?? searchState;\n  const setSearch = (next: string) => {\n    if (searchProp === undefined) setSearchState(next);\n    onSearchChange?.(next);\n  };\n  const deferredSearch = React.useDeferredValue(search);\n  const query = deferredSearch.trim().toLowerCase();\n  const matches = React.useMemo(\n    () => findMatches(data, rootPath, rootName, query, sortKeys),\n    [data, rootPath, rootName, query, sortKeys],\n  );\n  const matchSet = React.useMemo(() => new Set(matches.map((match) => match.path)), [matches]);\n  const [current, setCurrent] = React.useState(0);\n  const currentMatch = matches[Math.min(current, matches.length - 1)];\n\n  // Selection and roving focus\n  const [selectedState, setSelectedState] = React.useState<string | null>(defaultSelectedPath);\n  const selected = selectedProp !== undefined ? selectedProp : selectedState;\n  const [activeId, setActiveId] = React.useState<string | null>(null);\n\n  const rows = React.useMemo(\n    () => flatten(data, rootPath, rootName, { isExpanded, limits, pageSize, sortKeys }),\n    [data, rootPath, rootName, isExpanded, limits, pageSize, sortKeys],\n  );\n  const navigable = React.useMemo(() => rows.filter((row) => row.kind !== \"close\"), [rows]);\n  const active = navigable.find((row) => row.id === activeId) ?? null;\n  const tabStop = active?.id ?? navigable[0]?.id;\n  const activeContainer = active\n    ? active.kind === \"node\" && active.expanded\n      ? active.path\n      : active.parent\n    : null;\n\n  const treeRef = React.useRef<HTMLDivElement>(null);\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const rowRefs = React.useRef(new Map<string, HTMLDivElement>());\n  const [focusRequest, setFocusRequest] = React.useState<{ id: string; tick: number } | null>(null);\n  const [scrollRequest, setScrollRequest] = React.useState<{ id: string; tick: number } | null>(null);\n  const scrollOnResults = React.useRef(false);\n\n  useIsoLayoutEffect(() => {\n    if (!focusRequest) return;\n    rowRefs.current.get(focusRequest.id)?.focus();\n  }, [focusRequest]);\n\n  useIsoLayoutEffect(() => {\n    if (!scrollRequest) return;\n    const element = rowRefs.current.get(scrollRequest.id);\n    const container = scrollRef.current;\n    if (!element || !container) return;\n    if (container.scrollHeight > container.clientHeight + 1) {\n      const top = element.offsetTop - container.offsetTop;\n      const bottom = top + element.offsetHeight;\n      if (top < container.scrollTop + 8 || bottom > container.scrollTop + container.clientHeight - 8)\n        container.scrollTop = Math.max(0, top - container.clientHeight / 2 + element.offsetHeight / 2);\n    } else element.scrollIntoView({ block: \"nearest\" });\n  }, [scrollRequest]);\n\n  const reveal = (match: Match) => {\n    setPaths(\n      match.chain.filter(({ path, depth }) => !isExpanded(path, depth)).map(({ path, depth }) => ({ path, depth })),\n      true,\n    );\n    const raise = match.chain.filter(\n      ({ path, index }) => index >= Math.max(pageSize, limits.get(path) ?? 0),\n    );\n    if (raise.length)\n      setLimits((currentLimits) => {\n        const next = new Map(currentLimits);\n        for (const { path, index } of raise)\n          next.set(path, Math.ceil((index + 1) / pageSize) * pageSize);\n        return next;\n      });\n    setActiveId(match.path);\n    setScrollRequest({ id: match.path, tick: Date.now() });\n  };\n\n  // Open the ancestors of every match when the query changes.\n  const matchKey = matches.map((match) => match.path).join(\"\\n\");\n  useIsoLayoutEffect(() => {\n    setCurrent(0);\n    if (!matches.length) return;\n    const needed = new Map<string, number>();\n    for (const match of matches)\n      for (const { path, depth } of match.chain) if (!isExpanded(path, depth)) needed.set(path, depth);\n    if (needed.size) setPaths([...needed].map(([path, depth]) => ({ path, depth })), true);\n    if (scrollOnResults.current) {\n      scrollOnResults.current = false;\n      reveal(matches[0]);\n    }\n  }, [matchKey]);\n\n  const goToMatch = (direction: 1 | -1) => {\n    if (!matches.length) return;\n    const next = (Math.min(current, matches.length - 1) + direction + matches.length) % matches.length;\n    setCurrent(next);\n    reveal(matches[next]);\n  };\n\n  // Copying\n  const [copied, setCopied] = React.useState<string | null>(null);\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(null), 1400);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n  const copy = async (text: string, kind: JsonCopyKind, path: string) => {\n    if (onCopy) onCopy(text, { kind, path });\n    else if (!(await writeClipboard(text))) return;\n    setCopied(`${kind}:${path}`);\n  };\n\n  const json = React.useMemo(() => toJsonString(data), [data]);\n  const bytes = React.useMemo(() => new TextEncoder().encode(json).length, [json]);\n\n  const select = (row: Row) => {\n    if (row.kind !== \"node\") return;\n    if (selectedProp === undefined) setSelectedState(row.path);\n    onSelect?.(row.path, row.value);\n  };\n  const toggle = (row: Row) => {\n    if (row.kind !== \"node\" || !row.size) return;\n    setPaths([{ path: row.path, depth: row.depth }], !row.expanded);\n  };\n  const showMore = (row: Row) => {\n    setLimits((currentLimits) => {\n      const next = new Map(currentLimits);\n      next.set(row.path, Math.max(pageSize, currentLimits.get(row.path) ?? 0) + pageSize);\n      return next;\n    });\n  };\n  const moveTo = (row: Row | undefined) => {\n    if (!row) return;\n    setActiveId(row.id);\n    setFocusRequest({ id: row.id, tick: Date.now() });\n  };\n\n  const handleTreeKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (event.target instanceof HTMLButtonElement || event.target instanceof HTMLAnchorElement) {\n      if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") return;\n    }\n    const index = navigable.findIndex((row) => row.id === (active?.id ?? tabStop));\n    const row = navigable[index];\n    if (!row) return;\n    const mod = event.metaKey || event.ctrlKey;\n    let handled = true;\n    switch (event.key) {\n      case \"ArrowDown\":\n        moveTo(navigable[Math.min(index + 1, navigable.length - 1)]);\n        break;\n      case \"ArrowUp\":\n        moveTo(navigable[Math.max(index - 1, 0)]);\n        break;\n      case \"PageDown\":\n        moveTo(navigable[Math.min(index + 10, navigable.length - 1)]);\n        break;\n      case \"PageUp\":\n        moveTo(navigable[Math.max(index - 10, 0)]);\n        break;\n      case \"Home\":\n        moveTo(navigable[0]);\n        break;\n      case \"End\":\n        moveTo(navigable[navigable.length - 1]);\n        break;\n      case \"ArrowRight\":\n        if (row.kind === \"node\" && row.size) {\n          if (!row.expanded) toggle(row);\n          else moveTo(navigable[index + 1]);\n        }\n        break;\n      case \"ArrowLeft\":\n        if (row.kind === \"node\" && row.expanded) toggle(row);\n        else if (row.parent !== null) moveTo(navigable.find((item) => item.id === row.parent));\n        break;\n      case \"Enter\":\n        if (row.kind === \"more\") showMore(row);\n        else if (row.size) toggle(row);\n        else select(row);\n        break;\n      case \" \":\n        if (row.kind === \"more\") showMore(row);\n        else select(row);\n        break;\n      case \"*\": {\n        const siblings = navigable.filter(\n          (item) => item.kind === \"node\" && item.parent === row.parent && item.size && !item.expanded,\n        );\n        setPaths(siblings.map((item) => ({ path: item.path, depth: item.depth })), true);\n        break;\n      }\n      case \"/\":\n        if (showSearch) searchRef.current?.focus();\n        else handled = false;\n        break;\n      default:\n        if (mod && (event.key === \"c\" || event.key === \"C\") && copyable && row.kind === \"node\") {\n          if (window.getSelection()?.toString()) {\n            handled = false;\n            break;\n          }\n          void copy(copyText(row.value, row.type), \"value\", row.path);\n        } else handled = false;\n    }\n    if (handled) {\n      event.preventDefault();\n      event.stopPropagation();\n    }\n  };\n\n  /* --------------------------------- Row rendering --------------------------------- */\n\n  const renderLeaf = (row: Row, isCurrent: boolean) => {\n    const custom = renderValue?.(row.value, row.path);\n    if (custom !== undefined) return custom;\n    const text = displayText(row.value, row.type);\n    if (row.type === \"string\") {\n      const raw = row.value as string;\n      const full = fullStrings.has(row.path);\n      const hitAt = query ? text.toLowerCase().indexOf(query) : -1;\n      const long = text.length > maxStringLength;\n      const cut = long && !full && !(hitAt >= maxStringLength - query.length);\n      const shown = cut ? text.slice(0, maxStringLength) : text;\n      const isUrl = URL_VALUE.test(raw);\n      const isDate = !isUrl && ISO_DATE.test(raw) && !Number.isNaN(Date.parse(raw));\n      const body = highlight(shown, query, isCurrent);\n      return (\n        <>\n          <span className={typeClass.string}>\n            <span className=\"opacity-55\">\"</span>\n            {isUrl ? (\n              <a\n                href={raw}\n                target=\"_blank\"\n                rel=\"noreferrer\"\n                tabIndex={-1}\n                onClick={(event) => event.stopPropagation()}\n                className=\"underline decoration-current/35 underline-offset-[3px] transition-[text-decoration-color] hover:decoration-current\"\n              >\n                {body}\n              </a>\n            ) : isDate ? (\n              <span className=\"underline decoration-current/30 decoration-dotted underline-offset-[3px]\">{body}</span>\n            ) : (\n              body\n            )}\n            {cut && <span className=\"opacity-55\">…</span>}\n            <span className=\"opacity-55\">\"</span>\n          </span>\n          {isDate && mounted && (\n            <span\n              data-slot=\"json-viewer-hint\"\n              className=\"ml-2 hidden font-sans text-[11px] whitespace-nowrap text-muted-foreground group-hover/row:inline group-data-[active=true]/row:inline\"\n            >\n              {formatDate(new Date(raw))}\n            </span>\n          )}\n          {long && (\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              onClick={(event) => {\n                event.stopPropagation();\n                setFullStrings((currentSet) => {\n                  const next = new Set(currentSet);\n                  if (!next.delete(row.path)) next.add(row.path);\n                  return next;\n                });\n              }}\n              aria-label={full ? labels.showLess : `${labels.showMore}, ${labels.characters(text.length - maxStringLength)}`}\n              className=\"ml-1.5 inline-flex h-[18px] translate-y-[-1px] items-center rounded-md bg-muted px-1.5 align-middle font-sans text-[11px] font-medium text-muted-foreground transition-colors hover:bg-primary/10 hover:text-primary\"\n            >\n              {full ? labels.showLess : `${labels.showMore} · ${(text.length - maxStringLength).toLocaleString()}`}\n            </button>\n          )}\n        </>\n      );\n    }\n    if (row.type === \"date\") {\n      const date = row.value as Date;\n      return (\n        <>\n          <span className={cn(typeClass.date, \"underline decoration-current/30 decoration-dotted underline-offset-[3px]\")}>\n            {highlight(text, query, isCurrent)}\n          </span>\n          {mounted && !Number.isNaN(date.getTime()) && (\n            <span className=\"ml-2 hidden font-sans text-[11px] text-muted-foreground group-hover/row:inline group-data-[active=true]/row:inline\">\n              {formatDate(date)}\n            </span>\n          )}\n        </>\n      );\n    }\n    return (\n      <span className={cn(typeClass[row.type], (row.type === \"number\" || row.type === \"bigint\") && \"tabular-nums\")}>\n        {highlight(text, query, isCurrent)}\n      </span>\n    );\n  };\n\n  const renderRow = (row: Row) => {\n    const indent = PAD + row.depth * INDENT;\n    if (row.kind === \"close\") {\n      return (\n        <div\n          key={row.id}\n          aria-hidden=\"true\"\n          className=\"relative flex min-h-[22px] items-start pr-3\"\n          style={{ paddingLeft: indent }}\n        >\n          <Guides row={row} activeContainer={activeContainer} />\n          <span className=\"w-4 shrink-0\" />\n          <span className=\"text-muted-foreground/70\">\n            {row.type === \"array\" ? \"]\" : \"}\"}\n            {!row.last && \",\"}\n          </span>\n        </div>\n      );\n    }\n\n    const isActive = row.id === tabStop;\n    if (row.kind === \"more\") {\n      return (\n        <div\n          key={row.id}\n          ref={(node) => {\n            if (node) rowRefs.current.set(row.id, node);\n            else rowRefs.current.delete(row.id);\n          }}\n          role=\"treeitem\"\n          aria-level={row.depth + 1}\n          aria-posinset={row.position}\n          aria-setsize={row.setSize}\n          aria-label={`${labels.showMoreItems(Math.min(pageSize, row.hidden))}, ${labels.hiddenItems(row.hidden)}`}\n          tabIndex={isActive ? 0 : -1}\n          data-slot=\"json-viewer-more\"\n          data-active={isActive && activeId !== null ? true : undefined}\n          onFocus={() => setActiveId(row.id)}\n          onClick={() => showMore(row)}\n          className={cn(\n            \"group/row relative flex min-h-[26px] cursor-pointer items-center pr-3 outline-none\",\n            \"focus-visible:bg-primary/[0.05] focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-inset\",\n          )}\n          style={{ paddingLeft: indent }}\n        >\n          <Guides row={row} activeContainer={activeContainer} />\n          <span className=\"w-4 shrink-0\" />\n          <span className=\"inline-flex items-center gap-2 font-sans text-xs\">\n            <span className=\"rounded-md bg-muted px-1.5 py-px font-medium text-foreground/80 transition-colors group-hover/row:bg-primary/10 group-hover/row:text-primary\">\n              {labels.showMoreItems(Math.min(pageSize, row.hidden))}\n            </span>\n            <span className=\"text-muted-foreground tabular-nums\">{labels.hiddenItems(row.hidden)}</span>\n          </span>\n        </div>\n      );\n    }\n\n    const container = row.type === \"object\" || row.type === \"array\";\n    const isMatch = matchSet.has(row.path);\n    const isCurrent = isMatch && currentMatch?.path === row.path;\n    const isSelected = selected === row.path;\n    const keyText = row.key === null ? null : String(row.key);\n    const keyHighlighted = typeof row.key === \"string\" && keyText !== null ? highlight(keyText, query, isCurrent) : keyText;\n    const count = row.type === \"array\" ? labels.items(row.size) : labels.keys(row.size);\n    const open = row.type === \"array\" ? \"[\" : \"{\";\n    const close = row.type === \"array\" ? \"]\" : \"}\";\n    const copiedValue = copied === `value:${row.path}`;\n    const copiedPath = copied === `path:${row.path}`;\n\n    return (\n      <div\n        key={row.id}\n        ref={(node) => {\n          if (node) rowRefs.current.set(row.id, node);\n          else rowRefs.current.delete(row.id);\n        }}\n        role=\"treeitem\"\n        aria-level={row.depth + 1}\n        aria-posinset={row.position}\n        aria-setsize={row.setSize}\n        aria-expanded={container && row.size ? row.expanded : undefined}\n        aria-selected={isSelected}\n        aria-label={container ? `${keyText ?? labels.root}, ${count}` : undefined}\n        tabIndex={isActive ? 0 : -1}\n        data-slot=\"json-viewer-node\"\n        data-type={row.type}\n        data-path={row.path}\n        data-match={isMatch ? (isCurrent ? \"current\" : \"true\") : undefined}\n        data-selected={isSelected || undefined}\n        data-active={isActive && activeId !== null ? true : undefined}\n        onFocus={() => setActiveId(row.id)}\n        onClick={() => {\n          if (window.getSelection()?.toString()) return;\n          setActiveId(row.id);\n          select(row);\n          if (container) toggle(row);\n        }}\n        className={cn(\n          \"group/row relative flex min-h-[22px] cursor-default items-start pr-3 outline-none\",\n          \"hover:bg-muted/45 focus-visible:bg-primary/[0.05] focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-inset\",\n          isSelected &&\n            \"bg-primary/[0.07] hover:bg-primary/[0.09] before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-primary\",\n          isCurrent && !isSelected && \"bg-amber-400/[0.08]\",\n        )}\n        style={{ paddingLeft: indent }}\n      >\n        <Guides row={row} activeContainer={activeContainer} />\n        <span aria-hidden=\"true\" className=\"flex h-[22px] w-4 shrink-0 items-center justify-center\">\n          {container && row.size > 0 && (\n            <ChevronRight\n              className={cn(\n                \"size-3.5 text-muted-foreground/80 transition-transform duration-150 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover/row:text-foreground motion-reduce:transition-none\",\n                row.expanded && \"rotate-90\",\n              )}\n              stroke={2}\n            />\n          )}\n        </span>\n        <span className=\"min-w-0 flex-1 [overflow-wrap:anywhere]\">\n          {keyText !== null && (\n            <>\n              <span\n                className={cn(\n                  row.inArray ? \"text-muted-foreground/75 tabular-nums\" : \"text-foreground\",\n                  row.depth === 0 && \"font-semibold\",\n                )}\n              >\n                {keyHighlighted}\n              </span>\n              <span className=\"text-muted-foreground/60\">: </span>\n            </>\n          )}\n          {container ? (\n            row.expanded ? (\n              <>\n                <span className=\"text-muted-foreground/70\">{open}</span>\n                {row.type === \"array\" && (\n                  <span className=\"ml-2 font-sans text-[11px] text-muted-foreground tabular-nums\">{count}</span>\n                )}\n              </>\n            ) : (\n              <>\n                <span className=\"text-muted-foreground/70\">{open}</span>\n                {row.size > 0 && (\n                  <span className=\"mx-px rounded-[4px] bg-muted px-1 text-muted-foreground transition-colors group-hover/row:bg-primary/10 group-hover/row:text-primary\">\n                    …\n                  </span>\n                )}\n                <span className=\"text-muted-foreground/70\">\n                  {close}\n                  {!row.last && \",\"}\n                </span>\n                <span className=\"ml-2 font-sans text-[11px] text-muted-foreground tabular-nums\">{count}</span>\n              </>\n            )\n          ) : (\n            <>\n              {renderLeaf(row, isCurrent)}\n              {!row.last && <span className=\"text-muted-foreground/70\">,</span>}\n            </>\n          )}\n        </span>\n        {copyable && (\n          <span\n            data-slot=\"json-viewer-row-actions\"\n            className=\"absolute top-[2px] right-1.5 hidden items-center gap-px rounded-lg border border-border/70 bg-popover/90 p-px shadow-sm backdrop-blur-md group-hover/row:flex group-focus-visible/row:flex\"\n          >\n            {row.path && (\n              <button\n                type=\"button\"\n                tabIndex={-1}\n                aria-label={`${labels.copyPath} ${row.path}`}\n                title={labels.copyPath}\n                onClick={(event) => {\n                  event.stopPropagation();\n                  void copy(row.path, \"path\", row.path);\n                }}\n                className=\"inline-flex size-[18px] items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n              >\n                {copiedPath ? (\n                  <Check className=\"size-3 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n                ) : (\n                  <Route className=\"size-3\" aria-hidden=\"true\" />\n                )}\n              </button>\n            )}\n            <button\n              type=\"button\"\n              tabIndex={-1}\n              aria-label={labels.copyValue}\n              title={labels.copyValue}\n              onClick={(event) => {\n                event.stopPropagation();\n                void copy(copyText(row.value, row.type), \"value\", row.path);\n              }}\n              className=\"inline-flex size-[18px] items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n            >\n              {copiedValue ? (\n                <Check className=\"size-3 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n              ) : (\n                <Copy className=\"size-3\" aria-hidden=\"true\" />\n              )}\n            </button>\n          </span>\n        )}\n      </div>\n    );\n  };\n\n  /* --------------------------------- Layout --------------------------------- */\n\n  const iconButton = cn(\n    \"inline-flex h-7 min-w-7 items-center justify-center gap-1.5 rounded-md px-1.5 text-xs font-medium text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none\",\n    focusRing,\n  );\n  const toolbarActions = (showToolbar || actions) && (\n    <div className=\"flex shrink-0 items-center gap-0.5\">\n      {actions}\n      {showToolbar && (\n        <>\n          <button type=\"button\" onClick={expandAll} aria-label={labels.expandAll} title={labels.expandAll} className={iconButton}>\n            <FoldDown className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n          </button>\n          <button type=\"button\" onClick={collapseAll} aria-label={labels.collapseAll} title={labels.collapseAll} className={iconButton}>\n            <FoldUp className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n          </button>\n          {copyable && (\n            <button\n              type=\"button\"\n              onClick={() => void copy(json, \"json\", rootPath)}\n              aria-label={copied === `json:${rootPath}` ? labels.copied : labels.copyJson}\n              title={labels.copyJson}\n              className={iconButton}\n            >\n              {copied === `json:${rootPath}` ? (\n                <Check className=\"size-4 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n              ) : (\n                <Copy className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n              )}\n              <span className=\"hidden @md/json:inline\">\n                {copied === `json:${rootPath}` ? labels.copied : labels.copyJson}\n              </span>\n            </button>\n          )}\n        </>\n      )}\n    </div>\n  );\n\n  const searchField = showSearch && (\n    <div\n      data-slot=\"json-viewer-search\"\n      className={cn(\n        \"flex h-8 min-w-0 flex-1 items-center gap-1.5 rounded-lg bg-muted/50 pr-1 pl-2.5 ring-1 ring-border/60 transition-[box-shadow,background-color] duration-150 ring-inset focus-within:bg-card focus-within:ring-2 focus-within:ring-primary/30 focus-within:shadow-[0_0_14px_-4px_color-mix(in_oklab,var(--color-primary)_45%,transparent)] motion-reduce:transition-none\",\n      )}\n    >\n      <Search className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n      <input\n        ref={searchRef}\n        type=\"text\"\n        value={search}\n        spellCheck={false}\n        autoComplete=\"off\"\n        aria-label={labels.search}\n        aria-controls={`${id}-tree`}\n        placeholder={labels.search}\n        onChange={(event) => {\n          scrollOnResults.current = true;\n          setSearch(event.target.value);\n        }}\n        onKeyDown={(event) => {\n          if (event.key === \"Enter\") {\n            event.preventDefault();\n            goToMatch(event.shiftKey ? -1 : 1);\n          } else if (event.key === \"Escape\" && search) {\n            event.preventDefault();\n            setSearch(\"\");\n          } else if (event.key === \"ArrowDown\" && currentMatch) {\n            event.preventDefault();\n            reveal(currentMatch);\n            setFocusRequest({ id: currentMatch.path, tick: Date.now() });\n          }\n        }}\n        className=\"h-full min-w-0 flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground\"\n      />\n      {query && (\n        <>\n          <span\n            aria-live=\"polite\"\n            className={cn(\n              \"shrink-0 px-1 text-xs whitespace-nowrap tabular-nums\",\n              matches.length ? \"text-muted-foreground\" : \"text-destructive\",\n            )}\n          >\n            {matches.length\n              ? labels.matchCount(Math.min(current, matches.length - 1) + 1, matches.length)\n              : labels.noMatches}\n          </span>\n          <span className=\"flex shrink-0 items-center\">\n            <button\n              type=\"button\"\n              onClick={() => goToMatch(-1)}\n              disabled={!matches.length}\n              aria-label={labels.previousMatch}\n              title={`${labels.previousMatch} (Shift+Enter)`}\n              className={cn(iconButton, \"h-6 min-w-6 px-0\")}\n            >\n              <ChevronUp className=\"size-3.5\" aria-hidden=\"true\" />\n            </button>\n            <button\n              type=\"button\"\n              onClick={() => goToMatch(1)}\n              disabled={!matches.length}\n              aria-label={labels.nextMatch}\n              title={`${labels.nextMatch} (Enter)`}\n              className={cn(iconButton, \"h-6 min-w-6 px-0\")}\n            >\n              <ChevronDown className=\"size-3.5\" aria-hidden=\"true\" />\n            </button>\n          </span>\n        </>\n      )}\n      {search && (\n        <button\n          type=\"button\"\n          onClick={() => {\n            setSearch(\"\");\n            searchRef.current?.focus();\n          }}\n          aria-label={labels.clearSearch}\n          title={labels.clearSearch}\n          className={cn(iconButton, \"h-6 min-w-6 px-0\")}\n        >\n          <X className=\"size-3.5\" aria-hidden=\"true\" />\n        </button>\n      )}\n    </div>\n  );\n\n  const meta = (\n    <span className=\"shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums\">{formatBytes(bytes)}</span>\n  );\n  // The status bar follows focus, then the selection, then the root.\n  const status =\n    (active?.kind === \"node\" ? active : null) ??\n    navigable.find((row) => row.kind === \"node\" && row.path === selected) ??\n    navigable[0] ??\n    null;\n  const statusType = status\n    ? status.type === \"object\"\n      ? labels.keys(status.size)\n      : status.type === \"array\"\n        ? labels.items(status.size)\n        : status.type === \"string\"\n          ? labels.characters((status.value as string).length)\n          : status.type\n    : null;\n\n  return (\n    <div\n      data-slot=\"json-viewer\"\n      className={cn(\n        \"@container/json flex min-w-0 flex-col overflow-hidden rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        className,\n      )}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        const target = event.target as HTMLElement;\n        if (\n          event.key === \"/\" &&\n          showSearch &&\n          !event.defaultPrevented &&\n          !(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)\n        ) {\n          event.preventDefault();\n          searchRef.current?.focus();\n        }\n      }}\n      {...props}\n    >\n      <style href=\"overtrue-json-viewer\" precedence=\"default\">\n        {styles}\n      </style>\n\n      {(title || description) && (\n        <div className=\"flex items-start gap-3 px-4 pt-3.5 pb-2.5\">\n          <div className=\"min-w-0 flex-1\">\n            <div className=\"flex min-w-0 items-baseline gap-2\">\n              {title && <p className=\"truncate text-sm leading-6 font-semibold tracking-tight\">{title}</p>}\n              {meta}\n            </div>\n            {description && <p className=\"truncate text-[13px] leading-5 text-muted-foreground\">{description}</p>}\n          </div>\n          {toolbarActions}\n        </div>\n      )}\n      {(showSearch || (!title && !description && (showToolbar || actions))) && (\n        <div\n          data-slot=\"json-viewer-toolbar\"\n          className={cn(\"flex items-center gap-2 px-3 pb-3\", title || description ? \"pt-0\" : \"pt-3\")}\n        >\n          {searchField || <span className=\"flex-1 pl-1\">{meta}</span>}\n          {!(title || description) && toolbarActions}\n        </div>\n      )}\n\n      <div\n        ref={scrollRef}\n        className=\"relative min-h-0 flex-1 overflow-auto border-t border-border/60\"\n        style={{ maxHeight }}\n      >\n        <div\n          ref={treeRef}\n          id={`${id}-tree`}\n          role=\"tree\"\n          aria-label={typeof title === \"string\" ? title : (rootName ?? labels.tree)}\n          onKeyDown={handleTreeKeyDown}\n          data-slot=\"json-viewer-tree\"\n          className=\"min-w-0 py-2 font-mono text-[12px] leading-[22px] [font-variant-ligatures:none] @md/json:text-[13px]\"\n        >\n          {rows.map(renderRow)}\n        </div>\n      </div>\n\n      {showStatusBar && (\n        <div\n          data-slot=\"json-viewer-status\"\n          className=\"flex h-9 shrink-0 items-center gap-2 border-t border-border/60 bg-muted/25 pr-1.5 pl-3\"\n        >\n          {status ? (\n            <>\n              <span className=\"min-w-0 flex-1 truncate font-mono text-xs text-foreground/85 [font-variant-ligatures:none]\" title={status.path}>\n                {status.path || labels.root}\n              </span>\n              {statusType && (\n                <span className=\"hidden shrink-0 text-[11px] text-muted-foreground tabular-nums @sm/json:inline\">\n                  {statusType}\n                </span>\n              )}\n              {copyable && (\n                <span className=\"flex shrink-0 items-center\">\n                  {status.path && (\n                    <button\n                      type=\"button\"\n                      onClick={() => void copy(status.path, \"path\", status.path)}\n                      aria-label={copied === `path:${status.path}` ? labels.copied : labels.copyPath}\n                      className={iconButton}\n                    >\n                      {copied === `path:${status.path}` ? (\n                        <Check className=\"size-3.5 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n                      ) : (\n                        <Route className=\"size-3.5\" aria-hidden=\"true\" />\n                      )}\n                      <span className=\"hidden @md/json:inline\">{labels.copyPath}</span>\n                    </button>\n                  )}\n                  <button\n                    type=\"button\"\n                    onClick={() => void copy(copyText(status.value, status.type), \"value\", status.path)}\n                    aria-label={copied === `value:${status.path}` ? labels.copied : labels.copyValue}\n                    className={iconButton}\n                  >\n                    {copied === `value:${status.path}` ? (\n                      <Check className=\"size-3.5 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n                    ) : (\n                      <Copy className=\"size-3.5\" aria-hidden=\"true\" />\n                    )}\n                    <span className=\"hidden @md/json:inline\">{labels.copyValue}</span>\n                  </button>\n                </span>\n              )}\n            </>\n          ) : (\n            <span className=\"truncate text-xs text-muted-foreground\">{labels.statusHint}</span>\n          )}\n        </div>\n      )}\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {copied ? labels.copied : \"\"}\n      </span>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/json-viewer. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
