{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "type": "registry:component",
  "title": "Tree View",
  "description": "Generic, accessible, keyboard-navigable controlled tree for nested M8 plugin data (e.g. category trees). No data fetching, no business types.",
  "dependencies": [
    "lucide-react"
  ],
  "files": [
    {
      "path": "registry/blocks/tree/tree-view.tsx",
      "content": "\"use client\";\n// astro-ui-m8-skin-version: 1.5.3 (A-C6 — run `npx astro-ui-m8-skin-lock` to compare against your installed @mano8/astro-ui-m8)\n\nimport * as React from \"react\";\nimport { ChevronRight } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface TreeViewNode {\n  id: string;\n  label: string;\n  children?: TreeViewNode[];\n  count?: number;\n  icon?: React.ReactNode;\n}\n\nexport interface TreeViewLabels {\n  empty: string;\n  expand: (node: TreeViewNode) => string;\n  collapse: (node: TreeViewNode) => string;\n}\n\nconst DEFAULT_LABELS: TreeViewLabels = {\n  empty: \"No items.\",\n  expand: (node) => `Expand ${node.label}`,\n  collapse: (node) => `Collapse ${node.label}`,\n};\n\nexport interface TreeViewNodeContext {\n  node: TreeViewNode;\n  level: number;\n  expanded: boolean;\n  selected: boolean;\n  hasChildren: boolean;\n  toggle: () => void;\n  select: () => void;\n}\n\nexport interface TreeViewProps {\n  nodes: TreeViewNode[];\n  selectedId?: string | null;\n  onSelect?: (node: TreeViewNode) => void;\n  expandedIds?: string[];\n  defaultExpandedIds?: string[];\n  onExpandedChange?: (expandedIds: string[]) => void;\n  renderNode?: (context: TreeViewNodeContext) => React.ReactNode;\n  nodeAttributes?: (node: TreeViewNode) => React.LiHTMLAttributes<HTMLLIElement>;\n  labels?: Partial<TreeViewLabels>;\n  empty?: React.ReactNode;\n  className?: string;\n  \"aria-label\"?: string;\n  \"aria-labelledby\"?: string;\n}\n\n/** One entry of the depth-first list of currently visible nodes. */\ninterface TreeViewFlatNode {\n  node: TreeViewNode;\n  level: number;\n  parentId: string | null;\n  hasChildren: boolean;\n  expanded: boolean;\n}\n\nfunction flattenVisibleNodes(\n  nodes: TreeViewNode[],\n  expanded: ReadonlySet<string>,\n  level: number,\n  parentId: string | null,\n  out: TreeViewFlatNode[],\n): TreeViewFlatNode[] {\n  for (const node of nodes) {\n    const children = node.children ?? [];\n    const hasChildren = children.length > 0;\n    const isExpanded = hasChildren && expanded.has(node.id);\n    out.push({ node, level, parentId, hasChildren, expanded: isExpanded });\n    if (isExpanded) {\n      flattenVisibleNodes(children, expanded, level + 1, node.id, out);\n    }\n  }\n  return out;\n}\n\ninterface TreeViewItemsProps {\n  nodes: TreeViewNode[];\n  level: number;\n  idPrefix: string;\n  selectedId?: string | null;\n  activeId: string | null;\n  expanded: ReadonlySet<string>;\n  onToggle: (node: TreeViewNode) => void;\n  onSelect?: (node: TreeViewNode) => void;\n  onItemKeyDown: (event: React.KeyboardEvent<HTMLLIElement>, node: TreeViewNode) => void;\n  onItemFocus: (event: React.FocusEvent<HTMLLIElement>, node: TreeViewNode) => void;\n  onItemPointerDown: (node: TreeViewNode) => void;\n  registerItem: (id: string, element: HTMLLIElement | null) => void;\n  renderNode?: (context: TreeViewNodeContext) => React.ReactNode;\n  nodeAttributes?: (node: TreeViewNode) => React.LiHTMLAttributes<HTMLLIElement>;\n  labels: TreeViewLabels;\n}\n\nfunction TreeViewItems({\n  nodes,\n  level,\n  idPrefix,\n  selectedId,\n  activeId,\n  expanded,\n  onToggle,\n  onSelect,\n  onItemKeyDown,\n  onItemFocus,\n  onItemPointerDown,\n  registerItem,\n  renderNode,\n  nodeAttributes,\n  labels,\n}: TreeViewItemsProps) {\n  const items = nodes.map((node, index) => {\n    const children = node.children ?? [];\n    const hasChildren = children.length > 0;\n    const isExpanded = hasChildren && expanded.has(node.id);\n    const isSelected = selectedId === node.id;\n    const itemId = `${idPrefix}-${index}`;\n    const labelId = `${itemId}-label`;\n    const countId = `${itemId}-count`;\n    const toggle = () => onToggle(node);\n    const select = () => onSelect?.(node);\n    const context: TreeViewNodeContext = {\n      node,\n      level,\n      expanded: isExpanded,\n      selected: isSelected,\n      hasChildren,\n      toggle,\n      select,\n    };\n\n    // The treeitem is named explicitly so the nested role=\"group\" never leaks\n    // into name-from-content. A custom renderNode owns its own markup, so the\n    // node label is the fallback name there.\n    const labelledBy = node.count === undefined ? labelId : `${labelId} ${countId}`;\n\n    return (\n      <li\n        key={node.id}\n        ref={(element) => {\n          registerItem(node.id, element);\n        }}\n        role=\"treeitem\"\n        tabIndex={activeId === node.id ? 0 : -1}\n        aria-level={level}\n        aria-selected={isSelected}\n        aria-expanded={hasChildren ? isExpanded : undefined}\n        aria-label={renderNode ? node.label : undefined}\n        aria-labelledby={renderNode ? undefined : labelledBy}\n        data-tree-view-node={node.id}\n        data-state={isSelected ? \"selected\" : undefined}\n        className=\"rounded-sm outline-none\"\n        onKeyDown={(event) => onItemKeyDown(event, node)}\n        onFocus={(event) => onItemFocus(event, node)}\n        {...nodeAttributes?.(node)}\n      >\n        <div\n          data-tree-view-select={renderNode ? undefined : node.id}\n          className={cn(\n            \"flex items-center gap-1 rounded-sm [li:focus-visible>&]:ring-2 [li:focus-visible>&]:ring-ring\",\n            isSelected && \"bg-accent text-accent-foreground\",\n          )}\n          onPointerDown={() => onItemPointerDown(node)}\n          onClick={renderNode ? undefined : select}\n        >\n          {hasChildren ? (\n            <span\n              aria-hidden=\"true\"\n              title={isExpanded ? labels.collapse(node) : labels.expand(node)}\n              data-tree-view-toggle={node.id}\n              data-expanded={isExpanded}\n              className=\"flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground\"\n              onClick={(event) => {\n                event.stopPropagation();\n                toggle();\n              }}\n            >\n              <ChevronRight\n                className={cn(\"size-4 transition-transform\", isExpanded && \"rotate-90\")}\n              />\n            </span>\n          ) : (\n            <span aria-hidden=\"true\" className=\"size-5 shrink-0\" />\n          )}\n          {renderNode ? (\n            renderNode(context)\n          ) : (\n            <span\n              className={cn(\n                \"flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-foreground\",\n                isSelected && \"font-medium\",\n              )}\n            >\n              {node.icon ?? null}\n              <span id={labelId} className=\"truncate\">\n                {node.label}\n              </span>\n              {node.count === undefined ? null : (\n                <span\n                  id={countId}\n                  data-tree-view-count={node.id}\n                  className=\"ml-auto shrink-0 text-xs text-muted-foreground tabular-nums\"\n                >\n                  {node.count}\n                </span>\n              )}\n            </span>\n          )}\n        </div>\n        {hasChildren && isExpanded ? (\n          <ul role=\"group\" className=\"ml-3 flex flex-col gap-0.5 border-l pl-2\">\n            <TreeViewItems\n              nodes={children}\n              level={level + 1}\n              idPrefix={itemId}\n              selectedId={selectedId}\n              activeId={activeId}\n              expanded={expanded}\n              onToggle={onToggle}\n              onSelect={onSelect}\n              onItemKeyDown={onItemKeyDown}\n              onItemFocus={onItemFocus}\n              onItemPointerDown={onItemPointerDown}\n              registerItem={registerItem}\n              renderNode={renderNode}\n              nodeAttributes={nodeAttributes}\n              labels={labels}\n            />\n          </ul>\n        ) : null}\n      </li>\n    );\n  });\n\n  return <>{items}</>;\n}\n\nexport function TreeView({\n  nodes,\n  selectedId,\n  onSelect,\n  expandedIds,\n  defaultExpandedIds,\n  onExpandedChange,\n  renderNode,\n  nodeAttributes,\n  labels,\n  empty,\n  className,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n}: TreeViewProps) {\n  const t = { ...DEFAULT_LABELS, ...labels };\n  const baseId = React.useId();\n  const [internalExpandedIds, setInternalExpandedIds] = React.useState<string[]>(\n    () => defaultExpandedIds ?? [],\n  );\n  const [focusedId, setFocusedId] = React.useState<string | null>(null);\n  const currentExpandedIds = expandedIds ?? internalExpandedIds;\n  const expanded = React.useMemo(\n    () => new Set(currentExpandedIds),\n    [currentExpandedIds],\n  );\n  const visibleNodes = React.useMemo(\n    () => flattenVisibleNodes(nodes, expanded, 1, null, []),\n    [nodes, expanded],\n  );\n\n  const itemsRef = React.useRef(new Map<string, HTMLLIElement>());\n  const registerItem = (id: string, element: HTMLLIElement | null) => {\n    if (element === null) {\n      itemsRef.current.delete(id);\n    } else {\n      itemsRef.current.set(id, element);\n    }\n  };\n\n  // Roving tabindex: exactly one treeitem is tabbable — the last focused node\n  // while it stays visible, else the selected node, else the first node.\n  const isVisible = (id: string | null | undefined) =>\n    id !== null && id !== undefined && visibleNodes.some((entry) => entry.node.id === id);\n  let activeId: string | null = visibleNodes[0]?.node.id ?? null;\n  if (isVisible(focusedId)) {\n    activeId = focusedId;\n  } else if (isVisible(selectedId)) {\n    activeId = selectedId ?? null;\n  }\n\n  const focusItem = (id: string) => {\n    setFocusedId(id);\n    itemsRef.current.get(id)?.focus();\n  };\n\n  const focusAt = (index: number) => {\n    const entry = visibleNodes[index];\n    if (entry !== undefined) {\n      focusItem(entry.node.id);\n    }\n  };\n\n  const setExpansion = (node: TreeViewNode, next: boolean) => {\n    if (expanded.has(node.id) === next) {\n      return;\n    }\n    const nextIds = next\n      ? [...currentExpandedIds, node.id]\n      : currentExpandedIds.filter((id) => id !== node.id);\n    if (expandedIds === undefined) {\n      setInternalExpandedIds(nextIds);\n    }\n    onExpandedChange?.(nextIds);\n  };\n\n  const handleToggle = (node: TreeViewNode) => {\n    setExpansion(node, !expanded.has(node.id));\n  };\n\n  // ArrowRight opens a closed branch, then steps into it; a leaf is a no-op.\n  const expandOrEnter = (entry: TreeViewFlatNode, index: number) => {\n    if (!entry.hasChildren) {\n      return false;\n    }\n    if (entry.expanded) {\n      focusAt(index + 1);\n    } else {\n      setExpansion(entry.node, true);\n    }\n    return true;\n  };\n\n  // ArrowLeft closes an open branch, else steps out to the parent.\n  const collapseOrLeave = (entry: TreeViewFlatNode) => {\n    if (entry.hasChildren && entry.expanded) {\n      setExpansion(entry.node, false);\n      return true;\n    }\n    if (entry.parentId === null) {\n      return false;\n    }\n    focusItem(entry.parentId);\n    return true;\n  };\n\n  const applyKey = (key: string, entry: TreeViewFlatNode, index: number) => {\n    switch (key) {\n      case \"ArrowDown\":\n        focusAt(index + 1);\n        return true;\n      case \"ArrowUp\":\n        focusAt(index - 1);\n        return true;\n      case \"Home\":\n        focusAt(0);\n        return true;\n      case \"End\":\n        focusAt(visibleNodes.length - 1);\n        return true;\n      case \"ArrowRight\":\n        return expandOrEnter(entry, index);\n      case \"ArrowLeft\":\n        return collapseOrLeave(entry);\n      case \"Enter\":\n      case \" \":\n        onSelect?.(entry.node);\n        return true;\n      default:\n        return false;\n    }\n  };\n\n  const handleItemKeyDown = (\n    event: React.KeyboardEvent<HTMLLIElement>,\n    node: TreeViewNode,\n  ) => {\n    // Only the treeitem that actually holds focus reacts; the event bubbles\n    // through every ancestor treeitem on its way out.\n    if (event.target !== event.currentTarget) {\n      return;\n    }\n    const index = visibleNodes.findIndex((entry) => entry.node.id === node.id);\n    if (index === -1) {\n      return;\n    }\n    if (applyKey(event.key, visibleNodes[index], index)) {\n      event.preventDefault();\n    }\n  };\n\n  const handleItemFocus = (\n    event: React.FocusEvent<HTMLLIElement>,\n    node: TreeViewNode,\n  ) => {\n    if (event.target === event.currentTarget) {\n      setFocusedId(node.id);\n    }\n  };\n\n  // A pointer press moves the roving tabindex with it, so a later Tab leaves\n  // the tree from the node the user last touched.\n  const handleItemPointerDown = (node: TreeViewNode) => {\n    focusItem(node.id);\n  };\n\n  return (\n    <div className={cn(\"w-full\", className)} data-tree-view=\"\">\n      {nodes.length === 0 ? (\n        (empty ?? <p className=\"px-2 py-1 text-sm text-muted-foreground\">{t.empty}</p>)\n      ) : (\n        <ul\n          role=\"tree\"\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabelledBy}\n          className=\"flex flex-col gap-0.5\"\n        >\n          <TreeViewItems\n            nodes={nodes}\n            level={1}\n            idPrefix={baseId}\n            selectedId={selectedId}\n            activeId={activeId}\n            expanded={expanded}\n            onToggle={handleToggle}\n            onSelect={onSelect}\n            onItemKeyDown={handleItemKeyDown}\n            onItemFocus={handleItemFocus}\n            onItemPointerDown={handleItemPointerDown}\n            registerItem={registerItem}\n            renderNode={renderNode}\n            nodeAttributes={nodeAttributes}\n            labels={t}\n          />\n        </ul>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/m8-ui/tree-view.tsx"
    }
  ]
}
