{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "type": "registry:ui",
  "title": "Tree View",
  "description": "Nested folders and structured content with expandable branches, selection, guide lines, and keyboard navigation.",
  "dependencies": [
    "@remixicon/react@^4.9.0",
    "motion@^12.42.2",
    "react-aria-components@^1.17.0"
  ],
  "registryDependencies": [
    "cx",
    "direction"
  ],
  "files": [
    {
      "path": "components/base/dropdown/menu-styles.ts",
      "content": "/**\n * Shared visual recipe for BoardUI menu surfaces.\n *\n * Select and Dropdown intentionally keep their distinct React Aria semantics\n * (single-value listbox vs. action menu), while consuming the same panel,\n * motion, and row treatments from here.\n */\nexport const MENU_POPOVER_SURFACE = [\n  // z-110 sits above the modal layer (z-100), so menus opened inside a\n  // Modal or Drawer render over it rather than behind its backdrop.\n  \"z-110 max-w-[calc(100vw-32px)] overflow-y-auto\",\n  \"rounded-2xl border border-border-button-default bg-background-primary-default p-2.5 shadow-dropdown\",\n  \"transition duration-150 ease-out\",\n  \"data-[entering]:opacity-0 data-[entering]:scale-95 data-[entering]:blur-[2px]\",\n  \"data-[exiting]:opacity-0 data-[exiting]:scale-95 data-[exiting]:blur-[2px]\",\n  \"data-[placement=bottom]:origin-top-left rtl:data-[placement=bottom]:origin-top-right data-[placement=top]:origin-bottom-left rtl:data-[placement=top]:origin-bottom-right\",\n  \"data-[placement=left]:origin-right data-[placement=right]:origin-left\",\n].join(\" \");\n\nexport const MENU_POPOVER_WIDTH = \"w-[266px]\";\n\n/**\n * BoardUI's compact dropdown (the project board's and the chat's menus, and\n * the canvas editor's app menus): a 14px panel at 4px padding over\n * px-2 py-1.5 rows. Layered over `MENU_POPOVER_SURFACE` and `MENU_ITEM`; the\n * rows' 10px radius sits concentric 4px inside the panel's 14px.\n */\nexport const MENU_POPOVER_COMPACT = \"rounded-[14px] p-1\";\n\nexport const MENU_ITEM_COMPACT = \"px-2 py-1.5\";\n\n/**\n * `DropdownDivider` bleeds through the default p-2.5 panel; in the compact\n * panel it bleeds through p-1 and sits in the rows' 4px gap on each side.\n */\nexport const MENU_DIVIDER_COMPACT = \"-mx-1 my-0\";\n\nexport const MENU_ITEMS_CONTAINER = \"flex w-full flex-col gap-1 outline-none\";\n\nexport const MENU_ITEM = [\n  \"flex w-full cursor-pointer items-center gap-2 rounded-2lg p-2 text-start\",\n  \"text-text-primary outline-none transition-colors\",\n].join(\" \");\n\nexport const MENU_ITEM_ACTIVE = \"bg-dropdown-item-hover-background\";\n\nexport const MENU_ITEM_INTERACTIVE =\n  \"hover:bg-dropdown-item-hover-background focus-visible:bg-dropdown-item-hover-background\";\n",
      "type": "registry:component",
      "target": "components/base/dropdown/menu-styles.ts"
    },
    {
      "path": "components/base/tree-view/tree-view.tsx",
      "content": "\"use client\";\n\nimport { useContext, useState } from \"react\";\nimport type { ComponentProps, ComponentType, ContextType, KeyboardEventHandler, ReactNode, Ref } from \"react\";\nimport { AnimatePresence, motion, useIsPresent, useReducedMotion } from \"motion/react\";\nimport { RiArrowRightSLine, RiFileLine, RiFolder3Line, RiFolderOpenLine } from \"@remixicon/react\";\nimport {\n  Button as AriaButton,\n  CollectionRendererContext,\n  DefaultCollectionRenderer,\n  Tree as AriaTree,\n  TreeItem as AriaTreeItem,\n  TreeItemContent,\n  TreeStateContext,\n} from \"react-aria-components\";\nimport type {\n  Key,\n  TreeProps as AriaTreeProps,\n  TreeItemProps as AriaTreeItemProps,\n} from \"react-aria-components\";\nimport { useDirection } from \"@/components/foundations/direction/direction\";\nimport { MENU_ITEM_ACTIVE } from \"@/components/base/dropdown/menu-styles\";\nimport { cx } from \"@/utils/cx\";\n\ntype IconComponent = ComponentType<{\n  className?: string;\n  \"aria-hidden\"?: boolean | \"true\" | \"false\";\n}>;\n\nexport interface TreeViewProps<T extends object> extends AriaTreeProps<T> {\n  /** Medium rows are 36px tall; small rows are 32px. */\n  size?: \"sm\" | \"md\";\n  /** Show connected trunks and curved branches beside nested rows. */\n  showGuides?: boolean;\n  onKeyDownCapture?: KeyboardEventHandler<HTMLDivElement>;\n  ref?: Ref<HTMLDivElement>;\n}\n\n/**\n * A source-owned tree for nested folders and structured content. React Aria\n * manages expansion, selection, typeahead, and locale-aware keyboard navigation.\n * Supply an aria-label or aria-labelledby and stable, unique item ids.\n * The tree grows with its content, leaving scrolling to the enclosing page.\n */\nexport function TreeView<T extends object>({\n  size = \"md\",\n  showGuides = true,\n  selectionMode = \"single\",\n  renderEmptyState = () => \"No items.\",\n  className,\n  onKeyDownCapture,\n  ref,\n  ...props\n}: TreeViewProps<T>) {\n  const direction = useDirection();\n  const parentRenderer = useContext(CollectionRendererContext);\n  const renderer = parentRenderer === DefaultCollectionRenderer && !props.dragAndDropHooks\n    ? TREE_VIEW_RENDERER\n    : parentRenderer;\n\n  return (\n    <div\n      className=\"contents\"\n      onKeyDownCapture={(event) => {\n        onKeyDownCapture?.(event);\n        if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;\n        if (event.key !== (direction === \"rtl\" ? \"ArrowLeft\" : \"ArrowRight\")) return;\n        const row = event.target;\n        if (!(row instanceof HTMLElement) || row.getAttribute(\"role\") !== \"row\" || row.getAttribute(\"aria-expanded\") !== \"true\") return;\n\n        // React Aria expands closed branches and handles parent navigation.\n        // Complete forward navigation for an already-expanded branch, skipping\n        // disabled rows. Focusing the child also updates React Aria's focus state.\n        const level = Number(row.getAttribute(\"aria-level\"));\n        const tree = row.closest('[role=\"treegrid\"]');\n        const rows = Array.from(tree?.querySelectorAll<HTMLElement>('[role=\"row\"][data-key]') ?? [])\n          .filter((item) => item.closest('[role=\"treegrid\"]') === tree && !item.closest('[data-tree-view-exiting]'));\n        for (let index = rows.indexOf(row) + 1; index < rows.length; index++) {\n          const child = rows[index];\n          if (Number(child.getAttribute(\"aria-level\")) <= level) break;\n          if (child.getAttribute(\"aria-disabled\") !== \"true\") {\n            event.preventDefault();\n            event.stopPropagation();\n            child.focus();\n            return;\n          }\n        }\n      }}\n    >\n      <CollectionRendererContext.Provider value={renderer}>\n        <AriaTree\n          {...props}\n          ref={ref}\n          selectionMode={selectionMode}\n          data-size={size}\n          data-show-guides={showGuides}\n          renderEmptyState={renderEmptyState}\n          className={(state) => cx(\n            \"group/tree-view flex w-full min-w-0 flex-col rounded-3xl border border-border-button-default bg-background-primary-default p-2 outline-none\",\n            renderer === TREE_VIEW_RENDERER ? \"gap-0\" : \"gap-0.5\",\n            \"data-[empty]:px-4 data-[empty]:py-8 data-[empty]:text-center data-[empty]:text-body-regular data-[empty]:text-text-tertiary\",\n            \"data-[focus-visible]:ring-2 data-[focus-visible]:ring-border-focus-ring\",\n            typeof className === \"function\" ? className(state) : className,\n          )}\n        />\n      </CollectionRendererContext.Provider>\n    </div>\n  );\n}\n\nexport interface TreeViewItemProps<T extends object = object>\n  extends Omit<AriaTreeItemProps<T>, \"textValue\" | \"children\"> {\n  /** Visible label, also used for accessible naming and typeahead by default. */\n  label: string;\n  textValue?: string;\n  /** Defaults to a folder for branches and a file for leaves. null hides it. */\n  icon?: IconComponent | null;\n  /** Optional replacement icon while a branch is open. */\n  expandedIcon?: IconComponent;\n  iconClassName?: string;\n  /** Optional metadata or a badge at the end of the row. */\n  trailingContent?: ReactNode;\n  /** Nested TreeViewItem elements or a TreeViewCollection. */\n  children?: ReactNode;\n  ref?: Ref<HTMLDivElement>;\n}\n\nexport function TreeViewItem<T extends object = object>({\n  label,\n  textValue = label,\n  icon,\n  expandedIcon,\n  iconClassName,\n  trailingContent,\n  children,\n  className,\n  style,\n  ref,\n  ...props\n}: TreeViewItemProps<T>) {\n  const direction = useDirection();\n\n  return (\n    <AriaTreeItem\n      {...props}\n      ref={ref}\n      textValue={textValue}\n      style={(state) => ({\n        paddingInlineStart: `calc(0.5rem + ${(state.level - 1)} * 1.25rem)`,\n        ...(typeof style === \"function\" ? style(state) : style),\n      })}\n      className={(state) => cx(\n        \"relative flex min-h-9 min-w-0 cursor-pointer items-center gap-2 rounded-xl pe-2 text-body-regular text-text-primary outline-none\",\n        \"transition-[background-color,color,box-shadow] duration-150 motion-reduce:transition-none\",\n        \"group-data-[size=sm]/tree-view:min-h-8 group-data-[size=sm]/tree-view:text-body-2-regular\",\n        (state.isHovered || state.isPressed || state.isFocusVisible) && !state.isDisabled && MENU_ITEM_ACTIVE,\n        state.isSelected && MENU_ITEM_ACTIVE,\n        state.isFocusVisible && \"ring-2 ring-inset ring-border-focus-ring\",\n        state.isDisabled && \"cursor-default text-text-placeholder\",\n        typeof className === \"function\" ? className(state) : className,\n      )}\n    >\n      <TreeItemContent>\n        {({ hasChildItems, isExpanded, isDisabled, level, state, id }) => {\n          const Icon = icon === null ? null : (\n            isExpanded && expandedIcon\n              ? expandedIcon\n              : icon ?? (hasChildItems ? (isExpanded ? RiFolderOpenLine : RiFolder3Line) : RiFileLine)\n          );\n\n          return (\n            <>\n              <TreeGuides state={state} id={id} level={level} expanded={hasChildItems && isExpanded} branchWidth={hasChildItems ? 12 : 16} direction={direction} />\n              <span className=\"flex shrink-0 items-center gap-1\">\n                {hasChildItems ? (\n                  <AriaButton\n                    slot=\"chevron\"\n                    isDisabled={isDisabled}\n                    className=\"flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md text-foreground-icon-tertiary outline-none transition-colors hover:text-foreground-icon-primary data-[focus-visible]:ring-2 data-[focus-visible]:ring-border-focus-ring\"\n                  >\n                    <RiArrowRightSLine\n                      aria-hidden\n                      className={cx(\n                        \"size-4 opacity-50 transition-transform duration-150 motion-reduce:transition-none\",\n                        isExpanded ? \"rotate-90\" : direction === \"rtl\" && \"rotate-180\",\n                      )}\n                    />\n                  </AriaButton>\n                ) : (\n                  // Leaves need less disclosure space. Keep root icons aligned,\n                  // and pull nested leaves in so their branch stays compact.\n                  <span aria-hidden className={cx(\"h-5 shrink-0\", level > 1 ? \"w-2\" : \"w-5\")} />\n                )}\n                {Icon && <Icon aria-hidden className={cx(\n                  \"size-4 shrink-0 opacity-50\",\n                  hasChildItems ? \"text-foreground-icon-primary\" : \"text-foreground-icon-secondary\",\n                  iconClassName,\n                )} />}\n              </span>\n              <span className=\"min-w-0 flex-1 truncate text-start\"><bdi>{label}</bdi></span>\n              {trailingContent != null && (\n                <span className=\"ms-auto shrink-0 text-caption-1-regular text-text-tertiary\">{trailingContent}</span>\n              )}\n            </>\n          );\n        }}\n      </TreeItemContent>\n      {children}\n    </AriaTreeItem>\n  );\n}\n\n/** Use Collection for recursive rendering of data-driven trees. */\nexport { Collection as TreeViewCollection } from \"react-aria-components\";\n\nconst TREE_VIEW_RENDERER = {\n  ...DefaultCollectionRenderer,\n  CollectionRoot: AnimatedTreeCollection,\n};\n\nfunction AnimatedTreeCollection({ collection, ...props }: ComponentProps<typeof DefaultCollectionRenderer.CollectionRoot>) {\n  const state = useContext(TreeStateContext);\n  if (!state) return <DefaultCollectionRenderer.CollectionRoot collection={collection} {...props} />;\n\n  return (\n    <AnimatePresence initial={false}>\n      {Array.from(collection).filter((node) => node.type !== \"content\").map((node) => (\n        <AnimatedTreeRow key={node.key} state={state}>\n          {node.render?.(node)}\n        </AnimatedTreeRow>\n      ))}\n    </AnimatePresence>\n  );\n}\n\ntype TreeState = NonNullable<ContextType<typeof TreeStateContext>>;\n\nfunction TreeGuides({ state, id, level, expanded, branchWidth, direction }: {\n  state: TreeState;\n  id: Key;\n  level: number;\n  expanded: boolean;\n  branchWidth: number;\n  direction: \"ltr\" | \"rtl\";\n}) {\n  const node = state.collection.getItem(id);\n  if (!node) return null;\n\n  // A descendant carries an outer trunk only when its ancestor has a sibling\n  // still to come. This keeps the line connected through an expanded subtree,\n  // while the final child's elbow closes that level of the tree.\n  const continuingLevels: number[] = [];\n  let ancestor = node.parentKey != null ? state.collection.getItem(node.parentKey) : null;\n  let ancestorLevel = level - 1;\n  while (ancestor) {\n    if (ancestor.type === \"item\") {\n      if (ancestorLevel > 1 && ancestor.nextKey != null) continuingLevels.push(ancestorLevel - 2);\n      ancestorLevel--;\n    }\n    ancestor = ancestor.parentKey != null ? state.collection.getItem(ancestor.parentKey) : null;\n  }\n\n  const axis = (depth: number) => `calc(1.125rem + ${depth} * 1.25rem)`;\n\n  return (\n    <span aria-hidden data-tree-view-guides className=\"pointer-events-none absolute inset-0 text-foreground-icon-quaternary group-data-[show-guides=false]/tree-view:hidden\">\n      {continuingLevels.map((depth) => (\n        <span key={depth} data-tree-view-trunk className=\"absolute -inset-y-px w-px bg-current\" style={{ insetInlineStart: axis(depth) }} />\n      ))}\n      {level > 1 && (\n        <span data-tree-view-branch className=\"absolute -inset-y-px\" style={{ insetInlineStart: axis(level - 2), width: branchWidth }}>\n          <span className=\"absolute start-0 top-0 w-px bg-current\" style={{ bottom: \"calc(50% + 6px)\" }} />\n          <svg\n            width={branchWidth}\n            height=\"7\"\n            viewBox={`0 0 ${branchWidth} 7`}\n            fill=\"none\"\n            className={cx(\"absolute start-0\", direction === \"rtl\" && \"-scale-x-100\")}\n            style={{ top: \"calc(50% - 6px)\" }}\n          >\n            <path d={`M0.5 0 Q0.5 6 6.5 6 H${branchWidth - 0.5}`} stroke=\"currentColor\" strokeWidth=\"1\" />\n          </svg>\n          {node.nextKey != null && (\n            <span data-tree-view-tail className=\"absolute start-0 bottom-0 w-px bg-current\" style={{ top: \"calc(50% - 6px)\" }} />\n          )}\n        </span>\n      )}\n      {expanded && (\n        <span data-tree-view-bridge className=\"absolute -bottom-px w-px bg-current\" style={{ insetInlineStart: axis(level - 1), top: \"calc(50% + 8px)\" }} />\n      )}\n    </span>\n  );\n}\n\nfunction AnimatedTreeRow({ state, children }: { state: TreeState; children: ReactNode }) {\n  const isPresent = useIsPresent();\n  const reduceMotion = useReducedMotion();\n  const [lastPresentState, setLastPresentState] = useState(state);\n  if (isPresent && lastPresentState !== state) setLastPresentState(state);\n\n  // Preserve the row's last collection while it fades out. The live tree has\n  // already removed it from keyboard navigation; the retained visual is inert.\n  return (\n    <motion.div\n      role=\"presentation\"\n      className=\"relative min-w-0 shrink-0 overflow-hidden\"\n      data-tree-view-exiting={!isPresent || undefined}\n      aria-hidden={!isPresent || undefined}\n      inert={!isPresent}\n      initial={reduceMotion ? false : { height: 0, paddingTop: 0, paddingBottom: 0, opacity: 0, y: -4, filter: \"blur(4px)\" }}\n      animate={{ height: \"auto\", paddingTop: 1, paddingBottom: 1, opacity: 1, y: 0, filter: \"blur(0px)\" }}\n      exit={{ height: 0, paddingTop: 0, paddingBottom: 0, opacity: 0, y: reduceMotion ? 0 : -4, filter: reduceMotion ? \"blur(0px)\" : \"blur(4px)\" }}\n      transition={{ duration: reduceMotion ? 0 : 0.28, ease: [0.22, 1, 0.36, 1] }}\n    >\n      <TreeStateContext.Provider value={isPresent ? state : lastPresentState}>\n        {children}\n      </TreeStateContext.Provider>\n    </motion.div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/base/tree-view/tree-view.tsx"
    }
  ],
  "meta": {
    "docsUrl": "https://www.boardui.com/components/tree-view",
    "example": "import { TreeView, TreeViewItem } from \"@/components/base/tree-view/tree-view\";\n\nexport function Example() {\n  return (\n    <TreeView\n      aria-label=\"Project files\"\n      defaultExpandedKeys={[\"src\", \"components\"]}\n      defaultSelectedKeys={[\"components\"]}\n      className=\"max-w-sm\"\n    >\n      <TreeViewItem id=\"src\" label=\"src\">\n        <TreeViewItem id=\"components\" label=\"components\">\n          <TreeViewItem id=\"button\" label=\"button.tsx\" iconClassName=\"text-accent-700\" />\n          <TreeViewItem id=\"button-styles\" label=\"button.module.css\" iconClassName=\"text-chart-5-active\" />\n          <TreeViewItem id=\"input\" label=\"input.tsx\" iconClassName=\"text-accent-700\" />\n        </TreeViewItem>\n        <TreeViewItem id=\"hooks\" label=\"hooks\">\n          <TreeViewItem id=\"use-theme\" label=\"use-theme.ts\" iconClassName=\"text-accent-700\" />\n          <TreeViewItem id=\"use-media-query\" label=\"use-media-query.ts\" iconClassName=\"text-accent-700\" />\n        </TreeViewItem>\n        <TreeViewItem id=\"page\" label=\"page.tsx\" iconClassName=\"text-accent-700\" />\n      </TreeViewItem>\n      <TreeViewItem id=\"public\" label=\"public\">\n        <TreeViewItem id=\"logo\" label=\"logo.svg\" iconClassName=\"text-chart-5-active\" />\n        <TreeViewItem id=\"favicon\" label=\"favicon.ico\" />\n      </TreeViewItem>\n      <TreeViewItem id=\"readme\" label=\"README.md\" iconClassName=\"text-chart-1-active\" />\n      <TreeViewItem id=\"package\" label=\"package.json\" />\n      <TreeViewItem id=\"tsconfig\" label=\"tsconfig.json\" />\n    </TreeView>\n  );\n}",
    "snippets": [
      {
        "label": "controlled",
        "code": "import { useState } from \"react\";\nimport type { Key, Selection } from \"react-aria-components\";\nimport { TreeView, TreeViewCollection, TreeViewItem } from \"@/components/base/tree-view/tree-view\";\n\ninterface FileNode {\n  id: string;\n  name: string;\n  children?: FileNode[];\n}\n\nconst files: FileNode[] = [\n  { id: \"design\", name: \"Design\", children: [\n    { id: \"logo\", name: \"Logo.svg\" },\n    { id: \"colors\", name: \"Colors.fig\" },\n  ] },\n  { id: \"notes\", name: \"Project notes.md\" },\n];\n\nfunction renderFile(item: FileNode) {\n  return (\n    <TreeViewItem id={item.id} label={item.name}>\n      <TreeViewCollection items={item.children ?? []}>{renderFile}</TreeViewCollection>\n    </TreeViewItem>\n  );\n}\n\nexport function Example() {\n  const [expandedKeys, setExpandedKeys] = useState<Set<Key>>(new Set([\"design\"]));\n  const [selectedKeys, setSelectedKeys] = useState<Selection>(new Set([\"logo\"]));\n\n  return (\n    <TreeView\n      aria-label=\"Workspace files\"\n      items={files}\n      expandedKeys={expandedKeys}\n      onExpandedChange={setExpandedKeys}\n      selectedKeys={selectedKeys}\n      onSelectionChange={setSelectedKeys}\n    >\n      {renderFile}\n    </TreeView>\n  );\n}"
      },
      {
        "label": "multiple",
        "code": "<TreeView\n  aria-label=\"Documents to share\"\n  selectionMode=\"multiple\"\n  defaultExpandedKeys={[\"documents\"]}\n  defaultSelectedKeys={[\"overview\", \"guidelines\"]}\n>\n  <TreeViewItem id=\"documents\" label=\"Documents\" trailingContent=\"3 files\">\n    <TreeViewItem id=\"overview\" label=\"Overview.md\" />\n    <TreeViewItem id=\"guidelines\" label=\"Guidelines.md\" />\n    <TreeViewItem id=\"changelog\" label=\"Changelog.md\" />\n  </TreeViewItem>\n</TreeView>"
      },
      {
        "label": "states",
        "code": "import { RiFolder3Line } from \"@remixicon/react\";\n\n<TreeView aria-label=\"Repository files\" size=\"sm\" showGuides={false}>\n  <TreeViewItem id=\"index\" label=\"index.tsx\" />\n  <TreeViewItem id=\"private\" label=\"Private files\" isDisabled trailingContent=\"Restricted\" />\n  <TreeViewItem id=\"archive\" label=\"Archive\" icon={RiFolder3Line} trailingContent=\"Empty\" />\n</TreeView>\n\n<TreeView aria-label=\"Search results\" renderEmptyState={() => \"No matching files.\"}>\n  {[]}\n</TreeView>"
      },
      {
        "label": "rtl",
        "code": "import { DirectionProvider } from \"@/components/foundations/direction/direction\";\nimport { TreeView, TreeViewItem } from \"@/components/base/tree-view/tree-view\";\n\n<DirectionProvider locale=\"ar\">\n  <TreeView aria-label=\"ملفات المشروع\" defaultExpandedKeys={[\"project\"]}>\n    <TreeViewItem id=\"project\" label=\"المشروع\">\n      <TreeViewItem id=\"design\" label=\"التصميم\">\n        <TreeViewItem id=\"logo\" label=\"الشعار.svg\" />\n      </TreeViewItem>\n      <TreeViewItem id=\"notes\" label=\"الملاحظات.md\" />\n    </TreeViewItem>\n  </TreeView>\n</DirectionProvider>"
      }
    ]
  }
}
