{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "type": "registry:ui",
  "title": "Tree View",
  "description": "Tree View is a hierarchical, keyboard-navigable tree — file explorers, nested category browsers, org charts. Composes Content/Tree Item rows with roving-tabindex keyboard navigation and depth-based indentation.",
  "author": "Skrewww",
  "dependencies": [
    "@phosphor-icons/react"
  ],
  "registryDependencies": [
    "@skrewww/foundation"
  ],
  "docs": "Host requirements (assumed already present, not installed by this command): react, react-dom.",
  "files": [
    {
      "path": "components/ui/TreeView.tsx",
      "content": "/** @skrewww-component tree-view */\n\"use client\";\n\nimport { useEffect, useMemo, useRef, useState, type KeyboardEvent } from \"react\";\nimport { useControllableState } from \"@/lib/use-controllable\";\nimport { TreeItem } from \"@/components/ui/internal/TreeItem\";\nimport {\n  flattenVisibleTree,\n  resolveTreeKeyAction,\n  type TreeNode,\n} from \"@/components/ui/internal/tree-flatten\";\nimport { cn } from \"@/lib/cn\";\nimport styles from \"@/components/ui/tree-view.module.css\";\n\nexport type { TreeNode };\n\nexport type TreeViewProps = {\n  /** Recursive node data — the only shape Tree View accepts. */\n  data: TreeNode[];\n  /** Controlled expanded-node ids. Pass alongside onExpandedChange. */\n  expanded?: string[];\n  /** Initial expanded-node ids for uncontrolled usage. */\n  defaultExpanded?: string[];\n  onExpandedChange?: (expanded: string[]) => void;\n  /** Controlled selected node id (single-select). Pass alongside onSelectedChange. */\n  selected?: string | null;\n  /** Initial selected node id for uncontrolled usage. */\n  defaultSelected?: string | null;\n  onSelectedChange?: (id: string | null) => void;\n  \"aria-label\"?: string;\n  \"aria-labelledby\"?: string;\n  className?: string;\n};\n\n/**\n * Hierarchical tree, built against Figma's Content/Tree Item component set +\n * the \"Tree View (example)\" composed demo. Single-select only — multi-select\n * is a deferred v2, not part of this scope. No drag-and-drop reordering,\n * virtualization, or async/lazy-loaded children.\n */\nexport function TreeView(props: TreeViewProps) {\n  const expandedProvided = \"expanded\" in props;\n  const selectedProvided = \"selected\" in props;\n  const {\n    data,\n    expanded: expandedProp,\n    defaultExpanded = [],\n    onExpandedChange,\n    selected: selectedProp,\n    defaultSelected = null,\n    onSelectedChange,\n    \"aria-label\": ariaLabel,\n    \"aria-labelledby\": ariaLabelledBy,\n    className,\n  } = props;\n\n  const [expandedList, setExpandedList] = useControllableState<string[]>({\n    value: expandedProp,\n    defaultValue: defaultExpanded,\n    onChange: onExpandedChange,\n    valueProvided: expandedProvided,\n  });\n\n  const [selected, setSelected] = useControllableState<string | null>({\n    value: selectedProp,\n    defaultValue: defaultSelected,\n    onChange: onSelectedChange,\n    valueProvided: selectedProvided,\n  });\n\n  const expandedSet = useMemo(() => new Set(expandedList), [expandedList]);\n  const rows = useMemo(() => flattenVisibleTree(data, expandedSet), [data, expandedSet]);\n\n  const rowRefs = useRef(new Map<string, HTMLDivElement>());\n  const pendingFocusChildRef = useRef<string | null>(null);\n\n  const [focusedId, setFocusedId] = useState<string | null>(() => rows[0]?.node.id ?? null);\n\n  // Recover focus onto the first visible row whenever the previously\n  // focused node stops being visible (data changed, or its parent collapsed\n  // via a controlled `expanded` update) — adjusted during render rather\n  // than in an effect, per React's guidance for state derived from props,\n  // guarded by comparing against the previous `rows` reference so it only\n  // runs when the visible set actually changes.\n  const [lastRows, setLastRows] = useState(rows);\n  if (rows !== lastRows) {\n    setLastRows(rows);\n    const stillVisible = focusedId !== null && rows.some((row) => row.node.id === focusedId);\n    if (!stillVisible) {\n      setFocusedId(rows[0]?.node.id ?? null);\n    }\n  }\n\n  // ArrowRight on a collapsed node expands it, then moves focus onto its\n  // first child — but that child doesn't exist in the DOM until the\n  // expand commits, so the actual .focus() call is deferred here.\n  useEffect(() => {\n    const pending = pendingFocusChildRef.current;\n    if (!pending) return;\n    if (!rows.some((row) => row.node.id === pending)) return;\n    const node = rowRefs.current.get(pending);\n    node?.focus({ preventScroll: true });\n    pendingFocusChildRef.current = null;\n  }, [rows]);\n\n  function focusRow(id: string) {\n    setFocusedId(id);\n    const node = rowRefs.current.get(id);\n    if (node) {\n      node.focus({ preventScroll: true });\n      node.scrollIntoView?.({ block: \"nearest\" });\n    }\n  }\n\n  function handleSelectRow(id: string) {\n    focusRow(id);\n    setSelected(id);\n  }\n\n  function handleToggleExpand(id: string) {\n    focusRow(id);\n    setExpandedList(\n      expandedSet.has(id)\n        ? expandedList.filter((existing) => existing !== id)\n        : [...expandedList, id],\n    );\n  }\n\n  function handleRowKeyDown(event: KeyboardEvent<HTMLDivElement>, rowId: string) {\n    const action = resolveTreeKeyAction(event.key, rows, rowId, expandedSet);\n    if (action.type === \"none\") return;\n    event.preventDefault();\n\n    switch (action.type) {\n      case \"move\":\n        focusRow(action.id);\n        break;\n      case \"expand\":\n        setExpandedList([...expandedList, action.id]);\n        break;\n      case \"expand-and-focus-child\":\n        pendingFocusChildRef.current = action.childId;\n        setFocusedId(action.childId);\n        setExpandedList([...expandedList, action.id]);\n        break;\n      case \"collapse\":\n        setExpandedList(expandedList.filter((existing) => existing !== action.id));\n        break;\n      case \"select\":\n        setSelected(action.id);\n        break;\n    }\n  }\n\n  return (\n    <div\n      role=\"tree\"\n      aria-label={ariaLabel}\n      aria-labelledby={ariaLabelledBy}\n      className={cn(styles.tree, className)}\n    >\n      {rows.map((row) => (\n        <TreeItem\n          key={row.node.id}\n          ref={(node) => {\n            if (node) rowRefs.current.set(row.node.id, node);\n            else rowRefs.current.delete(row.node.id);\n          }}\n          label={row.node.label}\n          icon={row.node.icon}\n          depth={row.depth}\n          hasChildren={row.hasChildren}\n          expanded={expandedSet.has(row.node.id)}\n          selected={selected === row.node.id}\n          posInSet={row.posInSet}\n          setSize={row.setSize}\n          tabIndex={row.node.id === focusedId ? 0 : -1}\n          onSelect={() => handleSelectRow(row.node.id)}\n          onToggleExpand={() => handleToggleExpand(row.node.id)}\n          onKeyDown={(event) => handleRowKeyDown(event, row.node.id)}\n        />\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/TreeView.tsx"
    },
    {
      "path": "components/ui/tree-view.module.css",
      "content": ".tree {\n  display: flex;\n  flex-direction: column;\n  gap: 0.125rem;\n  outline: none;\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/tree-view.module.css"
    },
    {
      "path": "lib/cn.ts",
      "content": "export function cn(...classes: Array<string | false | null | undefined>): string {\n  return classes.filter(Boolean).join(\" \");\n}\n",
      "type": "registry:lib",
      "target": "~/lib/cn.ts"
    },
    {
      "path": "lib/use-controllable.ts",
      "content": "import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport function useControllableState<T>({\n  value,\n  defaultValue,\n  onChange,\n  controlled: controlledProp,\n  valueProvided,\n}: {\n  value?: T;\n  defaultValue?: T;\n  onChange?: (next: T) => void;\n  /** Explicit controlled override — prefer `valueProvided` from the component root. */\n  controlled?: boolean;\n  /** True when the parent passed a `value` prop, including `undefined`. */\n  valueProvided?: boolean;\n}) {\n  const [uncontrolled, setUncontrolled] = useState(defaultValue as T);\n  const isControlled = controlledProp ?? valueProvided ?? value !== undefined;\n  const current = isControlled ? (value as T) : uncontrolled;\n  const wasControlledRef = useRef(isControlled);\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"development\") return;\n    if (wasControlledRef.current !== isControlled) {\n      console.warn(\n        \"[Skrewww] A component changed between controlled and uncontrolled modes. Keep `value` or `defaultValue` usage consistent across renders.\",\n      );\n    }\n    wasControlledRef.current = isControlled;\n  }, [isControlled]);\n\n  const setValue = useCallback(\n    (next: T) => {\n      if (!isControlled) setUncontrolled(next);\n      onChange?.(next);\n    },\n    [isControlled, onChange],\n  );\n\n  return [current, setValue] as const;\n}\n",
      "type": "registry:lib",
      "target": "~/lib/use-controllable.ts"
    },
    {
      "path": "components/ui/internal/TreeItem.tsx",
      "content": "\"use client\";\n\nimport { forwardRef, type KeyboardEvent, type MouseEvent, type ReactNode } from \"react\";\nimport { CaretRight } from \"@phosphor-icons/react\";\nimport { cn } from \"@/lib/cn\";\nimport styles from \"@/components/ui/internal/tree-item.module.css\";\n\n/** Depth-proportional left spacer, confirmed 20px per depth in Figma's composed example. */\nexport const TREE_ITEM_INDENT_PX = 20;\n\nexport type TreeItemProps = {\n  label: string;\n  icon?: ReactNode;\n  depth: number;\n  hasChildren: boolean;\n  expanded: boolean;\n  selected: boolean;\n  posInSet: number;\n  setSize: number;\n  tabIndex: 0 | -1;\n  onSelect: () => void;\n  onToggleExpand: () => void;\n  onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;\n  className?: string;\n};\n\n/**\n * A single Tree View row. Internal to components/ui/TreeView.tsx — the\n * public API is TreeView + a TreeNode data prop, not this row in isolation\n * (matches the Figma anatomy: Chevron + Icon slot + Label, with indentation\n * as a real depth * 20px spacer rather than a fixed per-depth variant).\n */\nexport const TreeItem = forwardRef<HTMLDivElement, TreeItemProps>(function TreeItem(\n  {\n    label,\n    icon,\n    depth,\n    hasChildren,\n    expanded,\n    selected,\n    posInSet,\n    setSize,\n    tabIndex,\n    onSelect,\n    onToggleExpand,\n    onKeyDown,\n    className,\n  },\n  ref,\n) {\n  function handleChevronClick(event: MouseEvent<HTMLSpanElement>) {\n    event.stopPropagation();\n    onToggleExpand();\n  }\n\n  return (\n    <div\n      ref={ref}\n      role=\"treeitem\"\n      tabIndex={tabIndex}\n      aria-expanded={hasChildren ? expanded : undefined}\n      aria-selected={selected}\n      aria-level={depth + 1}\n      aria-setsize={setSize}\n      aria-posinset={posInSet}\n      className={cn(styles.row, selected && styles.selected, className)}\n      style={{\n        paddingLeft: `calc(var(--tree-item-padding-x) + ${depth * TREE_ITEM_INDENT_PX}px)`,\n      }}\n      onClick={onSelect}\n      onKeyDown={onKeyDown}\n    >\n      {hasChildren ? (\n        <span\n          role=\"presentation\"\n          className={cn(styles.chevron, expanded && styles.chevronExpanded)}\n          onClick={handleChevronClick}\n        >\n          <CaretRight size={16} weight=\"bold\" aria-hidden=\"true\" />\n        </span>\n      ) : (\n        <span className={styles.chevronSpacer} aria-hidden=\"true\" />\n      )}\n      {icon ? (\n        <span className={styles.icon} aria-hidden=\"true\">\n          {icon}\n        </span>\n      ) : null}\n      <span className={styles.label}>{label}</span>\n    </div>\n  );\n});\n",
      "type": "registry:ui",
      "target": "~/components/ui/internal/TreeItem.tsx"
    },
    {
      "path": "components/ui/internal/tree-item.module.css",
      "content": ".row {\n  display: flex;\n  align-items: center;\n  gap: var(--tree-item-gap);\n  min-height: var(--tree-item-height);\n  padding-right: var(--tree-item-padding-x);\n  border: 0;\n  border-radius: var(--tree-item-radius);\n  background: transparent;\n  color: var(--tree-item-text);\n  cursor: pointer;\n  user-select: none;\n}\n\n.row:hover {\n  background: var(--tree-item-hover-surface);\n}\n\n.row:focus-visible {\n  outline: 2px solid var(--semantic-focus-ring);\n  outline-offset: -2px;\n}\n\n.selected {\n  background-color: var(--tree-item-selected-surface);\n  background-image: var(--component-surface-gradient-overlay);\n  color: var(--tree-item-selected-text);\n}\n\n.selected:hover {\n  background-image: var(--component-surface-gradient-overlay);\n}\n\n.chevron {\n  display: inline-flex;\n  flex-shrink: 0;\n  align-items: center;\n  justify-content: center;\n  width: var(--tree-item-chevron-size);\n  height: var(--tree-item-chevron-size);\n  color: var(--tree-item-icon-color);\n  transform: rotate(0deg);\n  transition: transform 0.15s ease;\n}\n\n.chevronExpanded {\n  transform: rotate(90deg);\n}\n\n.chevronSpacer {\n  flex-shrink: 0;\n  width: var(--tree-item-chevron-size);\n  height: var(--tree-item-chevron-size);\n}\n\n.icon {\n  display: inline-flex;\n  flex-shrink: 0;\n  align-items: center;\n  justify-content: center;\n  width: var(--tree-item-icon-size);\n  height: var(--tree-item-icon-size);\n  color: var(--tree-item-icon-color);\n}\n\n.label {\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  font-size: 0.875rem;\n  line-height: 1.4;\n}\n\n[data-skrewww-shape=\"pill\"] .row {\n  border-radius: min(var(--tree-item-radius), 1rem);\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/internal/tree-item.module.css"
    },
    {
      "path": "components/ui/internal/tree-flatten.ts",
      "content": "import type { ReactNode } from \"react\";\n\nexport type TreeNode = {\n  id: string;\n  label: string;\n  icon?: ReactNode;\n  children?: TreeNode[];\n};\n\nexport type FlatTreeRow = {\n  node: TreeNode;\n  depth: number;\n  parentId: string | null;\n  posInSet: number;\n  setSize: number;\n  hasChildren: boolean;\n};\n\n/**\n * Flattens a tree into its currently-visible rows in document order\n * (depth-first, pre-order). A node's children are only included when the\n * node's own id is in `expandedIds` — matching the real Figma anatomy,\n * where indentation is a per-instance depth spacer, not a fixed variant.\n */\nexport function flattenVisibleTree(\n  nodes: TreeNode[],\n  expandedIds: ReadonlySet<string>,\n): FlatTreeRow[] {\n  const rows: FlatTreeRow[] = [];\n\n  function visit(siblings: TreeNode[], depth: number, parentId: string | null) {\n    siblings.forEach((node, index) => {\n      const hasChildren = Boolean(node.children && node.children.length > 0);\n      rows.push({\n        node,\n        depth,\n        parentId,\n        posInSet: index + 1,\n        setSize: siblings.length,\n        hasChildren,\n      });\n      if (hasChildren && expandedIds.has(node.id)) {\n        visit(node.children as TreeNode[], depth + 1, node.id);\n      }\n    });\n  }\n\n  visit(nodes, 0, null);\n  return rows;\n}\n\nexport type TreeKeyAction =\n  | { type: \"move\"; id: string }\n  | { type: \"expand\"; id: string }\n  | { type: \"expand-and-focus-child\"; id: string; childId: string }\n  | { type: \"collapse\"; id: string }\n  | { type: \"select\"; id: string }\n  | { type: \"none\" };\n\n/**\n * Pure resolution of a keydown into a tree action — no DOM or state access,\n * so branches are unit-testable without rendering. `rows` must already be\n * ordered by `flattenVisibleTree` (depth-first, pre-order): an expanded\n * node's first child is always the very next row, which lets ArrowRight\n * resolve without a second tree walk.\n */\nexport function resolveTreeKeyAction(\n  key: string,\n  rows: FlatTreeRow[],\n  focusedId: string,\n  expandedIds: ReadonlySet<string>,\n): TreeKeyAction {\n  const index = rows.findIndex((row) => row.node.id === focusedId);\n  if (index === -1) return { type: \"none\" };\n  const row = rows[index];\n\n  switch (key) {\n    case \"ArrowDown\": {\n      const next = rows[index + 1];\n      return next ? { type: \"move\", id: next.node.id } : { type: \"none\" };\n    }\n    case \"ArrowUp\": {\n      const previous = rows[index - 1];\n      return previous ? { type: \"move\", id: previous.node.id } : { type: \"none\" };\n    }\n    case \"ArrowRight\": {\n      if (!row.hasChildren) return { type: \"none\" };\n      if (!expandedIds.has(row.node.id)) {\n        // A collapsed node's children are never in `rows` (flattenVisibleTree\n        // only recurses into already-expanded nodes), so the first child's id\n        // must come from the raw node data, not from the flattened list.\n        const firstChild = row.node.children?.[0];\n        return firstChild\n          ? { type: \"expand-and-focus-child\", id: row.node.id, childId: firstChild.id }\n          : { type: \"expand\", id: row.node.id };\n      }\n      const child = rows[index + 1];\n      return child && child.parentId === row.node.id\n        ? { type: \"move\", id: child.node.id }\n        : { type: \"none\" };\n    }\n    case \"ArrowLeft\": {\n      if (row.hasChildren && expandedIds.has(row.node.id)) {\n        return { type: \"collapse\", id: row.node.id };\n      }\n      if (row.parentId) return { type: \"move\", id: row.parentId };\n      return { type: \"none\" };\n    }\n    case \"Enter\":\n    case \" \":\n      return { type: \"select\", id: row.node.id };\n    default:\n      return { type: \"none\" };\n  }\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/tree-flatten.ts"
    }
  ]
}
