{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree",
  "type": "registry:ui",
  "title": "Tree",
  "description": "Accessible, keyboard-first tree view with async children, typeahead and multi-select. Zero runtime dependencies.",
  "dependencies": [],
  "registryDependencies": [],
  "categories": [
    "tree",
    "file-tree",
    "navigation",
    "accessibility"
  ],
  "files": [
    {
      "path": "src/registry/tree/tree.tsx",
      "target": "@components/tree/tree.tsx",
      "type": "registry:ui",
      "content": "import * as React from \"react\"\n\nimport { DEFAULT_MESSAGES, useTree, type TreeController } from \"./use-tree.js\"\nimport type { FlatNode, SelectionMode, TreeNode, TreeMessages, TreeRenderContext } from \"./types.js\"\n\nexport type { FlatNode, SelectionMode, TreeNode, TreeMessages, TreeRenderContext }\n\nexport interface TreeProps {\n  /** Root nodes. Each node needs a stable and unique `id`. */\n  data: TreeNode[]\n  /** Accessible name for the tree. Required so every tree is announced. */\n  \"aria-label\": string\n  selectionMode?: SelectionMode\n  /** Case-insensitive substring filter over labels / `searchText`. View-only. */\n  filter?: string\n  /** Fixed height in pixels. Enables windowing for very large trees. */\n  height?: number\n  /** Extra rows rendered above and below the viewport. Defaults to `6`. */\n  overscan?: number\n  expandedIds?: string[]\n  defaultExpandedIds?: string[]\n  onExpandedChange?: (ids: string[]) => void\n  selectedIds?: string[]\n  defaultSelectedIds?: string[]\n  onSelectionChange?: (ids: string[]) => void\n  loadChildren?: (node: TreeNode) => Promise<TreeNode[]>\n  onLoadError?: (node: TreeNode, error: unknown) => void\n  renderIcon?: (node: TreeNode, ctx: TreeRenderContext) => React.ReactNode\n  renderActions?: (node: TreeNode, ctx: TreeRenderContext) => React.ReactNode\n  renderEmpty?: () => React.ReactNode\n  /** Indentation in pixels per level. Defaults to `16`. */\n  indent?: number\n  messages?: Partial<TreeMessages>\n  className?: string\n  itemClassName?: string\n}\n\n/** Rows are `h-8` (32px); windowing needs a fixed height. */\nconst ROW_HEIGHT = 32\n\nfunction cx(...values: Array<string | false | null | undefined>): string {\n  return values.filter(Boolean).join(\" \")\n}\n\nfunction highlight(label: React.ReactNode, query: string): React.ReactNode {\n  if (!query || typeof label !== \"string\") return label\n  const index = label.toLowerCase().indexOf(query)\n  if (index < 0) return label\n  return (\n    <>\n      {label.slice(0, index)}\n      <mark className=\"rounded-sm bg-brand/25 px-0.5 text-foreground\">\n        {label.slice(index, index + query.length)}\n      </mark>\n      {label.slice(index + query.length)}\n    </>\n  )\n}\n\ninterface TreeRowProps {\n  item: FlatNode\n  expanded: boolean\n  selected: boolean\n  focused: boolean\n  loading: boolean\n  error: boolean\n  selectionMode: SelectionMode\n  indent: number\n  messages: TreeMessages\n  query: string\n  itemClassName?: string\n  registerRow: (id: string, element: HTMLDivElement | null) => void\n  onToggle: (node: TreeNode) => void\n  onRetry: (node: TreeNode) => void\n  onClick: (event: React.MouseEvent<HTMLDivElement>, node: TreeNode) => void\n  onDoubleClick: (node: TreeNode) => void\n  renderIcon?: TreeProps[\"renderIcon\"]\n  renderActions?: TreeProps[\"renderActions\"]\n}\n\nfunction TreeRow({\n  item,\n  expanded,\n  selected,\n  focused,\n  loading,\n  error,\n  selectionMode,\n  indent,\n  messages,\n  query,\n  itemClassName,\n  registerRow,\n  onToggle,\n  onRetry,\n  onClick,\n  onDoubleClick,\n  renderIcon,\n  renderActions,\n}: TreeRowProps) {\n  const { node } = item\n  const context: TreeRenderContext = {\n    level: item.level,\n    isExpanded: expanded,\n    isSelected: selected,\n    isFocused: focused,\n  }\n  const icon = node.icon ?? renderIcon?.(node, context)\n\n  return (\n    // Keyboard interaction is implemented once, on the tree container, using a\n    // roving tabindex. Rows only need pointer handlers.\n    // eslint-disable-next-line jsx-a11y/click-events-have-key-events\n    <div\n      role=\"treeitem\"\n      data-tree-row={node.id}\n      data-state={selected ? \"selected\" : expanded && item.hasChildren ? \"open\" : \"closed\"}\n      ref={(element) => registerRow(node.id, element)}\n      aria-level={item.level + 1}\n      aria-posinset={item.posinset}\n      aria-setsize={item.setsize}\n      aria-label={typeof node.label === \"string\" ? node.label : undefined}\n      aria-expanded={item.hasChildren ? expanded : undefined}\n      aria-selected={selectionMode === \"none\" ? undefined : selected}\n      aria-disabled={node.disabled || undefined}\n      aria-busy={loading || undefined}\n      tabIndex={focused ? 0 : -1}\n      className={cx(\n        \"group/tree-row flex h-8 w-full items-center gap-1.5 rounded-md pe-2 text-start text-sm outline-none\",\n        \"hover:bg-accent/60 motion-safe:transition-colors\",\n        focused && \"ring-1 ring-ring/50 ring-inset\",\n        selected && \"bg-accent text-accent-foreground\",\n        node.disabled && \"pointer-events-none opacity-50\",\n        itemClassName,\n      )}\n      style={{ paddingInlineStart: `${6 + item.level * indent}px` }}\n      onClick={(event) => onClick(event, node)}\n      onDoubleClick={() => onDoubleClick(node)}\n    >\n      {item.hasChildren ? (\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label={expanded ? messages.collapse : messages.expand}\n          className=\"flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground\"\n          onClick={(event) => {\n            event.stopPropagation()\n            onToggle(node)\n          }}\n          onDoubleClick={(event) => event.stopPropagation()}\n        >\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            aria-hidden=\"true\"\n            className={cx(\"size-3.5 motion-safe:transition-transform\", expanded && \"rotate-90\")}\n          >\n            <path\n              d=\"M9 6l6 6-6 6\"\n              stroke=\"currentColor\"\n              strokeWidth=\"2\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n            />\n          </svg>\n        </button>\n      ) : (\n        <span aria-hidden=\"true\" className=\"size-4 shrink-0\" />\n      )}\n\n      {icon ? <span className=\"flex shrink-0 items-center text-muted-foreground\">{icon}</span> : null}\n\n      <span className=\"min-w-0 flex-1 truncate\">{highlight(node.label, query)}</span>\n\n      {loading ? (\n        <svg\n          viewBox=\"0 0 24 24\"\n          fill=\"none\"\n          aria-hidden=\"true\"\n          className=\"size-3.5 shrink-0 animate-spin text-muted-foreground\"\n        >\n          <circle cx=\"12\" cy=\"12\" r=\"9\" stroke=\"currentColor\" strokeOpacity=\"0.25\" strokeWidth=\"3\" />\n          <path d=\"M21 12a9 9 0 0 0-9-9\" stroke=\"currentColor\" strokeWidth=\"3\" strokeLinecap=\"round\" />\n        </svg>\n      ) : null}\n\n      {error && !loading ? (\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          className=\"shrink-0 rounded-sm bg-destructive/10 px-1.5 py-0.5 text-xs text-destructive hover:bg-destructive/20\"\n          onClick={(event) => {\n            event.stopPropagation()\n            onRetry(node)\n          }}\n        >\n          {messages.retry}\n        </button>\n      ) : null}\n\n      {renderActions?.(node, context)}\n    </div>\n  )\n}\n\n/**\n * Accessible tree view with roving tabindex, typeahead, multi-select, filtering,\n * async children and windowed rendering for large trees. Styling uses shadcn/ui\n * CSS variables, so it inherits your theme.\n */\nexport function Tree({\n  data,\n  \"aria-label\": ariaLabel,\n  selectionMode = \"single\",\n  filter,\n  height,\n  overscan = 6,\n  expandedIds,\n  defaultExpandedIds,\n  onExpandedChange,\n  selectedIds,\n  defaultSelectedIds,\n  onSelectionChange,\n  loadChildren,\n  onLoadError,\n  renderIcon,\n  renderActions,\n  renderEmpty,\n  indent = 16,\n  messages: messagesProp,\n  className,\n  itemClassName,\n}: TreeProps) {\n  const messages = React.useMemo<TreeMessages>(\n    () => ({ ...DEFAULT_MESSAGES, ...messagesProp }),\n    [messagesProp],\n  )\n\n  const controller: TreeController = useTree({\n    data,\n    selectionMode,\n    messages,\n    filter,\n    expandedIds,\n    defaultExpandedIds,\n    onExpandedChange,\n    selectedIds,\n    defaultSelectedIds,\n    onSelectionChange,\n    loadChildren,\n    onLoadError,\n  })\n\n  const treeRef = React.useRef<HTMLDivElement | null>(null)\n  const scrollRef = React.useRef<HTMLDivElement | null>(null)\n  const rowsRef = React.useRef(new Map<string, HTMLDivElement>())\n  const lastFocusedRef = React.useRef<string | null>(null)\n\n  const virtual = typeof height === \"number\" && height > 0\n  const query = filter?.trim().toLowerCase() ?? \"\"\n  const [scrollTop, setScrollTop] = React.useState(0)\n  const [measuredHeight, setMeasuredHeight] = React.useState(0)\n  const viewport = measuredHeight || (typeof height === \"number\" ? height : 0)\n\n  const registerRow = React.useCallback((id: string, element: HTMLDivElement | null) => {\n    if (element) rowsRef.current.set(id, element)\n    else rowsRef.current.delete(id)\n  }, [])\n\n  // Measure the scroll viewport so windowing does not depend on `height` alone.\n  React.useEffect(() => {\n    const element = scrollRef.current\n    if (!element || !virtual) return\n    const measure = () => setMeasuredHeight(element.clientHeight)\n    measure()\n    if (typeof ResizeObserver === \"undefined\") return\n    const observer = new ResizeObserver(measure)\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [virtual])\n\n  const total = controller.visible.length\n  const windowed = React.useMemo(() => {\n    if (!virtual) return { start: 0, end: total }\n    const start = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - overscan)\n    const end = Math.min(total, Math.ceil((scrollTop + viewport) / ROW_HEIGHT) + overscan)\n    return { start, end }\n  }, [virtual, total, scrollTop, viewport, overscan])\n\n  const rows =\n    windowed.start === 0 && windowed.end === total\n      ? controller.visible\n      : controller.visible.slice(windowed.start, windowed.end)\n\n  // Move DOM focus with the roving tabindex. With windowing on, the target row may\n  // not be mounted yet, so scroll it into the window and retry on the next frame.\n  // Never steal focus from outside the tree.\n  React.useEffect(() => {\n    const id = controller.focusedId\n    if (!id || id === lastFocusedRef.current) return\n    lastFocusedRef.current = id\n\n    const root = treeRef.current\n    const active = document.activeElement\n    const wasInside = active instanceof Node && root?.contains(active) === true\n\n    if (virtual) {\n      const scroll = scrollRef.current\n      const index = controller.visible.findIndex((item) => item.id === id)\n      if (scroll && index >= 0) {\n        const top = index * ROW_HEIGHT\n        const viewportPx = viewport || scroll.clientHeight\n        if (top < scroll.scrollTop || top + ROW_HEIGHT > scroll.scrollTop + viewportPx) {\n          scroll.scrollTop = Math.max(0, top + ROW_HEIGHT - viewportPx)\n          // The window is derived from scroll state; keep the two in sync.\n          setScrollTop(scroll.scrollTop)\n        }\n      }\n    }\n\n    if (!wasInside) return\n\n    const attemptFocus = (tries: number) => {\n      const row = rowsRef.current.get(id)\n      if (row) {\n        row.focus({ preventScroll: true })\n        return\n      }\n      if (tries >= 3) return\n      const schedule =\n        typeof requestAnimationFrame === \"function\"\n          ? requestAnimationFrame\n          : (callback: FrameRequestCallback) => setTimeout(() => callback(0), 0)\n      schedule(() => attemptFocus(tries + 1))\n    }\n\n    attemptFocus(0)\n  }, [controller.focusedId, controller.visible, virtual, viewport])\n\n  const rovingId = controller.focusedId ?? controller.visible[0]?.id ?? null\n  const isEmpty = controller.visible.length === 0\n  const emptyContent = renderEmpty ? renderEmpty() : query ? messages.noMatches : messages.empty\n\n  return (\n    <div className={cx(\"w-full\", className)}>\n      {isEmpty ? (\n        <div className=\"px-2 py-6 text-center text-sm text-muted-foreground\">{emptyContent}</div>\n      ) : (\n        <div\n          ref={scrollRef}\n          data-tree-scroll={virtual ? \"\" : undefined}\n          style={virtual ? { height } : undefined}\n          className={virtual ? \"relative overflow-auto pe-1\" : undefined}\n          onScroll={\n            virtual\n              ? (event) => setScrollTop(event.currentTarget.scrollTop)\n              : undefined\n          }\n        >\n          <div\n            style={\n              virtual\n                ? {\n                    paddingTop: windowed.start * ROW_HEIGHT,\n                    paddingBottom: (total - windowed.end) * ROW_HEIGHT,\n                  }\n                : undefined\n            }\n          >\n            <div\n              ref={treeRef}\n              role=\"tree\"\n              aria-label={ariaLabel}\n              aria-multiselectable={selectionMode === \"multiple\" ? true : undefined}\n              tabIndex={-1}\n              className=\"outline-none\"\n              onKeyDown={controller.handleKeyDown}\n              onFocus={controller.handleFocusIn}\n            >\n              {rows.map((item) => (\n                <TreeRow\n                  key={item.id}\n                  item={item}\n                  expanded={controller.isExpanded(item.id)}\n                  selected={controller.isSelected(item.id)}\n                  focused={controller.focusedId !== null && rovingId === item.id}\n                  loading={controller.loadingIds.has(item.id)}\n                  error={controller.errorIds.has(item.id)}\n                  selectionMode={selectionMode}\n                  indent={indent}\n                  messages={messages}\n                  query={query}\n                  itemClassName={itemClassName}\n                  registerRow={registerRow}\n                  onToggle={controller.toggleExpanded}\n                  onRetry={controller.retryLoad}\n                  onClick={controller.handleRowClick}\n                  onDoubleClick={controller.handleRowDoubleClick}\n                  renderIcon={renderIcon}\n                  renderActions={renderActions}\n                />\n              ))}\n            </div>\n          </div>\n        </div>\n      )}\n\n      <div role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {controller.announcement}\n      </div>\n    </div>\n  )\n}\n"
    },
    {
      "path": "src/registry/tree/use-tree.ts",
      "target": "@components/tree/use-tree.ts",
      "type": "registry:lib",
      "content": "import * as React from \"react\"\n\nimport type { FlatNode, SelectionMode, TreeNode, TreeMessages } from \"./types.js\"\n\nexport const DEFAULT_MESSAGES: TreeMessages = {\n  loading: \"Loading…\",\n  loadFailed: \"Couldn't load children.\",\n  retry: \"Retry\",\n  empty: \"No items\",\n  noMatches: \"No matching items\",\n  expand: \"Expand\",\n  collapse: \"Collapse\",\n}\n\nexport interface UseTreeOptions {\n  data: TreeNode[]\n  selectionMode: SelectionMode\n  messages: TreeMessages\n  filter?: string\n  expandedIds?: string[]\n  defaultExpandedIds?: string[]\n  onExpandedChange?: (ids: string[]) => void\n  selectedIds?: string[]\n  defaultSelectedIds?: string[]\n  onSelectionChange?: (ids: string[]) => void\n  loadChildren?: (node: TreeNode) => Promise<TreeNode[]>\n  onLoadError?: (node: TreeNode, error: unknown) => void\n}\n\nexport interface TreeController {\n  visible: FlatNode[]\n  expandedSet: Set<string>\n  selectedSet: Set<string>\n  focusedId: string | null\n  loadingIds: Set<string>\n  errorIds: Set<string>\n  announcement: string\n  isExpanded: (id: string) => boolean\n  isSelected: (id: string) => boolean\n  toggleExpanded: (node: TreeNode) => void\n  expandSiblings: (node: TreeNode) => void\n  retryLoad: (node: TreeNode) => void\n  handleKeyDown: (event: React.KeyboardEvent<HTMLDivElement>) => void\n  handleFocusIn: (event: React.FocusEvent<HTMLDivElement>) => void\n  handleRowClick: (event: React.MouseEvent<HTMLDivElement>, node: TreeNode) => void\n  handleRowDoubleClick: (node: TreeNode) => void\n}\n\nfunction textOf(node: TreeNode): string {\n  if (node.searchText !== undefined) return node.searchText.toLowerCase()\n  return typeof node.label === \"string\" ? node.label.toLowerCase() : \"\"\n}\n\nfunction containsId(node: TreeNode, id: string, getChildren: (n: TreeNode) => TreeNode[]): boolean {\n  for (const child of getChildren(node)) {\n    if (child.id === id) return true\n    if (containsId(child, id, getChildren)) return true\n  }\n  return false\n}\n\nexport function useTree(options: UseTreeOptions): TreeController {\n  const {\n    data,\n    selectionMode,\n    messages,\n    filter,\n    expandedIds,\n    defaultExpandedIds,\n    onExpandedChange,\n    selectedIds,\n    defaultSelectedIds,\n    onSelectionChange,\n    loadChildren,\n    onLoadError,\n  } = options\n\n  const [expandedInternal, setExpandedInternal] = React.useState<Set<string>>(\n    () => new Set(defaultExpandedIds ?? []),\n  )\n  const [selectedInternal, setSelectedInternal] = React.useState<Set<string>>(\n    () => new Set(defaultSelectedIds ?? []),\n  )\n  const [focusedRaw, setFocusedIdState] = React.useState<string | null>(null)\n  const [asyncChildren, setAsyncChildren] = React.useState<Map<string, TreeNode[]>>(() => new Map())\n  const [loadingIds, setLoadingIds] = React.useState<Set<string>>(() => new Set())\n  const [errorIds, setErrorIds] = React.useState<Set<string>>(() => new Set())\n  const [announcement, setAnnouncement] = React.useState(\"\")\n\n  // All ids that currently exist, including async children.\n  const allIds = React.useMemo(() => {\n    const ids = new Set<string>()\n    const stack = [...data]\n    while (stack.length > 0) {\n      const node = stack.pop()\n      if (!node) continue\n      ids.add(node.id)\n      const children = asyncChildren.get(node.id) ?? node.children\n      if (children) stack.push(...children)\n    }\n    return ids\n  }, [data, asyncChildren])\n\n  // Stale ids are ignored instead of being written back, so removing a node from\n  // `data` never causes an extra render pass.\n  const expandedSet = React.useMemo(() => {\n    const base = expandedIds ? new Set(expandedIds) : expandedInternal\n    const next = new Set<string>()\n    for (const id of base) if (allIds.has(id)) next.add(id)\n    return next\n  }, [expandedIds, expandedInternal, allIds])\n  const selectedSet = React.useMemo(() => {\n    const base = selectedIds ? new Set(selectedIds) : selectedInternal\n    const next = new Set<string>()\n    for (const id of base) if (allIds.has(id)) next.add(id)\n    return next\n  }, [selectedIds, selectedInternal, allIds])\n\n  const inflightRef = React.useRef(new Set<string>())\n  const cancelledRef = React.useRef(false)\n  const typeaheadRef = React.useRef<{ buffer: string; timer: ReturnType<typeof setTimeout> | null }>({\n    buffer: \"\",\n    timer: null,\n  })\n  const anchorRef = React.useRef<string | null>(null)\n  const mountedRef = React.useRef(false)\n  const asyncChildrenRef = React.useRef(asyncChildren)\n  const visibleRef = React.useRef<FlatNode[]>([])\n  const focusedRef = React.useRef<string | null>(null)\n\n  React.useEffect(() => {\n    mountedRef.current = true\n    const typeahead = typeaheadRef.current\n    return () => {\n      mountedRef.current = false\n      cancelledRef.current = true\n      if (typeahead.timer) clearTimeout(typeahead.timer)\n    }\n  }, [])\n\n  React.useEffect(() => {\n    asyncChildrenRef.current = asyncChildren\n  }, [asyncChildren])\n\n  const getChildren = React.useCallback(\n    (node: TreeNode): TreeNode[] => asyncChildren.get(node.id) ?? node.children ?? [],\n    [asyncChildren],\n  )\n\n  const hasChildren = React.useCallback(\n    (node: TreeNode): boolean => {\n      if ((asyncChildren.get(node.id) ?? node.children ?? []).length > 0) return true\n      if (node.children !== undefined) return false\n      return loadChildren !== undefined && !asyncChildren.has(node.id)\n    },\n    [asyncChildren, loadChildren],\n  )\n\n  const filterQuery = filter?.trim().toLowerCase() ?? \"\"\n  /**\n   * Filtering is view-only: it never mutates expansion or selection. Ancestors of\n   * a match are force-expanded so the match is always reachable, and non-matching\n   * branches are dropped from the rendered tree.\n   */\n  const filtered = React.useMemo(() => {\n    if (!filterQuery) return null\n    const matchedIds = new Set<string>()\n    const autoExpanded = new Set<string>()\n    const build = (nodes: TreeNode[]): TreeNode[] => {\n      const out: TreeNode[] = []\n      for (const node of nodes) {\n        const own = textOf(node).includes(filterQuery)\n        const children = build(getChildren(node))\n        if (own) matchedIds.add(node.id)\n        if (!own && children.length === 0) continue\n        autoExpanded.add(node.id)\n        out.push({ ...node, children })\n      }\n      return out\n    }\n    return { nodes: build(data), matchedIds, autoExpanded }\n  }, [data, filterQuery, getChildren])\n\n  const expandedEffective = React.useMemo(\n    () => (filtered ? new Set([...expandedSet, ...filtered.autoExpanded]) : expandedSet),\n    [expandedSet, filtered],\n  )\n\n  const visible = React.useMemo(() => {\n    const roots = filtered ? filtered.nodes : data\n    const childrenOf = filtered ? (node: TreeNode) => node.children ?? [] : getChildren\n    const canExpand = filtered ? (node: TreeNode) => childrenOf(node).length > 0 : hasChildren\n    const out: FlatNode[] = []\n    const stack: { nodes: TreeNode[]; index: number; level: number; parentId: string | null }[] = [\n      { nodes: roots, index: 0, level: 0, parentId: null },\n    ]\n    while (stack.length > 0) {\n      const frame = stack[stack.length - 1]\n      if (!frame) break\n      if (frame.index >= frame.nodes.length) {\n        stack.pop()\n        continue\n      }\n      const node = frame.nodes[frame.index]\n      frame.index += 1\n      if (!node) continue\n      const canExpandNode = canExpand(node)\n      out.push({\n        id: node.id,\n        node,\n        level: frame.level,\n        parentId: frame.parentId,\n        posinset: frame.index,\n        setsize: frame.nodes.length,\n        hasChildren: canExpandNode,\n      })\n      if (canExpandNode && expandedEffective.has(node.id)) {\n        stack.push({\n          nodes: childrenOf(node),\n          index: 0,\n          level: frame.level + 1,\n          parentId: node.id,\n        })\n      }\n    }\n    return out\n  }, [data, expandedEffective, filtered, getChildren, hasChildren])\n\n  // Focus falls back to `null` (and therefore to the first row) when the focused\n  // node disappears.\n  const focusedId =\n    focusedRaw !== null && visible.some((item) => item.id === focusedRaw) ? focusedRaw : null\n\n  React.useEffect(() => {\n    visibleRef.current = visible\n    focusedRef.current = focusedId\n  })\n\n  // Warn once when the component switches between controlled and uncontrolled.\n  const controlledRef = React.useRef({\n    expanded: expandedIds !== undefined,\n    selected: selectedIds !== undefined,\n  })\n  React.useEffect(() => {\n    const next = { expanded: expandedIds !== undefined, selected: selectedIds !== undefined }\n    const prev = controlledRef.current\n    if (prev.expanded !== next.expanded) {\n      console.warn(\"[tree-ui] Tree switched between controlled and uncontrolled `expandedIds`.\")\n    }\n    if (prev.selected !== next.selected) {\n      console.warn(\"[tree-ui] Tree switched between controlled and uncontrolled `selectedIds`.\")\n    }\n    controlledRef.current = next\n  }, [expandedIds, selectedIds])\n\n  // Warn once about duplicate ids.\n  React.useEffect(() => {\n    const seen = new Set<string>()\n    const duplicates = new Set<string>()\n    const stack = [...data]\n    while (stack.length > 0) {\n      const node = stack.pop()\n      if (!node) continue\n      if (seen.has(node.id)) duplicates.add(node.id)\n      seen.add(node.id)\n      if (node.children) stack.push(...node.children)\n    }\n    if (duplicates.size > 0) {\n      console.warn(`[tree-ui] Duplicate node ids detected: ${[...duplicates].join(\", \")}`)\n    }\n  }, [data])\n\n  const commitExpanded = React.useCallback(\n    (next: Set<string>) => {\n      if (expandedIds === undefined) setExpandedInternal(next)\n      onExpandedChange?.([...next])\n    },\n    [expandedIds, onExpandedChange],\n  )\n\n  const commitSelected = React.useCallback(\n    (next: Set<string>) => {\n      if (selectedIds === undefined) setSelectedInternal(next)\n      onSelectionChange?.([...next])\n    },\n    [selectedIds, onSelectionChange],\n  )\n\n  const ensureChildren = React.useCallback(\n    (node: TreeNode) => {\n      if (!loadChildren) return\n      if (node.children !== undefined) return\n      if (asyncChildrenRef.current.has(node.id) || inflightRef.current.has(node.id)) return\n      inflightRef.current.add(node.id)\n      setLoadingIds((prev) => new Set(prev).add(node.id))\n      setErrorIds((prev) => {\n        if (!prev.has(node.id)) return prev\n        const next = new Set(prev)\n        next.delete(node.id)\n        return next\n      })\n      void loadChildren(node)\n        .then((children) => {\n          inflightRef.current.delete(node.id)\n          if (cancelledRef.current || !mountedRef.current) return\n          setAsyncChildren((prev) => {\n            const next = new Map(prev)\n            next.set(node.id, children)\n            return next\n          })\n          setLoadingIds((prev) => {\n            const copy = new Set(prev)\n            copy.delete(node.id)\n            return copy\n          })\n        })\n        .catch((error: unknown) => {\n          inflightRef.current.delete(node.id)\n          if (cancelledRef.current || !mountedRef.current) return\n          setLoadingIds((prev) => {\n            const copy = new Set(prev)\n            copy.delete(node.id)\n            return copy\n          })\n          setErrorIds((prev) => new Set(prev).add(node.id))\n          setAnnouncement(`${messages.loadFailed} ${messages.retry}.`)\n          onLoadError?.(node, error)\n        })\n    },\n    [loadChildren, messages.loadFailed, messages.retry, onLoadError],\n  )\n\n  const toggleExpanded = React.useCallback(\n    (node: TreeNode) => {\n      if (node.disabled) return\n      const expanded = expandedSet.has(node.id)\n      const next = new Set(expandedSet)\n      if (expanded) {\n        next.delete(node.id)\n        const focused = focusedRef.current\n        if (focused !== null && focused !== node.id && containsId(node, focused, getChildren)) {\n          setFocusedIdState(node.id)\n        }\n      } else {\n        next.add(node.id)\n      }\n      commitExpanded(next)\n      if (!expanded) ensureChildren(node)\n    },\n    [expandedSet, commitExpanded, ensureChildren, getChildren],\n  )\n\n  const expandSiblings = React.useCallback(\n    (node: TreeNode) => {\n      const item = visibleRef.current.find((entry) => entry.id === node.id)\n      if (!item) return\n      const next = new Set(expandedSet)\n      for (const sibling of visibleRef.current) {\n        if (sibling.level === item.level && sibling.parentId === item.parentId && sibling.hasChildren) {\n          if (!next.has(sibling.id)) {\n            next.add(sibling.id)\n            ensureChildren(sibling.node)\n          }\n        }\n      }\n      commitExpanded(next)\n    },\n    [expandedSet, commitExpanded, ensureChildren],\n  )\n\n  const retryLoad = React.useCallback(\n    (node: TreeNode) => {\n      if (!loadChildren) return\n      ensureChildren(node)\n    },\n    [ensureChildren, loadChildren],\n  )\n\n  const selectOnly = React.useCallback(\n    (node: TreeNode) => {\n      if (selectionMode === \"none\" || node.disabled) return\n      anchorRef.current = node.id\n      commitSelected(new Set([node.id]))\n    },\n    [commitSelected, selectionMode],\n  )\n\n  const toggleSelection = React.useCallback(\n    (node: TreeNode) => {\n      if (selectionMode !== \"multiple\" || node.disabled) return\n      const next = new Set(selectedSet)\n      if (next.has(node.id)) next.delete(node.id)\n      else next.add(node.id)\n      anchorRef.current = node.id\n      commitSelected(next)\n    },\n    [commitSelected, selectedSet, selectionMode],\n  )\n\n  const selectRange = React.useCallback(\n    (node: TreeNode) => {\n      if (selectionMode !== \"multiple\" || node.disabled) return\n      const anchor = anchorRef.current\n      const list = visibleRef.current\n      const from = anchor ? list.findIndex((entry) => entry.id === anchor) : -1\n      const to = list.findIndex((entry) => entry.id === node.id)\n      if (from < 0 || to < 0) {\n        selectOnly(node)\n        return\n      }\n      const start = Math.min(from, to)\n      const end = Math.max(from, to)\n      const next = new Set(selectedSet)\n      for (let index = start; index <= end; index += 1) {\n        const entry = list[index]\n        if (entry && !entry.node.disabled) next.add(entry.id)\n      }\n      anchorRef.current = node.id\n      commitSelected(next)\n    },\n    [commitSelected, selectedSet, selectOnly, selectionMode],\n  )\n\n  const isExpanded = React.useCallback((id: string) => expandedEffective.has(id), [expandedEffective])\n  const isSelected = React.useCallback((id: string) => selectedSet.has(id), [selectedSet])\n\n  const handleRowClick = React.useCallback(\n    (event: React.MouseEvent<HTMLDivElement>, node: TreeNode) => {\n      setFocusedIdState(node.id)\n      if (node.disabled) return\n      if (event.shiftKey && selectionMode === \"multiple\") {\n        event.preventDefault()\n        selectRange(node)\n        return\n      }\n      if ((event.metaKey || event.ctrlKey) && selectionMode === \"multiple\") {\n        toggleSelection(node)\n        return\n      }\n      selectOnly(node)\n    },\n    [selectOnly, selectRange, selectionMode, toggleSelection],\n  )\n\n  const handleRowDoubleClick = React.useCallback(\n    (node: TreeNode) => {\n      if (node.disabled) return\n      if (!hasChildren(node)) return\n      toggleExpanded(node)\n    },\n    [hasChildren, toggleExpanded],\n  )\n\n  const handleFocusIn = React.useCallback((event: React.FocusEvent<HTMLDivElement>) => {\n    const target = event.target as HTMLElement | null\n    const row = target?.closest<HTMLElement>(\"[data-tree-row]\")\n    const id = row?.dataset.treeRow\n    if (id) setFocusedIdState(id)\n  }, [])\n\n  const handleKeyDown = React.useCallback(\n    (event: React.KeyboardEvent<HTMLDivElement>) => {\n      if (event.defaultPrevented) return\n      const list = visibleRef.current\n      if (list.length === 0) return\n      const currentIndex = focusedRef.current ? list.findIndex((item) => item.id === focusedRef.current) : -1\n      const current = currentIndex >= 0 ? list[currentIndex] : undefined\n\n      const moveTo = (index: number) => {\n        const target = list[index]\n        if (target) setFocusedIdState(target.id)\n      }\n\n      switch (event.key) {\n        case \"ArrowDown\":\n          event.preventDefault()\n          moveTo(currentIndex < 0 ? 0 : currentIndex + 1)\n          return\n        case \"ArrowUp\":\n          event.preventDefault()\n          moveTo(currentIndex < 0 ? 0 : currentIndex - 1)\n          return\n        case \"Home\":\n          event.preventDefault()\n          moveTo(0)\n          return\n        case \"End\":\n          event.preventDefault()\n          moveTo(list.length - 1)\n          return\n        case \"ArrowRight\": {\n          if (!current) return\n          event.preventDefault()\n          if (current.hasChildren && !expandedSet.has(current.id)) {\n            toggleExpanded(current.node)\n          } else if (current.hasChildren) {\n            const next = list[currentIndex + 1]\n            if (next && next.level > current.level) setFocusedIdState(next.id)\n          }\n          return\n        }\n        case \"ArrowLeft\": {\n          if (!current) return\n          event.preventDefault()\n          if (current.hasChildren && expandedSet.has(current.id)) {\n            toggleExpanded(current.node)\n          } else if (current.parentId) {\n            setFocusedIdState(current.parentId)\n          }\n          return\n        }\n        case \"Enter\":\n        case \" \": {\n          if (!current) return\n          event.preventDefault()\n          if (errorIds.has(current.id)) {\n            retryLoad(current.node)\n            return\n          }\n          if (selectionMode === \"none\") {\n            if (current.hasChildren) toggleExpanded(current.node)\n            return\n          }\n          selectOnly(current.node)\n          return\n        }\n        case \"*\": {\n          if (!current) return\n          event.preventDefault()\n          expandSiblings(current.node)\n          return\n        }\n        default:\n          break\n      }\n\n      const isPrintable =\n        event.key.length === 1 &&\n        !event.metaKey &&\n        !event.ctrlKey &&\n        !event.altKey &&\n        !/^\\s$/.test(event.key)\n      if (!isPrintable) return\n\n      const typeahead = typeaheadRef.current\n      typeahead.buffer += event.key.toLowerCase()\n      if (typeahead.timer) clearTimeout(typeahead.timer)\n      typeahead.timer = setTimeout(() => {\n        typeahead.buffer = \"\"\n        typeahead.timer = null\n      }, 600)\n\n      const buffer = typeahead.buffer\n      const total = list.length\n      for (let offset = 1; offset <= total; offset += 1) {\n        const entry = list[(currentIndex + offset) % total]\n        if (!entry || entry.node.disabled) continue\n        if (textOf(entry.node).startsWith(buffer)) {\n          event.preventDefault()\n          setFocusedIdState(entry.id)\n          return\n        }\n      }\n    },\n    [errorIds, expandedSet, expandSiblings, retryLoad, selectOnly, selectionMode, toggleExpanded],\n  )\n\n  return {\n    visible,\n    expandedSet,\n    selectedSet,\n    focusedId,\n    loadingIds,\n    errorIds,\n    announcement,\n    isExpanded,\n    isSelected,\n    toggleExpanded,\n    expandSiblings,\n    retryLoad,\n    handleKeyDown,\n    handleFocusIn,\n    handleRowClick,\n    handleRowDoubleClick,\n  }\n}\n"
    },
    {
      "path": "src/registry/tree/types.ts",
      "target": "@components/tree/types.ts",
      "type": "registry:lib",
      "content": "import type { ReactNode } from \"react\"\n\n/**\n * A single node in the tree.\n *\n * `children` is optional. When omitted and `loadChildren` is provided the node\n * becomes an async node: children are fetched the first time it is expanded.\n */\nexport interface TreeNode {\n  /** Stable, unique identifier. Used for expansion, selection and focus. */\n  id: string\n  /** Visible label. String labels also power typeahead. */\n  label: ReactNode\n  children?: TreeNode[]\n  disabled?: boolean\n  icon?: ReactNode\n  /** Plain text used for typeahead when `label` is not a string. */\n  searchText?: string\n  /** Arbitrary payload, passed back through render slots. */\n  data?: unknown\n}\n\nexport type SelectionMode = \"none\" | \"single\" | \"multiple\"\n\n/** A node flattened into the currently visible order. */\nexport interface FlatNode {\n  id: string\n  node: TreeNode\n  /** 0-based depth. */\n  level: number\n  parentId: string | null\n  /** 1-based position among its siblings. */\n  posinset: number\n  /** Number of siblings, including this node. */\n  setsize: number\n  hasChildren: boolean\n}\n\n/** Context passed to the `renderIcon` / `renderActions` slots. */\nexport interface TreeRenderContext {\n  level: number\n  isExpanded: boolean\n  isSelected: boolean\n  isFocused: boolean\n}\n\n/** Copy used by the built-in loading, retry and empty affordances. */\nexport interface TreeMessages {\n  loading: string\n  loadFailed: string\n  retry: string\n  empty: string\n  noMatches: string\n  expand: string\n  collapse: string\n}\n"
    }
  ]
}
