{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "type": "registry:component",
  "title": "Tree view",
  "description": "A keyboard-first tree for files, permissions and navigation, with animated expansion, tri-state checkboxes, lazy children and filtering.",
  "categories": [
    "navigation"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/tree-view.tsx",
      "type": "registry:component",
      "target": "components/overtrue/tree-view.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconAlertCircle as AlertCircle,\n  IconCheck as Check,\n  IconChevronRight as ChevronRight,\n  IconLoader2 as Loader,\n  IconMinus as Minus,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------------------------------\n * Types\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface TreeNodeState {\n  /** 1 for root nodes. */\n  level: number;\n  expanded: boolean;\n  selected: boolean;\n  checked: TreeCheckedState;\n  disabled: boolean;\n  loading: boolean;\n  /** The node's label matches the current filter. */\n  match: boolean;\n}\n\nexport interface TreeNode {\n  id: string;\n  /** Plain text, used for type-ahead, filtering and the accessible name. */\n  label: string;\n  /** An icon, or a function of the node's state, e.g. an open folder while expanded. */\n  icon?: React.ReactNode | ((state: TreeNodeState) => React.ReactNode);\n  children?: readonly TreeNode[];\n  /** The node has children that load through `onLoadChildren` the first time it opens. */\n  hasChildren?: boolean;\n  /** Trailing content. Strings and numbers render as a quiet pill. */\n  badge?: React.ReactNode;\n  /** Can't be selected or checked. It can still be focused and expanded. */\n  disabled?: boolean;\n}\n\nexport type TreeCheckedState = boolean | \"mixed\";\nexport type TreeSelectionMode = \"single\" | \"multiple\" | \"none\";\n\nexport interface TreeViewLabels {\n  tree: string;\n  loading: string;\n  loadingNode: (label: string) => string;\n  loaded: (label: string, count: number) => string;\n  loadError: string;\n  loadErrorNode: (label: string) => string;\n  retry: string;\n  empty: string;\n  noMatches: string;\n  matches: (count: number) => string;\n}\n\nexport interface TreeViewProps\n  extends Omit<React.ComponentProps<\"div\">, \"children\" | \"onSelect\" | \"defaultValue\" | \"defaultChecked\" | \"onChange\"> {\n  nodes: readonly TreeNode[];\n  /** \"single\" (default), \"multiple\" with Shift and Cmd or Ctrl, or \"none\". */\n  selectionMode?: TreeSelectionMode;\n  /** Selected ids. Pass with `onSelectedChange` to control selection. */\n  selected?: readonly string[];\n  defaultSelected?: readonly string[];\n  onSelectedChange?: (ids: string[]) => void;\n  /** Called when a node is chosen by click, Enter or Space. */\n  onSelect?: (node: TreeNode) => void;\n  /** Expanded ids. Pass with `onExpandedChange` to control expansion. */\n  expanded?: readonly string[];\n  defaultExpanded?: readonly string[];\n  onExpandedChange?: (ids: string[]) => void;\n  /** Show tri-state checkboxes that propagate down to children and up to parents. */\n  checkable?: boolean;\n  /** Fully checked ids, branches included. Pass with `onCheckedChange` to control them. */\n  checked?: readonly string[];\n  defaultChecked?: readonly string[];\n  onCheckedChange?: (ids: string[]) => void;\n  /** Loads the children of a node marked `hasChildren`. Return them, or update `nodes` yourself. */\n  onLoadChildren?: (node: TreeNode) => Promise<readonly TreeNode[] | void>;\n  /** Shows matching nodes and their ancestors, opened. Matches are highlighted. */\n  filter?: string;\n  filterFn?: (node: TreeNode, query: string) => boolean;\n  /** Replace the label text; return undefined to keep it. The chevron, checkbox, icon and badge stay. */\n  renderLabel?: (node: TreeNode, state: TreeNodeState) => React.ReactNode;\n  /** Clicking or pressing Enter on a parent also opens or closes it. Defaults to true. */\n  expandOnClick?: boolean;\n  /** Vertical lines under each open parent. Defaults to true. */\n  indentGuides?: boolean;\n  /** Indent per level in pixels. Defaults to 16. */\n  indent?: number;\n  size?: \"sm\" | \"default\";\n  labels?: Partial<TreeViewLabels>;\n}\n\nconst LABELS: TreeViewLabels = {\n  tree: \"Tree\",\n  loading: \"Loading…\",\n  loadingNode: (label) => `Loading ${label}`,\n  loaded: (label, count) => `${label} loaded, ${count} ${count === 1 ? \"item\" : \"items\"}`,\n  loadError: \"Couldn't load\",\n  loadErrorNode: (label) => `Couldn't load ${label}`,\n  retry: \"Retry\",\n  empty: \"Nothing here\",\n  noMatches: \"No matches\",\n  matches: (count) => (count === 0 ? \"No matches\" : `${count} ${count === 1 ? \"match\" : \"matches\"}`),\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Helpers\n * -----------------------------------------------------------------------------------------------*/\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst reducedMotion = () =>\n  typeof window !== \"undefined\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\nconst EMPTY: readonly string[] = [];\n\nconst defaultFilter = (node: TreeNode, query: string) => node.label.toLowerCase().includes(query);\n\ninterface Info {\n  node: TreeNode;\n  parent: string | null;\n  level: number;\n}\n\ninterface Row {\n  node: TreeNode;\n  level: number;\n  parent: string | null;\n}\n\n/** Fully checked ids after normalizing: a parent is checked exactly when all its children are. */\nfunction computeChecks(\n  roots: readonly TreeNode[],\n  set: ReadonlySet<string>,\n  childrenOf: (node: TreeNode) => readonly TreeNode[] | undefined,\n) {\n  const state = new Map<string, TreeCheckedState>();\n  const visit = (node: TreeNode, inherited: boolean): TreeCheckedState => {\n    const self = inherited || set.has(node.id);\n    const kids = childrenOf(node);\n    let value: TreeCheckedState = self;\n    if (kids && kids.length) {\n      const values = kids.map((kid) => visit(kid, self));\n      value = values.every((v) => v === true) ? true : values.every((v) => v === false) ? false : \"mixed\";\n    }\n    state.set(node.id, value);\n    return value;\n  };\n  for (const root of roots) visit(root, false);\n  return state;\n}\n\nfunction highlight(text: string, query: string): React.ReactNode {\n  if (!query) return text;\n  const lower = text.toLowerCase();\n  let at = lower.indexOf(query);\n  if (at === -1) return text;\n  const parts: React.ReactNode[] = [];\n  let from = 0;\n  while (at !== -1) {\n    if (at > from) parts.push(text.slice(from, at));\n    parts.push(\n      <mark\n        key={at}\n        data-slot=\"tree-view-match\"\n        className=\"rounded-[3px] bg-amber-400/35 text-inherit dark:bg-amber-400/25\"\n      >\n        {text.slice(at, at + query.length)}\n      </mark>,\n    );\n    from = at + query.length;\n    at = lower.indexOf(query, from);\n  }\n  if (from < text.length) parts.push(text.slice(from));\n  return parts;\n}\n\n// The focus ring sits on the row, not on the item that also wraps the children.\nconst styles = `@keyframes tree-view-shimmer{from{transform:translateX(-100%)}to{transform:translateX(200%)}}[data-slot=\"tree-view-item\"]:focus-visible>[data-slot=\"tree-view-row\"]{box-shadow:0 0 0 2px color-mix(in oklab,var(--color-ring) 50%,transparent)}`;\n\n/* -------------------------------------------------------------------------------------------------\n * Collapse: animated height through grid rows, unmounted once closed\n * -----------------------------------------------------------------------------------------------*/\n\ntype Phase = \"opening\" | \"open\" | \"closing\" | \"closed\";\n\nfunction Collapse({\n  open,\n  animate,\n  children,\n  guide,\n  guideActive,\n}: {\n  open: boolean;\n  animate: boolean;\n  children: React.ReactNode;\n  guide: number | null;\n  guideActive: boolean;\n}) {\n  const [phase, setPhase] = React.useState<Phase>(open ? (animate ? \"opening\" : \"open\") : \"closed\");\n  const [previous, setPrevious] = React.useState(open);\n  if (open !== previous) {\n    setPrevious(open);\n    setPhase(open ? \"opening\" : \"closing\");\n  }\n\n  React.useEffect(() => {\n    if (phase !== \"opening\" && phase !== \"closing\") return;\n    const done = phase === \"opening\" ? \"open\" : \"closed\";\n    if (reducedMotion()) {\n      setPhase(done);\n      return;\n    }\n    // Fallback for browsers that skip the transition.\n    const timer = window.setTimeout(() => setPhase(done), 320);\n    return () => window.clearTimeout(timer);\n  }, [phase]);\n\n  if (phase === \"closed\") return null;\n  return (\n    <div\n      data-slot=\"tree-view-collapse\"\n      data-state={open ? \"open\" : \"closed\"}\n      inert={!open || undefined}\n      onTransitionEnd={(event) => {\n        if (event.target !== event.currentTarget || event.propertyName !== \"grid-template-rows\") return;\n        setPhase(open ? \"open\" : \"closed\");\n      }}\n      className={cn(\n        \"relative grid transition-[grid-template-rows,opacity] duration-[240ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n        open ? \"grid-rows-[1fr] opacity-100\" : \"grid-rows-[0fr] opacity-0\",\n        phase === \"opening\" && animate && \"starting:grid-rows-[0fr] starting:opacity-0\",\n      )}\n    >\n      <div className={cn(\"relative min-h-0\", phase !== \"open\" && \"overflow-hidden\")}>\n        {guide !== null && (\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"tree-view-guide\"\n            className={cn(\n              \"pointer-events-none absolute top-0 bottom-1 w-px transition-colors duration-150 motion-reduce:transition-none\",\n              guideActive ? \"bg-foreground/20\" : \"bg-border\",\n            )}\n            style={{ left: guide }}\n          />\n        )}\n        {children}\n      </div>\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * TreeView\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * A hierarchical tree for files, permissions or navigation: animated expansion, indent guides,\n * single or multiple selection, tri-state checkboxes, lazy children, filtering and type-ahead.\n */\nexport function TreeView({\n  nodes,\n  selectionMode = \"single\",\n  selected: selectedProp,\n  defaultSelected = EMPTY,\n  onSelectedChange,\n  onSelect,\n  expanded: expandedProp,\n  defaultExpanded = EMPTY,\n  onExpandedChange,\n  checkable = false,\n  checked: checkedProp,\n  defaultChecked = EMPTY,\n  onCheckedChange,\n  onLoadChildren,\n  filter = \"\",\n  filterFn = defaultFilter,\n  renderLabel,\n  expandOnClick = true,\n  indentGuides = true,\n  indent = 16,\n  size = \"default\",\n  labels: labelsProp,\n  className,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n  ...props\n}: TreeViewProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const id = React.useId();\n\n  // Lazy children and their loading state.\n  const [loaded, setLoaded] = React.useState<ReadonlyMap<string, readonly TreeNode[]>>(() => new Map());\n  const [status, setStatus] = React.useState<ReadonlyMap<string, \"loading\" | \"error\">>(() => new Map());\n  const childrenOf = React.useCallback(\n    (node: TreeNode) => node.children ?? loaded.get(node.id),\n    [loaded],\n  );\n  const isBranch = React.useCallback(\n    (node: TreeNode) => {\n      const kids = childrenOf(node);\n      return kids ? kids.length > 0 : !!node.hasChildren;\n    },\n    [childrenOf],\n  );\n\n  // Index of every known node, in tree order.\n  const { info, order } = React.useMemo(() => {\n    const info = new Map<string, Info>();\n    const order: string[] = [];\n    const visit = (node: TreeNode, parent: string | null, level: number) => {\n      info.set(node.id, { node, parent, level });\n      order.push(node.id);\n      for (const kid of childrenOf(node) ?? []) visit(kid, node.id, level + 1);\n    };\n    for (const root of nodes) visit(root, null, 1);\n    return { info, order };\n  }, [nodes, childrenOf]);\n\n  /* ------------------------------- Controlled state ------------------------------- */\n\n  const [expandedState, setExpandedState] = React.useState<readonly string[]>(defaultExpanded);\n  const expandedList = expandedProp ?? expandedState;\n  const expandedSet = React.useMemo(() => new Set(expandedList), [expandedList]);\n  const setExpanded = (next: Set<string>) => {\n    const list = order.filter((key) => next.has(key)).concat([...next].filter((key) => !info.has(key)));\n    if (expandedProp === undefined) setExpandedState(list);\n    onExpandedChange?.(list);\n  };\n\n  const [selectedState, setSelectedState] = React.useState<readonly string[]>(defaultSelected);\n  const selectedList = selectionMode === \"none\" ? EMPTY : (selectedProp ?? selectedState);\n  const selectedSet = React.useMemo(() => new Set(selectedList), [selectedList]);\n  const setSelected = (ids: string[]) => {\n    if (selectedProp === undefined) setSelectedState(ids);\n    onSelectedChange?.(ids);\n  };\n\n  const [checkedState, setCheckedState] = React.useState<readonly string[]>(defaultChecked);\n  const checkedList = checkedProp ?? checkedState;\n  const checks = React.useMemo(\n    () => (checkable ? computeChecks(nodes, new Set(checkedList), childrenOf) : null),\n    [checkable, nodes, checkedList, childrenOf],\n  );\n\n  /* ------------------------------------ Filter ------------------------------------ */\n\n  const query = filter.trim().toLowerCase();\n  const filtering = query.length > 0;\n  const { matches, keep, forced } = React.useMemo(() => {\n    const matches = new Set<string>();\n    const keep = new Set<string>();\n    const forced = new Set<string>();\n    if (!query) return { matches, keep, forced };\n    for (const key of order) {\n      const entry = info.get(key)!;\n      if (!filterFn(entry.node, query)) continue;\n      matches.add(key);\n      keep.add(key);\n      for (let parent = entry.parent; parent !== null; parent = info.get(parent)?.parent ?? null) {\n        keep.add(parent);\n        forced.add(parent);\n      }\n    }\n    return { matches, keep, forced };\n  }, [query, order, info, filterFn]);\n\n  // Parents the person closed while filtering stay closed until the filter changes.\n  const [filterClosed, setFilterClosed] = React.useState<ReadonlySet<string>>(() => new Set());\n  const [lastQuery, setLastQuery] = React.useState(query);\n  if (query !== lastQuery) {\n    setLastQuery(query);\n    setFilterClosed(new Set());\n  }\n\n  const isOpen = (node: TreeNode) =>\n    isBranch(node) &&\n    (expandedSet.has(node.id) || (filtering && forced.has(node.id) && !filterClosed.has(node.id)));\n\n  /* ----------------------------------- Visible rows ----------------------------------- */\n\n  // Children shown for a node: under a filter, only kept nodes unless an ancestor matched itself.\n  const shownChildren = (node: TreeNode, insideMatch: boolean) => {\n    const kids = childrenOf(node) ?? [];\n    if (!filtering || insideMatch || matches.has(node.id)) return kids;\n    return kids.filter((kid) => keep.has(kid.id));\n  };\n\n  const visible = React.useMemo(() => {\n    const rows: Row[] = [];\n    const visit = (list: readonly TreeNode[], level: number, parent: string | null, insideMatch: boolean) => {\n      for (const node of list) {\n        rows.push({ node, level, parent });\n        if (isOpen(node)) visit(shownChildren(node, insideMatch), level + 1, node.id, insideMatch || matches.has(node.id));\n      }\n    };\n    visit(filtering ? nodes.filter((node) => keep.has(node.id)) : nodes, 1, null, false);\n    return rows;\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [nodes, childrenOf, expandedSet, filtering, matches, keep, forced, filterClosed, isBranch]);\n\n  /* ------------------------------------ Focus ------------------------------------ */\n\n  const [activeId, setActiveId] = React.useState<string | null>(null);\n  const visibleIds = React.useMemo(() => new Set(visible.map((row) => row.node.id)), [visible]);\n  // The tab stop: the focused node, else its nearest visible ancestor, else the selection, else the first.\n  let tabStop: string | null = null;\n  for (let key = activeId; key !== null; key = info.get(key)?.parent ?? null) {\n    if (visibleIds.has(key)) {\n      tabStop = key;\n      break;\n    }\n  }\n  tabStop ??= selectedList.find((key) => visibleIds.has(key)) ?? visible[0]?.node.id ?? null;\n  const activeParent = tabStop ? (info.get(tabStop)?.parent ?? null) : null;\n\n  const itemRefs = React.useRef(new Map<string, HTMLLIElement>());\n  const [focusRequest, setFocusRequest] = React.useState<{ id: string; tick: number } | null>(null);\n  useIsoLayoutEffect(() => {\n    if (focusRequest) itemRefs.current.get(focusRequest.id)?.focus();\n  }, [focusRequest]);\n  const focusNode = (key: string | undefined) => {\n    if (!key) return;\n    setActiveId(key);\n    setFocusRequest({ id: key, tick: Date.now() });\n  };\n\n  // Children mounted after the first paint animate in; the initial tree renders open.\n  const ready = React.useRef(false);\n  React.useEffect(() => {\n    ready.current = true;\n  }, []);\n\n  /* ----------------------------------- Announcements ----------------------------------- */\n\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const announce = (text: string) => setAnnouncement((current) => (current === text ? `${text}\\u00a0` : text));\n  const lastAnnounced = React.useRef(query);\n  React.useEffect(() => {\n    if (query === lastAnnounced.current) return;\n    lastAnnounced.current = query;\n    if (query) announce(labels.matches(matches.size));\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [query, matches.size]);\n\n  /* ------------------------------------ Actions ------------------------------------ */\n\n  const alive = React.useRef(true);\n  React.useEffect(() => {\n    alive.current = true;\n    return () => {\n      alive.current = false;\n    };\n  }, []);\n\n  const load = async (node: TreeNode) => {\n    if (!onLoadChildren || status.get(node.id) === \"loading\") return;\n    setStatus((current) => new Map(current).set(node.id, \"loading\"));\n    announce(labels.loadingNode(node.label));\n    try {\n      const result = await onLoadChildren(node);\n      if (!alive.current) return;\n      if (Array.isArray(result)) setLoaded((current) => new Map(current).set(node.id, result));\n      setStatus((current) => {\n        const next = new Map(current);\n        next.delete(node.id);\n        return next;\n      });\n      announce(labels.loaded(node.label, Array.isArray(result) ? result.length : (node.children?.length ?? 0)));\n    } catch {\n      if (!alive.current) return;\n      setStatus((current) => new Map(current).set(node.id, \"error\"));\n      announce(labels.loadErrorNode(node.label));\n    }\n  };\n\n  const needsLoad = (node: TreeNode) => !!node.hasChildren && !childrenOf(node) && !!onLoadChildren;\n\n  const setOpen = (node: TreeNode, open: boolean) => {\n    if (!isBranch(node)) return;\n    if (open && needsLoad(node) && status.get(node.id) !== \"loading\") void load(node);\n    if (filtering && forced.has(node.id)) {\n      setFilterClosed((current) => {\n        const next = new Set(current);\n        if (open) next.delete(node.id);\n        else next.add(node.id);\n        return next;\n      });\n      if (!open) return;\n    }\n    if (expandedSet.has(node.id) === open) return;\n    const next = new Set(expandedSet);\n    if (open) next.add(node.id);\n    else next.delete(node.id);\n    setExpanded(next);\n  };\n\n  const toggleOpen = (node: TreeNode) => setOpen(node, !isOpen(node));\n\n  const expandSiblings = (row: Row) => {\n    const siblings = visible.filter((item) => item.parent === row.parent && isBranch(item.node));\n    const next = new Set(expandedSet);\n    for (const sibling of siblings) {\n      next.add(sibling.node.id);\n      if (needsLoad(sibling.node)) void load(sibling.node);\n    }\n    setExpanded(next);\n  };\n\n  const anchor = React.useRef<string | null>(null);\n  const selectable = (node: TreeNode) => selectionMode !== \"none\" && !node.disabled;\n  const choose = (node: TreeNode, mode: \"replace\" | \"toggle\" | \"range\") => {\n    if (!selectable(node)) return;\n    if (selectionMode === \"single\" || mode === \"replace\") {\n      setSelected([node.id]);\n      anchor.current = node.id;\n    } else if (mode === \"toggle\") {\n      const next = new Set(selectedSet);\n      if (!next.delete(node.id)) next.add(node.id);\n      setSelected(order.filter((key) => next.has(key)));\n      anchor.current = node.id;\n    } else {\n      const ids = visible.map((row) => row.node.id);\n      const from = ids.indexOf(anchor.current ?? node.id);\n      const to = ids.indexOf(node.id);\n      const [start, end] = from === -1 ? [to, to] : from < to ? [from, to] : [to, from];\n      const range = visible.slice(start, end + 1).filter((row) => !row.node.disabled).map((row) => row.node.id);\n      setSelected(range);\n    }\n    onSelect?.(node);\n  };\n\n  const toggleCheck = (node: TreeNode) => {\n    if (!checkable || !checks || node.disabled) return;\n    // Check everything that can change, unless all of it already is; locked nodes keep their state.\n    const enabled = (item: TreeNode): TreeNode[] =>\n      item.disabled ? [] : [item, ...(childrenOf(item) ?? []).flatMap(enabled)];\n    const target = !enabled(node).every((item) => {\n      const kids = childrenOf(item);\n      return kids && kids.length ? true : checks.get(item.id) === true;\n    });\n    const next = new Set<string>();\n    checks.forEach((value, key) => {\n      if (value === true) next.add(key);\n    });\n    const apply = (item: TreeNode) => {\n      if (item.disabled) return;\n      if (target) next.add(item.id);\n      else next.delete(item.id);\n      for (const kid of childrenOf(item) ?? []) apply(kid);\n    };\n    apply(node);\n    // A parent is checked exactly when every child is.\n    const normalize = (item: TreeNode): boolean => {\n      const kids = childrenOf(item);\n      if (!kids || !kids.length) return next.has(item.id);\n      const all = kids.map(normalize).every(Boolean);\n      if (all) next.add(item.id);\n      else next.delete(item.id);\n      return all;\n    };\n    for (const root of nodes) normalize(root);\n    const ids = order.filter((key) => next.has(key));\n    if (checkedProp === undefined) setCheckedState(ids);\n    onCheckedChange?.(ids);\n  };\n\n  /* ----------------------------------- Keyboard ----------------------------------- */\n\n  const typeahead = React.useRef({ text: \"\", time: 0 });\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLUListElement>) => {\n    if (event.defaultPrevented) return;\n    const target = event.target as HTMLElement;\n    if (target.getAttribute(\"role\") !== \"treeitem\") return;\n    const current = target.getAttribute(\"data-node-id\");\n    const index = visible.findIndex((row) => row.node.id === current);\n    const row = visible[index];\n    if (!row) return;\n    const { node } = row;\n    const mod = event.metaKey || event.ctrlKey;\n    let handled = true;\n    switch (event.key) {\n      case \"ArrowDown\":\n      case \"ArrowUp\": {\n        const next = visible[Math.max(0, Math.min(visible.length - 1, index + (event.key === \"ArrowDown\" ? 1 : -1)))];\n        if (event.shiftKey && selectionMode === \"multiple\" && next) {\n          anchor.current ??= node.id;\n          choose(next.node, \"range\");\n        }\n        focusNode(next?.node.id);\n        break;\n      }\n      case \"Home\":\n        focusNode(visible[0]?.node.id);\n        break;\n      case \"End\":\n        focusNode(visible[visible.length - 1]?.node.id);\n        break;\n      case \"ArrowRight\":\n        if (isBranch(node)) {\n          if (status.get(node.id) === \"error\") void load(node);\n          else if (!isOpen(node)) setOpen(node, true);\n          else if (visible[index + 1]?.parent === node.id) focusNode(visible[index + 1].node.id);\n        }\n        break;\n      case \"ArrowLeft\":\n        if (isOpen(node)) setOpen(node, false);\n        else focusNode(row.parent ?? undefined);\n        break;\n      case \"Enter\":\n        if (selectable(node)) {\n          choose(node, \"replace\");\n          if (isBranch(node) && expandOnClick) toggleOpen(node);\n        } else if (isBranch(node)) toggleOpen(node);\n        else if (checkable) toggleCheck(node);\n        break;\n      case \" \":\n        if (checkable) toggleCheck(node);\n        else if (selectionMode === \"multiple\") choose(node, \"toggle\");\n        else if (selectable(node)) choose(node, \"replace\");\n        break;\n      case \"*\":\n        expandSiblings(row);\n        break;\n      default:\n        if (mod && (event.key === \"a\" || event.key === \"A\") && selectionMode === \"multiple\") {\n          setSelected(visible.filter((item) => !item.node.disabled).map((item) => item.node.id));\n        } else if (event.key.length === 1 && !mod && !event.altKey && event.key !== \" \") {\n          const now = event.timeStamp;\n          const state = typeahead.current;\n          state.text = now - state.time > 600 ? event.key.toLowerCase() : state.text + event.key.toLowerCase();\n          state.time = now;\n          const repeated = [...state.text].every((char) => char === state.text[0]);\n          const search = repeated ? state.text[0] : state.text;\n          const start = repeated || state.text.length === 1 ? index + 1 : index;\n          for (let step = 0; step < visible.length; step++) {\n            const candidate = visible[(start + step) % visible.length];\n            if (candidate.node.label.toLowerCase().startsWith(search)) {\n              focusNode(candidate.node.id);\n              break;\n            }\n          }\n        } else handled = false;\n    }\n    if (handled) {\n      event.preventDefault();\n      event.stopPropagation();\n    }\n  };\n\n  /* ------------------------------------ Render ------------------------------------ */\n\n  const rowHeight = size === \"sm\" ? \"h-6\" : \"h-7\";\n  const pad = 6;\n  const chevronX = (level: number) => pad + (level - 1) * indent + 8;\n\n  const renderRows = (list: readonly TreeNode[], level: number, insideMatch: boolean) =>\n    list.map((node, position) => {\n      const branch = isBranch(node);\n      const open = isOpen(node);\n      const selected = selectedSet.has(node.id);\n      const checkedValue: TreeCheckedState = checks?.get(node.id) ?? false;\n      const loading = status.get(node.id) === \"loading\";\n      const failed = status.get(node.id) === \"error\";\n      const disabled = !!node.disabled;\n      const match = filtering && matches.has(node.id);\n      const state: TreeNodeState = { level, expanded: open, selected, checked: checkedValue, disabled, loading, match };\n      const icon = typeof node.icon === \"function\" ? node.icon(state) : node.icon;\n      const custom = renderLabel?.(node, state);\n      const isTabStop = node.id === tabStop;\n      const labelId = `${id}-${node.id}-label`;\n      const badgeId = `${id}-${node.id}-badge`;\n      const kids = branch ? shownChildren(node, insideMatch) : [];\n      const childInsideMatch = insideMatch || matches.has(node.id);\n\n      return (\n        <li\n          key={node.id}\n          ref={(element) => {\n            if (element) itemRefs.current.set(node.id, element);\n            else itemRefs.current.delete(node.id);\n          }}\n          role=\"treeitem\"\n          aria-level={level}\n          aria-posinset={position + 1}\n          aria-setsize={list.length}\n          aria-expanded={branch ? open : undefined}\n          aria-selected={selectionMode === \"none\" ? undefined : selected}\n          aria-checked={checkable ? (checkedValue === \"mixed\" ? \"mixed\" : checkedValue) : undefined}\n          aria-disabled={disabled || undefined}\n          aria-busy={loading || undefined}\n          aria-labelledby={node.badge != null ? `${labelId} ${badgeId}` : labelId}\n          tabIndex={isTabStop ? 0 : -1}\n          data-slot=\"tree-view-item\"\n          data-node-id={node.id}\n          data-state={branch ? (open ? \"open\" : \"closed\") : undefined}\n          data-selected={selected || undefined}\n          data-checked={checkable ? String(checkedValue) : undefined}\n          data-disabled={disabled || undefined}\n          data-match={match || undefined}\n          onFocus={(event) => {\n            if (event.target === event.currentTarget) setActiveId(node.id);\n          }}\n          className=\"group/item outline-none\"\n        >\n          <div\n            data-slot=\"tree-view-row\"\n            data-selected={selected || undefined}\n            onClick={(event) => {\n              const part = (event.target as Element).closest(\"[data-tree-part]\")?.getAttribute(\"data-tree-part\");\n              setActiveId(node.id);\n              if (part === \"chevron\") {\n                toggleOpen(node);\n                return;\n              }\n              if (part === \"checkbox\") {\n                toggleCheck(node);\n                return;\n              }\n              const mod = event.metaKey || event.ctrlKey;\n              if (selectable(node)) choose(node, event.shiftKey ? \"range\" : mod ? \"toggle\" : \"replace\");\n              else if (checkable && !branch) toggleCheck(node);\n              if (branch && expandOnClick && !mod && !event.shiftKey) toggleOpen(node);\n            }}\n            className={cn(\n              \"group/row relative flex cursor-default items-center gap-1.5 rounded-lg pr-2 select-none\",\n              rowHeight,\n              size === \"sm\" ? \"text-xs\" : \"text-[13px]\",\n              \"transition-[background-color,box-shadow] duration-150 motion-reduce:transition-none\",\n              \"hover:bg-muted/70 dark:hover:bg-muted/50\",\n              selected &&\n                \"bg-primary/[0.09] text-foreground hover:bg-primary/[0.12] dark:bg-primary/[0.16] dark:hover:bg-primary/20\",\n            )}\n            style={{ paddingLeft: pad + (level - 1) * indent }}\n          >\n            <span\n              data-tree-part={branch ? \"chevron\" : undefined}\n              aria-hidden=\"true\"\n              className=\"flex size-4 shrink-0 items-center justify-center\"\n            >\n              {branch &&\n                (loading ? (\n                  <Loader className=\"size-3.5 text-muted-foreground motion-safe:animate-spin\" stroke={2} />\n                ) : (\n                  <ChevronRight\n                    className={cn(\n                      \"size-3.5 text-muted-foreground/80 transition-transform duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover/row:text-foreground motion-reduce:transition-none\",\n                      open && \"rotate-90\",\n                    )}\n                    stroke={2}\n                  />\n                ))}\n            </span>\n            {checkable && (\n              <span\n                data-tree-part=\"checkbox\"\n                data-slot=\"tree-view-checkbox\"\n                data-state={checkedValue === \"mixed\" ? \"indeterminate\" : checkedValue ? \"checked\" : \"unchecked\"}\n                aria-hidden=\"true\"\n                className={cn(\n                  \"flex size-4 shrink-0 items-center justify-center rounded-[5px] border shadow-xs transition-[background-color,border-color,box-shadow] duration-150 motion-reduce:transition-none\",\n                  checkedValue\n                    ? \"border-primary bg-primary text-primary-foreground\"\n                    : \"border-input bg-card group-hover/row:border-foreground/30\",\n                  disabled && \"opacity-50\",\n                )}\n              >\n                {checkedValue === \"mixed\" ? (\n                  <Minus className=\"size-3\" stroke={3} />\n                ) : checkedValue ? (\n                  <Check className=\"size-3\" stroke={3} />\n                ) : null}\n              </span>\n            )}\n            {icon != null && (\n              <span\n                data-slot=\"tree-view-icon\"\n                aria-hidden=\"true\"\n                className={cn(\n                  \"flex size-4 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4\",\n                  selected && \"text-primary\",\n                  disabled && \"opacity-50\",\n                )}\n              >\n                {icon}\n              </span>\n            )}\n            <span\n              id={labelId}\n              data-slot=\"tree-view-label\"\n              className={cn(\n                \"min-w-0 flex-1 truncate\",\n                disabled ? \"text-muted-foreground\" : \"text-foreground\",\n                filtering && !match && \"text-muted-foreground\",\n              )}\n            >\n              {custom !== undefined ? custom : highlight(node.label, filtering ? query : \"\")}\n            </span>\n            {node.badge != null && (\n              <span id={badgeId} data-slot=\"tree-view-badge\" className=\"ml-auto flex shrink-0 items-center\">\n                {typeof node.badge === \"string\" || typeof node.badge === \"number\" ? (\n                  <span className=\"inline-flex h-5 min-w-5 items-center justify-center rounded-md bg-muted px-1.5 text-[11px] font-medium text-muted-foreground tabular-nums\">\n                    {node.badge}\n                  </span>\n                ) : (\n                  node.badge\n                )}\n              </span>\n            )}\n          </div>\n          {branch && (\n            <Collapse\n              open={open}\n              animate={ready.current}\n              guide={indentGuides ? chevronX(level) - 0.5 : null}\n              guideActive={activeParent === node.id}\n            >\n              <ul role=\"group\" data-slot=\"tree-view-group\">\n                {loading && !kids.length ? (\n                  <li\n                    role=\"none\"\n                    data-slot=\"tree-view-loading\"\n                    className={cn(\"flex items-center gap-1.5 text-xs text-muted-foreground\", rowHeight)}\n                    style={{ paddingLeft: pad + level * indent + 16 + 6 }}\n                  >\n                    <span className=\"relative flex h-1.5 w-24 overflow-hidden rounded-full bg-muted\">\n                      <span className=\"absolute inset-y-0 w-1/2 rounded-full bg-[linear-gradient(90deg,transparent,color-mix(in_oklab,var(--color-foreground)_14%,transparent),transparent)] motion-safe:animate-[tree-view-shimmer_1.1s_ease-in-out_infinite]\" />\n                    </span>\n                    {labels.loading}\n                  </li>\n                ) : failed && !kids.length ? (\n                  <li\n                    role=\"none\"\n                    data-slot=\"tree-view-error\"\n                    className={cn(\"flex items-center gap-2 text-xs\", rowHeight)}\n                    style={{ paddingLeft: pad + level * indent + 16 + 6 }}\n                  >\n                    <AlertCircle className=\"size-3.5 shrink-0 text-rose-600 dark:text-rose-400\" aria-hidden=\"true\" stroke={1.75} />\n                    <span className=\"text-rose-700 dark:text-rose-400\">{labels.loadError}</span>\n                    <button\n                      type=\"button\"\n                      tabIndex={-1}\n                      onClick={() => void load(node)}\n                      className=\"rounded-md px-1.5 py-0.5 font-medium text-foreground underline decoration-foreground/30 underline-offset-2 transition-colors hover:bg-muted hover:decoration-foreground\"\n                    >\n                      {labels.retry}\n                    </button>\n                  </li>\n                ) : (\n                  renderRows(kids, level + 1, childInsideMatch)\n                )}\n              </ul>\n            </Collapse>\n          )}\n        </li>\n      );\n    });\n\n  const roots = filtering ? nodes.filter((node) => keep.has(node.id)) : nodes;\n\n  return (\n    <div data-slot=\"tree-view\" className={cn(\"relative min-w-0\", className)} {...props}>\n      <style href=\"overtrue-tree-view\" precedence=\"default\">\n        {styles}\n      </style>\n      <ul\n        role=\"tree\"\n        aria-label={ariaLabelledBy ? undefined : (ariaLabel ?? labels.tree)}\n        aria-labelledby={ariaLabelledBy}\n        aria-multiselectable={selectionMode === \"multiple\" || undefined}\n        data-slot=\"tree-view-tree\"\n        data-filtering={filtering || undefined}\n        onKeyDown={handleKeyDown}\n        className=\"p-1\"\n      >\n        {roots.length ? (\n          renderRows(roots, 1, false)\n        ) : (\n          <li role=\"none\" data-slot=\"tree-view-empty\" className=\"px-3 py-6 text-center text-[13px] text-muted-foreground\">\n            {filtering ? labels.noMatches : labels.empty}\n          </li>\n        )}\n      </ul>\n      <span className=\"sr-only\" aria-live=\"polite\" aria-atomic=\"true\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/tree-view. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
