{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "type": "registry:ui",
  "title": "Tree View",
  "description": "A hierarchy of items that open and close (folders and files, sections and pages), moved through to the WAI-ARIA tree pattern: Up and Down through what is visible, Right to open or go in, Left to close or go up, Home, End, typing a letter to jump, * to open every sibling, and Enter to choose.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/direction",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/tree-view.tsx",
      "type": "registry:ui",
      "target": "components/ui/tree-view.tsx",
      "content": "\"use client\";\n/**\n * @name tree-view\n * @category ui\n * @description A hierarchy of items that open and close (folders and files, sections and pages), moved through to the WAI-ARIA tree pattern: Up and Down through what is visible, Right to open or go in, Left to close or go up, Home, End, typing a letter to jump, * to open every sibling, and Enter to choose.\n * @when Navigating or choosing within nested items: a file tree, a table of contents, categories. For flat lists use a list or virtual-list; for a few levels of site links use navigation-menu; for nested data to compare use data-grid grouping.\n * @example\n * <TreeView\n *   aria-label=\"Files\"\n *   items={[\n *     { id: \"src\", label: \"src\", children: [{ id: \"app\", label: \"app.tsx\" }, { id: \"lib\", label: \"lib\", children: [{ id: \"cn\", label: \"cn.ts\" }] }] },\n *     { id: \"readme\", label: \"README.md\" },\n *   ]}\n *   defaultExpanded={[\"src\"]}\n *   onSelectedChange={(id) => open(id)}\n * />\n */\nimport { ChevronRight, File, Folder, FolderOpen } from \"lucide-react\";\nimport { useRef, useState, type ComponentProps, type KeyboardEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\nimport { inlineStep } from \"@/lib/direction\";\n\nexport type TreeItem = {\n  id: string;\n  label: string;\n  /** Shown before the label. Default: a folder for items with children, a file otherwise. */\n  icon?: ReactNode;\n  children?: readonly TreeItem[];\n  disabled?: boolean;\n};\n\nexport type TreeViewProps = Omit<ComponentProps<\"ul\">, \"defaultValue\" | \"onSelect\"> & {\n  items: readonly TreeItem[];\n  /** The ids of open items. Controlled with `onExpandedChange`. */\n  expanded?: readonly string[];\n  defaultExpanded?: readonly string[];\n  onExpandedChange?: (expanded: readonly string[]) => void;\n  /** The chosen item's id. Controlled with `onSelectedChange`. */\n  selected?: string | null;\n  defaultSelected?: string | null;\n  onSelectedChange?: (id: string) => void;\n  /** Draws an item's label; the default is its text. */\n  renderLabel?: (item: TreeItem) => ReactNode;\n};\n\ntype Row = { item: TreeItem; level: number; parent: string | null; setSize: number; position: number };\n\nconst EMPTY: readonly string[] = [];\n\nexport function TreeView({\n  items,\n  expanded: expandedProp,\n  defaultExpanded = EMPTY,\n  onExpandedChange,\n  selected: selectedProp,\n  defaultSelected = null,\n  onSelectedChange,\n  renderLabel,\n  className,\n  ...props\n}: TreeViewProps) {\n  const [expanded, setExpanded] = useControllableState<readonly string[]>({ value: expandedProp, defaultValue: defaultExpanded, onChange: onExpandedChange });\n  const [selected, setSelected] = useControllableState<string | null>({ value: selectedProp, defaultValue: defaultSelected, onChange: (id) => id !== null && onSelectedChange?.(id) });\n  const [focusId, setFocusId] = useState<string | null>(null);\n  const typed = useRef({ text: \"\", at: 0 });\n  const refs = useRef(new Map<string, HTMLLIElement | null>());\n\n  // The visible rows in order: an item's children only when it is open.\n  const rows: Row[] = [];\n  const walk = (list: readonly TreeItem[], level: number, parent: string | null): void => {\n    list.forEach((item, index) => {\n      rows.push({ item, level, parent, setSize: list.length, position: index + 1 });\n      if (item.children && item.children.length > 0 && expanded.includes(item.id)) walk(item.children, level + 1, item.id);\n    });\n  };\n  walk(items, 1, null);\n  const current = rows.find((row) => row.item.id === focusId) ?? rows.find((row) => row.item.id === selected) ?? rows[0];\n\n  const focus = (id: string | undefined): void => {\n    if (!id) return;\n    setFocusId(id);\n    refs.current.get(id)?.focus();\n  };\n  const toggle = (id: string, open?: boolean): void => {\n    const isOpen = expanded.includes(id);\n    const want = open ?? !isOpen;\n    if (want === isOpen) return;\n    setExpanded(want ? [...expanded, id] : expanded.filter((x) => x !== id));\n  };\n  const onKeyDown = (event: KeyboardEvent<HTMLUListElement>): void => {\n    if (!current) return;\n    const index = rows.indexOf(current);\n    const hasChildren = Boolean(current.item.children?.length);\n    const open = expanded.includes(current.item.id);\n    const step = inlineStep(event.key, event.currentTarget);\n    // Any key that is not a letter ends a run of typed letters.\n    if (event.key.length !== 1) typed.current = { text: \"\", at: 0 };\n    if (event.key === \"ArrowDown\") focus(rows[index + 1]?.item.id);\n    else if (event.key === \"ArrowUp\") focus(rows[index - 1]?.item.id);\n    else if (step === 1) {\n      if (hasChildren && !open) toggle(current.item.id, true);\n      else if (hasChildren) focus(rows[index + 1]?.item.id);\n    } else if (step === -1) {\n      if (hasChildren && open) toggle(current.item.id, false);\n      else if (current.parent) focus(current.parent);\n    } else if (event.key === \"Home\") focus(rows[0]?.item.id);\n    else if (event.key === \"End\") focus(rows[rows.length - 1]?.item.id);\n    else if (event.key === \"Enter\" || event.key === \" \") {\n      if (!current.item.disabled) setSelected(current.item.id);\n      if (event.key === \"Enter\" && hasChildren) toggle(current.item.id);\n    } else if (event.key === \"*\") {\n      const siblings = rows.filter((row) => row.parent === current.parent && row.item.children?.length).map((row) => row.item.id);\n      setExpanded([...new Set([...expanded, ...siblings])]);\n    } else if (event.key.length === 1 && /\\S/.test(event.key)) {\n      // Type-ahead: letters typed in quick succession find the next item that starts with them.\n      const now = event.timeStamp;\n      typed.current = { text: now - typed.current.at < 600 ? typed.current.text + event.key.toLowerCase() : event.key.toLowerCase(), at: now };\n      const order = [...rows.slice(index + 1), ...rows.slice(0, index + 1)];\n      const hit = order.find((row) => row.item.label.toLowerCase().startsWith(typed.current.text)) ?? order.find((row) => row.item.label.toLowerCase().startsWith(event.key.toLowerCase()));\n      focus(hit?.item.id);\n    } else return;\n    event.preventDefault();\n  };\n\n  const render = (list: readonly TreeItem[], level: number): ReactNode =>\n    list.map((item, index) => {\n      const hasChildren = Boolean(item.children && item.children.length > 0);\n      const open = hasChildren && expanded.includes(item.id);\n      const chosen = selected === item.id;\n      return (\n        <li\n          key={item.id}\n          ref={(node) => {\n            refs.current.set(item.id, node);\n          }}\n          role=\"treeitem\"\n          aria-level={level}\n          aria-setsize={list.length}\n          aria-posinset={index + 1}\n          aria-expanded={hasChildren ? open : undefined}\n          aria-selected={chosen}\n          aria-disabled={item.disabled || undefined}\n          tabIndex={current?.item.id === item.id ? 0 : -1}\n          data-slot=\"tree-view-item\"\n          className=\"outline-none focus-visible:[&>div]:outline-2 focus-visible:[&>div]:-outline-offset-2 focus-visible:[&>div]:outline-ring\"\n          onFocus={(event) => {\n            if (event.target === event.currentTarget) setFocusId(item.id);\n          }}\n        >\n          <div\n            className={cn(\n              \"flex min-h-9 cursor-default items-center gap-1.5 rounded-control pe-2 text-sm select-none hover:bg-accent pointer-coarse:min-h-10\",\n              chosen && \"bg-highlight-soft font-medium hover:bg-highlight-soft\",\n              item.disabled && \"opacity-50\",\n            )}\n            style={{ paddingInlineStart: `${(level - 1) * 1.25 + 0.25}rem` }}\n            onClick={() => {\n              focus(item.id);\n              if (hasChildren) toggle(item.id);\n              if (!item.disabled) setSelected(item.id);\n            }}\n          >\n            <ChevronRight\n              aria-hidden=\"true\"\n              className={cn(\n                \"size-4 shrink-0 text-muted-foreground transition-transform duration-instant motion-reduce:transition-none rtl:-scale-x-100\",\n                open && \"rotate-90 rtl:-rotate-90\",\n                !hasChildren && \"invisible\",\n              )}\n            />\n            <span aria-hidden=\"true\" className=\"shrink-0 text-muted-foreground [&>svg]:size-4\">\n              {item.icon ?? (hasChildren ? open ? <FolderOpen className=\"size-4\" /> : <Folder className=\"size-4\" /> : <File className=\"size-4\" />)}\n            </span>\n            <span className=\"min-w-0 truncate\" dir=\"auto\">\n              {renderLabel ? renderLabel(item) : item.label}\n            </span>\n          </div>\n          {open ? (\n            <ul role=\"group\" className=\"flex flex-col\">\n              {render(item.children ?? [], level + 1)}\n            </ul>\n          ) : null}\n        </li>\n      );\n    });\n\n  return (\n    <ul data-slot=\"tree-view\" role=\"tree\" className={cn(\"flex min-w-0 flex-col\", className)} onKeyDown={onKeyDown} {...props}>\n      {render(items, 1)}\n    </ul>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Navigating or choosing within nested items: a file tree, a table of contents, categories. For flat lists use a list or virtual-list; for a few levels of site links use navigation-menu; for nested data to compare use data-grid grouping.",
    "example": "<TreeView\n  aria-label=\"Files\"\n  items={[\n    { id: \"src\", label: \"src\", children: [{ id: \"app\", label: \"app.tsx\" }, { id: \"lib\", label: \"lib\", children: [{ id: \"cn\", label: \"cn.ts\" }] }] },\n    { id: \"readme\", label: \"README.md\" },\n  ]}\n  defaultExpanded={[\"src\"]}\n  onSelectedChange={(id) => open(id)}\n/>",
    "client": true
  }
}
