{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-expand",
  "title": "Tree expand",
  "description": "File or category tree with spring expand/collapse, indentation guides, a selection highlight that glides between rows, and full arrow-key, Enter and type-ahead navigation.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json"
  ],
  "files": [
    {
      "path": "registry/components/lists/tree-expand.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\nimport { ChevronRight } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { spring } from \"@/lib/goodui-motion\"\n\n// Focus ring on the row only, so a focused folder doesn't outline its whole subtree.\nconst CSS = `\n.pc-tree-expand-item { outline: none }\n.pc-tree-expand-item:focus-visible > .pc-tree-expand-row {\n  box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent);\n}\n`\n\nexport type TreeExpandNode = {\n  /** Unique id across the whole tree; used by `expanded` and `selected`. */\n  id: string\n  /** Plain text of the row, also used for type-ahead. */\n  label: string\n  /** Icon before the label. */\n  icon?: React.ReactNode\n  /** Icon used instead of `icon` while the node is expanded, e.g. an open folder. */\n  openIcon?: React.ReactNode\n  /** Right-aligned extra, e.g. a size or a count. */\n  meta?: React.ReactNode\n  /** Child nodes; a node with children is a folder that can expand. */\n  children?: TreeExpandNode[]\n  /** Cannot be selected, and clicking it or pressing Enter does not toggle it. Still reachable with the arrow keys. */\n  disabled?: boolean\n}\n\nexport type TreeExpandProps = Omit<React.ComponentProps<\"ul\">, \"onSelect\" | \"defaultValue\"> & {\n  /** Top-level nodes. */\n  nodes: TreeExpandNode[]\n  /** Expanded node ids (controlled). */\n  expanded?: string[]\n  /** Node ids expanded on first render (uncontrolled). */\n  defaultExpanded?: string[]\n  /** Called with the new list of expanded ids when a folder opens or closes. */\n  onExpandedChange?: (expanded: string[]) => void\n  /** Selected node id (controlled). */\n  selected?: string | null\n  /** Node id selected on first render (uncontrolled). */\n  defaultSelected?: string | null\n  /** Called with the id and node when a row is clicked or chosen with Enter or Space. */\n  onSelectedChange?: (id: string | null, node: TreeExpandNode | null) => void\n  /** Draw vertical indentation guides. */\n  guides?: boolean\n  /** Pixels per nesting level. */\n  indent?: number\n  /** Clicking a parent row (or pressing Enter on it) also expands or collapses it. */\n  toggleOnSelect?: boolean\n  /** Accessible name of the tree. */\n  label?: string\n}\n\ntype Visible = { node: TreeExpandNode; level: number; parent: string | null }\n\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T) => void) {\n  const [inner, setInner] = React.useState(defaultValue)\n  const controlled = value !== undefined\n  const current = controlled ? value : inner\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next)\n      onChange?.(next)\n    },\n    [controlled, onChange],\n  )\n  return [current, set] as const\n}\n\n/** Tree with spring expand/collapse, indentation guides, a gliding selection and full arrow-key support. */\nexport function TreeExpand({\n  nodes,\n  expanded: expandedProp,\n  defaultExpanded = [],\n  onExpandedChange,\n  selected: selectedProp,\n  defaultSelected = null,\n  onSelectedChange,\n  guides = true,\n  indent = 18,\n  toggleOnSelect = true,\n  label = \"Tree\",\n  className,\n  onKeyDown,\n  ...props\n}: TreeExpandProps) {\n  const reduce = useReducedMotion() ?? false\n  const uid = React.useId()\n  const [expanded, setExpanded] = useControllable(expandedProp, defaultExpanded, onExpandedChange)\n  const [selected, setSelectedRaw] = useControllable<string | null>(selectedProp, defaultSelected, undefined)\n  const [focused, setFocused] = React.useState<string | null>(null)\n  const items = React.useRef(new Map<string, HTMLLIElement>())\n  const typeahead = React.useRef({ text: \"\", at: 0 })\n\n  const open = React.useMemo(() => new Set(expanded), [expanded])\n\n  // Right-to-left mirrors the arrow keys and the chevron; read after mount so SSR output is unchanged.\n  const [rtl, setRtl] = React.useState(false)\n  React.useEffect(() => {\n    const first = items.current.values().next().value\n    if (first) setRtl(getComputedStyle(first).direction === \"rtl\")\n  }, [])\n\n  const visible = React.useMemo(() => {\n    const out: Visible[] = []\n    const walk = (list: TreeExpandNode[], level: number, parent: string | null) => {\n      for (const node of list) {\n        out.push({ node, level, parent })\n        if (node.children?.length && open.has(node.id)) walk(node.children, level + 1, node.id)\n      }\n    }\n    walk(nodes, 1, null)\n    return out\n  }, [nodes, open])\n\n  const has = (id: string | null) => !!id && visible.some((v) => v.node.id === id)\n  const tabbable = has(focused) ? focused : has(selected) ? selected : (visible[0]?.node.id ?? null)\n\n  const select = (node: TreeExpandNode) => {\n    if (node.disabled) return\n    setSelectedRaw(node.id)\n    onSelectedChange?.(node.id, node)\n  }\n  const toggle = (id: string, force?: boolean) => {\n    const isOpen = open.has(id)\n    const next = force ?? !isOpen\n    if (next === isOpen) return\n    setExpanded(next ? [...expanded, id] : expanded.filter((x) => x !== id))\n  }\n  const focusId = (id: string) => {\n    setFocused(id)\n    items.current.get(id)?.focus()\n  }\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLUListElement>) => {\n    onKeyDown?.(e)\n    if (e.defaultPrevented || !tabbable) return\n    const i = visible.findIndex((v) => v.node.id === tabbable)\n    const cur = visible[i]\n    if (!cur) return\n    const focusAt = (j: number) => {\n      const v = visible[j]\n      if (v) focusId(v.node.id)\n    }\n    const parent = !!cur.node.children?.length\n    // Disabled folders can be focused but never expanded or collapsed.\n    const canToggle = parent && !cur.node.disabled\n    const isRtl = getComputedStyle(e.currentTarget).direction === \"rtl\"\n    const key = e.key === \"ArrowRight\" && isRtl ? \"ArrowLeft\" : e.key === \"ArrowLeft\" && isRtl ? \"ArrowRight\" : e.key\n    let handled = true\n    switch (key) {\n      case \"ArrowDown\":\n        if (i < visible.length - 1) focusAt(i + 1)\n        break\n      case \"ArrowUp\":\n        if (i > 0) focusAt(i - 1)\n        break\n      case \"Home\":\n        focusAt(0)\n        break\n      case \"End\":\n        focusAt(visible.length - 1)\n        break\n      case \"ArrowRight\":\n        if (canToggle && !open.has(cur.node.id)) toggle(cur.node.id, true)\n        else if (parent && open.has(cur.node.id)) focusAt(i + 1)\n        break\n      case \"ArrowLeft\":\n        if (canToggle && open.has(cur.node.id)) toggle(cur.node.id, false)\n        else if (cur.parent) focusId(cur.parent)\n        break\n      case \"Enter\":\n      case \" \":\n        select(cur.node)\n        if (parent && toggleOnSelect && !cur.node.disabled) toggle(cur.node.id)\n        break\n      default: {\n        if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey) {\n          handled = false\n          break\n        }\n        // Type-ahead: jump to the next visible item starting with the typed letters.\n        const now = e.timeStamp\n        const t = typeahead.current\n        t.text = now - t.at > 600 ? e.key.toLowerCase() : t.text + e.key.toLowerCase()\n        t.at = now\n        const order = [...visible.slice(i + (t.text.length === 1 ? 1 : 0)), ...visible.slice(0, i + 1)]\n        const hit = order.find((v) => v.node.label.toLowerCase().startsWith(t.text))\n        if (hit) focusId(hit.node.id)\n      }\n    }\n    if (handled) {\n      e.preventDefault()\n      e.stopPropagation()\n    }\n  }\n\n  const height = reduce ? { duration: 0 } : { type: \"spring\" as const, bounce: 0, duration: 0.34 }\n  const glide = reduce ? { duration: 0 } : spring.snap\n\n  const renderNodes = (list: TreeExpandNode[], level: number): React.ReactNode =>\n    list.map((node) => {\n      const isParent = !!node.children?.length\n      const isOpen = isParent && open.has(node.id)\n      const isSelected = selected === node.id\n      const icon = isOpen && node.openIcon ? node.openIcon : node.icon\n      return (\n        <li\n          key={node.id}\n          ref={(el) => {\n            if (el) items.current.set(node.id, el)\n            else items.current.delete(node.id)\n          }}\n          role=\"treeitem\"\n          aria-level={level}\n          aria-expanded={isParent ? isOpen : undefined}\n          aria-selected={isSelected}\n          aria-disabled={node.disabled || undefined}\n          tabIndex={tabbable === node.id ? 0 : -1}\n          onFocus={(e) => {\n            if (e.target === e.currentTarget) setFocused(node.id)\n          }}\n          className=\"pc-tree-expand-item\"\n        >\n          <div\n            className={cn(\n              \"pc-tree-expand-row relative flex h-8 cursor-pointer items-center gap-1.5 rounded-md pe-2 text-sm transition-colors select-none\",\n              !isSelected && \"hover:bg-muted/60\",\n              isSelected ? \"font-medium text-foreground\" : \"text-foreground/80\",\n              node.disabled && \"cursor-not-allowed opacity-50\",\n            )}\n            style={{ paddingInlineStart: (level - 1) * indent + 6 }}\n            onClick={(e) => {\n              e.stopPropagation()\n              focusId(node.id)\n              select(node)\n              if (isParent && toggleOnSelect && !node.disabled) toggle(node.id)\n            }}\n          >\n            {isSelected && (\n              <motion.span\n                layoutId={`${uid}-selection`}\n                transition={glide}\n                className=\"absolute inset-0 rounded-md bg-primary/10 ring-1 ring-primary/15 ring-inset dark:bg-primary/15\"\n                aria-hidden=\"true\"\n              />\n            )}\n            <span\n              className={cn(\"relative flex size-4 shrink-0 items-center justify-center text-muted-foreground\", !isParent && \"invisible\")}\n              aria-hidden=\"true\"\n              onClick={(e) => {\n                if (toggleOnSelect || !isParent || node.disabled) return\n                e.stopPropagation()\n                focusId(node.id)\n                toggle(node.id)\n              }}\n            >\n              <motion.span initial={false} animate={{ rotate: isOpen ? (rtl ? -90 : 90) : 0 }} transition={glide} className=\"flex\">\n                <ChevronRight className=\"size-3.5 rtl:-scale-x-100\" />\n              </motion.span>\n            </span>\n            {icon && (\n              <span className=\"relative flex shrink-0 text-muted-foreground [&_svg]:size-4\" aria-hidden=\"true\">\n                {icon}\n              </span>\n            )}\n            <span className=\"relative min-w-0 flex-1 truncate\">{node.label}</span>\n            {node.meta != null && <span className=\"relative shrink-0 text-xs text-foreground/65 tabular-nums\">{node.meta}</span>}\n          </div>\n          {isParent && (\n            <AnimatePresence initial={false}>\n              {isOpen && (\n                <motion.ul\n                  key=\"group\"\n                  role=\"group\"\n                  initial={{ height: 0, opacity: 0 }}\n                  animate={{ height: \"auto\", opacity: 1, transition: { height, opacity: { duration: reduce ? 0 : 0.2 } } }}\n                  exit={{ height: 0, opacity: 0, transition: { height, opacity: { duration: reduce ? 0 : 0.14 } } }}\n                  className={cn(\n                    \"relative overflow-hidden\",\n                    guides && \"before:absolute before:top-0 before:bottom-1 before:start-(--pc-guide) before:w-px before:bg-border\",\n                  )}\n                  style={{ [\"--pc-guide\" as string]: `${(level - 1) * indent + 13.5}px` }}\n                >\n                  {renderNodes(node.children!, level + 1)}\n                </motion.ul>\n              )}\n            </AnimatePresence>\n          )}\n        </li>\n      )\n    })\n\n  return (\n    <>\n      <style href=\"pc-tree-expand\" precedence=\"default\">\n        {CSS}\n      </style>\n      <ul role=\"tree\" aria-label={label} className={cn(\"w-full\", className)} onKeyDown={handleKeyDown} {...props}>\n        {renderNodes(nodes, 1)}\n      </ul>\n    </>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/tree-expand.tsx"
    }
  ],
  "categories": [
    "components",
    "lists"
  ],
  "type": "registry:component"
}