{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "title": "Tree View",
  "description": "A hierarchical tree with expand/collapse, tri-state checkboxes for multi-select, single-row selection, guide lines and full keyboard navigation.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/tree-view/tree-view.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type TreeViewSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface TreeNode {\n  id: string;\n  label: string;\n  icon?: React.ReactNode;\n  disabled?: boolean;\n  children?: TreeNode[];\n}\n\nexport interface TreeViewProps {\n  data: TreeNode[];\n  /** Single-row highlight, independent of checkboxes. */\n  selectable?: boolean;\n  selectedId?: string | null;\n  defaultSelectedId?: string | null;\n  onSelectedChange?: (id: string | null) => void;\n  /** Adds tri-state checkboxes for multi-select; checking a folder checks every leaf under it. */\n  checkable?: boolean;\n  /** The source of truth is leaf ids — a folder's checked/indeterminate state is always derived from its descendants. */\n  checkedIds?: string[];\n  defaultCheckedIds?: string[];\n  onCheckedChange?: (ids: string[]) => void;\n  expandedIds?: string[];\n  defaultExpandedIds?: string[];\n  onExpandedChange?: (ids: string[]) => void;\n  showLines?: boolean;\n  size?: TreeViewSize;\n  theme?: \"dark\" | \"light\";\n  accentColor?: string;\n  width?: number;\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.5)\", faint: \"rgba(245,244,241,0.28)\", line: \"rgba(255,255,255,0.12)\", hover: \"rgba(255,255,255,0.06)\", active: \"rgba(255,255,255,0.09)\", border: \"rgba(255,255,255,0.14)\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.5)\", faint: \"rgba(10,10,10,0.28)\", line: \"rgba(10,10,10,0.12)\", hover: \"rgba(10,10,10,0.05)\", active: \"rgba(10,10,10,0.06)\", border: \"rgba(10,10,10,0.18)\" },\n};\n\nconst SIZES: Record<TreeViewSize, { rowH: number; font: number; icon: number; indent: number; chevron: number }> = {\n  sm: { rowH: 28, font: 12.5, icon: 15, indent: 18, chevron: 12 },\n  md: { rowH: 32, font: 13.5, icon: 16, indent: 20, chevron: 13 },\n  lg: { rowH: 36, font: 14.5, icon: 18, indent: 22, chevron: 14 },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\ntype Size = (typeof SIZES)[\"md\"];\n\nfunction readableTextOn(hex: string): string {\n  const h = hex.replace(\"#\", \"\");\n  const full = h.length === 3 ? h.split(\"\").map((c) => c + c).join(\"\") : h;\n  const r = parseInt(full.slice(0, 2), 16);\n  const g = parseInt(full.slice(2, 4), 16);\n  const b = parseInt(full.slice(4, 6), 16);\n  return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? \"#0A0A0A\" : \"#FFFFFF\";\n}\n\nfunction collectLeafIds(node: TreeNode): string[] {\n  if (!node.children || node.children.length === 0) return [node.id];\n  return node.children.flatMap(collectLeafIds);\n}\n\nfunction checkState(node: TreeNode, checked: Set<string>): \"checked\" | \"indeterminate\" | \"unchecked\" {\n  const leaves = collectLeafIds(node);\n  const n = leaves.filter((id) => checked.has(id)).length;\n  if (n === 0) return \"unchecked\";\n  if (n === leaves.length) return \"checked\";\n  return \"indeterminate\";\n}\n\nfunction FolderIcon({ size, open }: { size: number; open: boolean }) {\n  return open ? (\n    <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <path d=\"M1.8 4.2a1 1 0 0 1 1-1h3l1.2 1.5h6.2a1 1 0 0 1 1 1.1l-.6 6.4a1 1 0 0 1-1 .9H2.7a1 1 0 0 1-1-.9l-.9-7.1V4.2Z\" />\n    </svg>\n  ) : (\n    <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <path d=\"M1.8 3.7a1 1 0 0 1 1-1h3l1.2 1.5h6.2a1 1 0 0 1 1 1v6.6a1 1 0 0 1-1 1H2.8a1 1 0 0 1-1-1V3.7Z\" />\n    </svg>\n  );\n}\n\nfunction FileIcon({ size }: { size: number }) {\n  return (\n    <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <path d=\"M4 1.8h5.2L12.2 5v9a.9.9 0 0 1-.9.9H4a.9.9 0 0 1-.9-.9V2.7a.9.9 0 0 1 .9-.9Z\" />\n      <path d=\"M9.2 1.8V5h3\" />\n    </svg>\n  );\n}\n\nfunction Chevron({ size, open }: { size: number; open: boolean }) {\n  return (\n    <motion.svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" animate={{ rotate: open ? 90 : 0 }} transition={{ duration: 0.16 }} aria-hidden=\"true\">\n      <path d=\"M6 3.5L10.5 8L6 12.5\" />\n    </motion.svg>\n  );\n}\n\nfunction CheckboxGlyph({ state, s, p, accent }: { state: \"checked\" | \"indeterminate\" | \"unchecked\"; s: Size; p: Palette; accent: string }) {\n  const onAccent = readableTextOn(accent);\n  const filled = state !== \"unchecked\";\n  return (\n    <span className=\"flex shrink-0 items-center justify-center rounded\" style={{ width: s.icon - 2, height: s.icon - 2, background: filled ? accent : \"transparent\", border: `1.5px solid ${filled ? accent : p.faint}` }}>\n      {state === \"checked\" && (\n        <svg width=\"9\" height=\"9\" viewBox=\"0 0 12 12\" fill=\"none\" aria-hidden=\"true\">\n          <path d=\"M2.3 6.3L4.7 8.7L9.7 3.3\" stroke={onAccent} strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n        </svg>\n      )}\n      {state === \"indeterminate\" && <span style={{ width: 7, height: 1.6, borderRadius: 1, background: onAccent }} />}\n    </span>\n  );\n}\n\n/** Renders the ancestor guide-line rail to the left of a row: a continuing\n * vertical line per ancestor that still has siblings below it, plus this\n * row's own L-shaped connector. */\nfunction Rail({ ancestorLines, isLast, s, p }: { ancestorLines: boolean[]; isLast: boolean; s: Size; p: Palette }) {\n  const half = s.rowH / 2;\n  return (\n    <div className=\"flex shrink-0\" style={{ height: s.rowH }}>\n      {ancestorLines.map((show, i) => (\n        <div key={i} className=\"relative shrink-0\" style={{ width: s.indent }}>\n          {show && <div className=\"absolute\" style={{ left: s.indent / 2, top: 0, bottom: 0, width: 1, background: p.line }} />}\n        </div>\n      ))}\n      <div className=\"relative shrink-0\" style={{ width: s.indent }}>\n        <div className=\"absolute\" style={{ left: s.indent / 2, top: 0, height: half, width: 1, background: p.line }} />\n        <div className=\"absolute\" style={{ left: s.indent / 2, top: half, width: s.indent / 2, height: 1, background: p.line }} />\n        {!isLast && <div className=\"absolute\" style={{ left: s.indent / 2, top: half, bottom: 0, width: 1, background: p.line }} />}\n      </div>\n    </div>\n  );\n}\n\ninterface RenderCtx {\n  s: Size;\n  p: Palette;\n  accent: string;\n  expanded: Set<string>;\n  toggleExpanded: (id: string) => void;\n  checkable: boolean;\n  checked: Set<string>;\n  toggleChecked: (node: TreeNode) => void;\n  selectable: boolean;\n  selectedId: string | null;\n  select: (id: string) => void;\n  focusedId: string | null;\n  focusRow: (id: string) => void;\n  setRowRef: (id: string, el: HTMLDivElement | null) => void;\n  showLines: boolean;\n}\n\nfunction NodeRow({ node, depth, ancestorLines, isLast, ctx }: { node: TreeNode; depth: number; ancestorLines: boolean[]; isLast: boolean; ctx: RenderCtx }) {\n  const { s, p, accent } = ctx;\n  const hasChildren = Boolean(node.children && node.children.length > 0);\n  const open = ctx.expanded.has(node.id);\n  const isSelected = ctx.selectable && ctx.selectedId === node.id;\n  const isFocused = ctx.focusedId === node.id;\n  const state = ctx.checkable ? checkState(node, ctx.checked) : \"unchecked\";\n\n  return (\n    <div>\n      <div\n        ref={(el) => ctx.setRowRef(node.id, el)}\n        role=\"treeitem\"\n        id={`tv-${node.id}`}\n        aria-level={depth + 1}\n        aria-expanded={hasChildren ? open : undefined}\n        aria-selected={ctx.selectable ? isSelected : undefined}\n        aria-checked={ctx.checkable ? (state === \"indeterminate\" ? \"mixed\" : state === \"checked\") : undefined}\n        aria-disabled={node.disabled || undefined}\n        tabIndex={isFocused ? 0 : -1}\n        onClick={() => {\n          if (node.disabled) return;\n          // Keep keyboard nav picking up from wherever the mouse last\n          // interacted: a plain click on a tabIndex={-1} row does not\n          // move real DOM focus there by itself (only tabIndex >= 0\n          // elements get that for free), so without this an arrow key\n          // right after a click would silently resume from the old\n          // roving-focus row instead of the one just clicked.\n          ctx.focusRow(node.id);\n          if (ctx.checkable) ctx.toggleChecked(node);\n          else if (hasChildren) ctx.toggleExpanded(node.id);\n          if (ctx.selectable) ctx.select(node.id);\n        }}\n        className=\"flex cursor-pointer items-center outline-none select-none focus-visible:ring-2\"\n        style={{ height: s.rowH, borderRadius: 8, background: isSelected ? ctx.p.active : \"transparent\", color: node.disabled ? p.faint : p.text, fontSize: s.font, fontWeight: isSelected ? 600 : 500, cursor: node.disabled ? \"default\" : \"pointer\", opacity: node.disabled ? 0.5 : 1, [\"--tw-ring-color\" as string]: accent }}\n        onMouseEnter={(e) => !isSelected && !node.disabled && (e.currentTarget.style.background = p.hover)}\n        onMouseLeave={(e) => !isSelected && (e.currentTarget.style.background = \"transparent\")}\n      >\n        {ctx.showLines && depth > 0 && <Rail ancestorLines={ancestorLines} isLast={isLast} s={s} p={p} />}\n        {(!ctx.showLines || depth === 0) && <span style={{ width: depth * s.indent, flexShrink: 0 }} />}\n        <span\n          className=\"flex shrink-0 items-center justify-center\"\n          style={{ width: s.indent, height: s.rowH, color: p.muted }}\n          onClick={(e) => {\n            if (!hasChildren) return;\n            e.stopPropagation();\n            ctx.toggleExpanded(node.id);\n          }}\n        >\n          {hasChildren && <Chevron size={s.chevron} open={open} />}\n        </span>\n        {ctx.checkable && (\n          <span className=\"mr-1.5 flex shrink-0 items-center justify-center\" style={{ width: s.icon, height: s.rowH }}>\n            <CheckboxGlyph state={state} s={s} p={p} accent={accent} />\n          </span>\n        )}\n        <span className=\"mr-1.5 flex shrink-0 items-center justify-center\" style={{ width: s.icon, height: s.rowH, color: p.muted }}>\n          {node.icon ?? (hasChildren ? <FolderIcon size={s.icon} open={open} /> : <FileIcon size={s.icon} />)}\n        </span>\n        <span className=\"min-w-0 flex-1 truncate\">{node.label}</span>\n      </div>\n\n      {hasChildren && (\n        <AnimatePresence initial={false}>\n          {open && (\n            <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: \"auto\", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.18, ease: [0.16, 1, 0.3, 1] }} className=\"overflow-hidden\">\n              {node.children!.map((child, i) => (\n                <NodeRow key={child.id} node={child} depth={depth + 1} ancestorLines={[...ancestorLines, !isLast]} isLast={i === node.children!.length - 1} ctx={ctx} />\n              ))}\n            </motion.div>\n          )}\n        </AnimatePresence>\n      )}\n    </div>\n  );\n}\n\nfunction flattenVisible(nodes: TreeNode[], expanded: Set<string>): TreeNode[] {\n  const out: TreeNode[] = [];\n  for (const node of nodes) {\n    if (node.disabled) continue;\n    out.push(node);\n    if (node.children && expanded.has(node.id)) out.push(...flattenVisible(node.children, expanded));\n  }\n  return out;\n}\n\nfunction parentOf(nodes: TreeNode[], id: string, ancestor: TreeNode | null = null): TreeNode | null {\n  for (const node of nodes) {\n    if (node.id === id) return ancestor;\n    if (node.children) {\n      const found = parentOf(node.children, id, node);\n      if (found !== null) return found;\n    }\n  }\n  return null;\n}\n\nexport function TreeView({\n  data,\n  selectable = true,\n  selectedId,\n  defaultSelectedId = null,\n  onSelectedChange,\n  checkable = false,\n  checkedIds,\n  defaultCheckedIds = [],\n  onCheckedChange,\n  expandedIds,\n  defaultExpandedIds = [],\n  onExpandedChange,\n  showLines = true,\n  size = \"md\",\n  theme = \"dark\",\n  accentColor = \"#F2A841\",\n  width = 280,\n  className,\n}: TreeViewProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const rowRefs = React.useRef<Record<string, HTMLDivElement | null>>({});\n\n  const [internalExpanded, setInternalExpanded] = React.useState(() => new Set(defaultExpandedIds));\n  const expanded = React.useMemo(() => (expandedIds !== undefined ? new Set(expandedIds) : internalExpanded), [expandedIds, internalExpanded]);\n  const setExpanded = (next: Set<string>) => {\n    if (expandedIds === undefined) setInternalExpanded(next);\n    onExpandedChange?.(Array.from(next));\n  };\n  const toggleExpanded = (id: string) => {\n    const next = new Set(expanded);\n    if (next.has(id)) next.delete(id);\n    else next.add(id);\n    setExpanded(next);\n  };\n\n  const [internalChecked, setInternalChecked] = React.useState(() => new Set(defaultCheckedIds));\n  const checked = React.useMemo(() => (checkedIds !== undefined ? new Set(checkedIds) : internalChecked), [checkedIds, internalChecked]);\n  const setChecked = (next: Set<string>) => {\n    if (checkedIds === undefined) setInternalChecked(next);\n    onCheckedChange?.(Array.from(next));\n  };\n  const toggleChecked = (node: TreeNode) => {\n    const leaves = collectLeafIds(node);\n    const willCheck = checkState(node, checked) !== \"checked\";\n    const next = new Set(checked);\n    leaves.forEach((id) => (willCheck ? next.add(id) : next.delete(id)));\n    setChecked(next);\n  };\n\n  const [internalSelected, setInternalSelected] = React.useState<string | null>(defaultSelectedId);\n  const currentSelected = selectedId !== undefined ? selectedId : internalSelected;\n  const select = (id: string) => {\n    if (selectedId === undefined) setInternalSelected(id);\n    onSelectedChange?.(id);\n  };\n\n  const visible = React.useMemo(() => flattenVisible(data, expanded), [data, expanded]);\n  const [focusedId, setFocusedId] = React.useState<string | null>(visible[0]?.id ?? null);\n  // A collapsed ancestor (or a removed node) can take the focused row out of\n  // view; land back on the first visible row instead of leaving focus on a\n  // hidden one. Adjusting here, during render, avoids the extra\n  // render-then-effect-then-render round trip a useEffect would cause.\n  const [lastVisible, setLastVisible] = React.useState(visible);\n  if (visible !== lastVisible) {\n    setLastVisible(visible);\n    if (focusedId && !visible.some((n) => n.id === focusedId)) setFocusedId(visible[0]?.id ?? null);\n  }\n\n  const focusRow = (id: string) => {\n    setFocusedId(id);\n    rowRefs.current[id]?.focus({ preventScroll: true });\n  };\n\n  const move = (dir: 1 | -1) => {\n    if (visible.length === 0) return;\n    const i = focusedId ? visible.findIndex((n) => n.id === focusedId) : -1;\n    const next = visible[(i + dir + visible.length) % visible.length];\n    focusRow(next.id);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const node = visible.find((n) => n.id === focusedId);\n    if (!node) return;\n    const hasChildren = Boolean(node.children && node.children.length > 0);\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      move(1);\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      move(-1);\n    } else if (e.key === \"ArrowRight\") {\n      e.preventDefault();\n      if (hasChildren && !expanded.has(node.id)) toggleExpanded(node.id);\n      else if (hasChildren) move(1);\n    } else if (e.key === \"ArrowLeft\") {\n      e.preventDefault();\n      if (hasChildren && expanded.has(node.id)) toggleExpanded(node.id);\n      else {\n        const parent = parentOf(data, node.id);\n        if (parent) focusRow(parent.id);\n      }\n    } else if (e.key === \"Home\") {\n      e.preventDefault();\n      focusRow(visible[0].id);\n    } else if (e.key === \"End\") {\n      e.preventDefault();\n      focusRow(visible[visible.length - 1].id);\n    } else if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      if (checkable) toggleChecked(node);\n      else if (hasChildren) toggleExpanded(node.id);\n      if (selectable) select(node.id);\n    }\n  };\n\n  const ctx: RenderCtx = {\n    s,\n    p,\n    accent: accentColor,\n    expanded,\n    toggleExpanded,\n    checkable,\n    checked,\n    toggleChecked,\n    selectable,\n    selectedId: currentSelected,\n    select,\n    focusedId,\n    focusRow,\n    setRowRef: (id, el) => {\n      rowRefs.current[id] = el;\n    },\n    showLines,\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"tree\"\n      aria-multiselectable={checkable || undefined}\n      tabIndex={-1}\n      onKeyDown={onKeyDown}\n      className={cn(\"outline-none\", className)}\n      style={{ width, maxWidth: \"100%\", padding: 6, borderRadius: 14, border: `1px solid ${p.border}`, fontFamily: \"Inter, sans-serif\" }}\n    >\n      {data.map((node, i) => (\n        <NodeRow key={node.id} node={node} depth={0} ancestorLines={[]} isLast={i === data.length - 1} ctx={ctx} />\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}