{
  "schemaVersion": 1,
  "target": "react",
  "name": "file-tree",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "File Tree",
  "description": "The files an agent changed as a folder tree with expand and collapse, full tree keyboard navigation, and added, modified, deleted, or renamed markers with line counts.",
  "tags": [
    "ai",
    "agent",
    "files",
    "tree",
    "diff",
    "changes",
    "code"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/file-tree",
  "props": [
    {
      "name": "nodes",
      "type": "{ name, children?, change?, additions?, deletions? }[]",
      "description": "The tree. Folders have children; files may carry a change of added, modified, deleted, or renamed and line counts."
    },
    {
      "name": "defaultExpanded",
      "type": "string[] | \"all\"",
      "default": "\"all\"",
      "description": "Folder paths that start open, such as src/billing."
    },
    {
      "name": "expanded / onExpandedChange",
      "type": "string[] / (paths) => void",
      "description": "Controlled open folders."
    },
    {
      "name": "selectedPath / onSelect",
      "type": "string | null / (path, node) => void",
      "description": "Makes files selectable; Enter, Space, or a click chooses a file."
    },
    {
      "name": "label",
      "type": "string",
      "default": "\"Changed files\"",
      "description": "Accessible name of the tree."
    }
  ],
  "accessibility": [
    "Uses role tree and treeitem with aria-level, aria-setsize, aria-posinset, aria-expanded on folders, and aria-selected on files when selection is enabled.",
    "One roving tab stop. Up and Down move, Right opens a folder or enters it, Left closes it or moves to the parent, Home and End jump, Enter and Space toggle or select, and typing a letter jumps to the next matching name.",
    "Change markers are letters (A, M, D, R) with an sr-only word, deleted files are struck through, and line counts read as lines added and lines removed; color is never the only signal.",
    "Opening and closing folders is instant by design (a frequent, keyboard driven action); only the chevron rotates, and not under reduced motion."
  ],
  "states": [
    "expanded",
    "collapsed",
    "selected",
    "added",
    "modified",
    "deleted",
    "renamed"
  ],
  "files": [
    {
      "path": "agent/file-tree.tsx",
      "content": "\"use client\";\n\nimport { type KeyboardEvent, useMemo, useRef, useState } from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nexport type FileChange = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\nexport interface FileTreeNode {\n  /** File or folder name, without slashes. */\n  name: string;\n  /** Present on folders, even when empty. */\n  children?: FileTreeNode[];\n  /** What the agent did to the file. Folders leave it unset. */\n  change?: FileChange;\n  /** Lines added. */\n  additions?: number;\n  /** Lines removed. */\n  deletions?: number;\n}\n\nexport interface FileTreeProps {\n  nodes: FileTreeNode[];\n  /** Folder paths that start open, like `src/components`. Defaults to every folder. */\n  defaultExpanded?: string[] | \"all\";\n  /** Controlled open folders. Pair with `onExpandedChange`. */\n  expanded?: string[];\n  onExpandedChange?: (expanded: string[]) => void;\n  /** Controlled selected file path. */\n  selectedPath?: string | null;\n  /** Called when a file is chosen with a click, Enter, or Space. Makes the tree selectable. */\n  onSelect?: (path: string, node: FileTreeNode) => void;\n  /** Accessible name of the tree. */\n  label?: string;\n  className?: string;\n}\n\nconst changes: Record<FileChange, { letter: string; label: string; tone: string }> = {\n  added: { letter: \"A\", label: \"added\", tone: \"text-emerald-600 dark:text-emerald-400\" },\n  modified: { letter: \"M\", label: \"modified\", tone: \"text-amber-600 dark:text-amber-400\" },\n  deleted: { letter: \"D\", label: \"deleted\", tone: \"text-red-600 dark:text-red-400\" },\n  renamed: { letter: \"R\", label: \"renamed\", tone: \"text-sky-600 dark:text-sky-400\" },\n};\n\ninterface Row {\n  node: FileTreeNode;\n  path: string;\n  parent: string | null;\n  level: number;\n  setSize: number;\n  position: number;\n  folder: boolean;\n  open: boolean;\n}\n\nfunction allFolders(nodes: FileTreeNode[], prefix = \"\"): string[] {\n  return nodes.flatMap((node) => {\n    if (!node.children) return [];\n    const path = prefix + node.name;\n    return [path, ...allFolders(node.children, `${path}/`)];\n  });\n}\n\nfunction visibleRows(nodes: FileTreeNode[], open: Set<string>, parent: string | null = null, level = 1): Row[] {\n  return nodes.flatMap((node, index) => {\n    const path = parent ? `${parent}/${node.name}` : node.name;\n    const folder = node.children !== undefined;\n    const isOpen = folder && open.has(path);\n    const row: Row = { node, path, parent, level, setSize: nodes.length, position: index + 1, folder, open: isOpen };\n    return isOpen ? [row, ...visibleRows(node.children ?? [], open, path, level + 1)] : [row];\n  });\n}\n\nfunction changedFiles(node: FileTreeNode): number {\n  if (!node.children) return node.change ? 1 : 0;\n  return node.children.reduce((sum, child) => sum + changedFiles(child), 0);\n}\n\n/**\n * The files an agent changed, as a folder tree. Folders open and close with a click or the arrow\n * keys; each file shows an A, M, D, or R marker and its added and removed line counts.\n */\nexport function FileTree({\n  nodes,\n  defaultExpanded = \"all\",\n  expanded: expandedProp,\n  onExpandedChange,\n  selectedPath,\n  onSelect,\n  label = \"Changed files\",\n  className,\n}: FileTreeProps) {\n  const [uncontrolled, setUncontrolled] = useState<string[]>(() =>\n    defaultExpanded === \"all\" ? allFolders(nodes) : defaultExpanded,\n  );\n  const expanded = expandedProp ?? uncontrolled;\n  const open = useMemo(() => new Set(expanded), [expanded]);\n  const rows = useMemo(() => visibleRows(nodes, open), [nodes, open]);\n  const [internalSelected, setInternalSelected] = useState<string | null>(null);\n  const selected = selectedPath !== undefined ? selectedPath : internalSelected;\n  const selectable = onSelect !== undefined || selectedPath !== undefined;\n  const [focused, setFocused] = useState<string | null>(null);\n  const items = useRef(new Map<string, HTMLLIElement>());\n\n  // The roving tab stop: the focused row, else the selected file, else the first row.\n  const tabStop = rows.find((row) => row.path === focused)?.path ?? rows.find((row) => row.path === selected)?.path ?? rows[0]?.path;\n\n  function setExpanded(next: string[]) {\n    if (expandedProp === undefined) setUncontrolled(next);\n    onExpandedChange?.(next);\n  }\n\n  function toggle(path: string, force?: boolean) {\n    const isOpen = open.has(path);\n    const next = force ?? !isOpen;\n    if (next === isOpen) return;\n    setExpanded(next ? [...expanded, path] : expanded.filter((item) => item !== path));\n  }\n\n  function focus(path: string | undefined) {\n    if (!path) return;\n    setFocused(path);\n    items.current.get(path)?.focus();\n  }\n\n  function choose(row: Row) {\n    if (row.folder) {\n      toggle(row.path);\n      return;\n    }\n    if (!selectable) return;\n    if (selectedPath === undefined) setInternalSelected(row.path);\n    onSelect?.(row.path, row.node);\n  }\n\n  function onKeyDown(event: KeyboardEvent<HTMLLIElement>, row: Row, index: number) {\n    let handled = true;\n    switch (event.key) {\n      case \"ArrowDown\":\n        focus(rows[index + 1]?.path);\n        break;\n      case \"ArrowUp\":\n        focus(rows[index - 1]?.path);\n        break;\n      case \"Home\":\n        focus(rows[0]?.path);\n        break;\n      case \"End\":\n        focus(rows[rows.length - 1]?.path);\n        break;\n      case \"ArrowRight\":\n        if (row.folder && !row.open) toggle(row.path, true);\n        else if (row.folder && row.node.children?.length) focus(rows[index + 1]?.path);\n        break;\n      case \"ArrowLeft\":\n        if (row.folder && row.open) toggle(row.path, false);\n        else if (row.parent) focus(row.parent);\n        break;\n      case \"Enter\":\n      case \" \":\n        choose(row);\n        break;\n      default:\n        // Type-ahead: jump to the next visible row whose name starts with the typed character.\n        if (event.key.length === 1 && /\\S/.test(event.key) && !event.metaKey && !event.ctrlKey && !event.altKey) {\n          const key = event.key.toLowerCase();\n          const ordered = [...rows.slice(index + 1), ...rows.slice(0, index)];\n          focus(ordered.find((item) => item.node.name.toLowerCase().startsWith(key))?.path);\n        } else handled = false;\n    }\n    if (handled) {\n      event.preventDefault();\n      event.stopPropagation();\n    }\n  }\n\n  return (\n    <ul role=\"tree\" aria-label={label} className={cx(\"grid text-sm\", className)}>\n      {rows.map((row, index) => {\n        const change = row.node.change ? changes[row.node.change] : undefined;\n        const isSelected = selectable && !row.folder && row.path === selected;\n        const hidden = row.folder && !row.open ? changedFiles(row.node) : 0;\n        return (\n          <li\n            key={row.path}\n            ref={(element) => {\n              if (element) items.current.set(row.path, element);\n              else items.current.delete(row.path);\n            }}\n            role=\"treeitem\"\n            aria-level={row.level}\n            aria-setsize={row.setSize}\n            aria-posinset={row.position}\n            aria-expanded={row.folder ? row.open : undefined}\n            aria-selected={selectable && !row.folder ? isSelected : undefined}\n            tabIndex={row.path === tabStop ? 0 : -1}\n            onFocus={() => setFocused(row.path)}\n            onKeyDown={(event) => onKeyDown(event, row, index)}\n            onClick={() => {\n              setFocused(row.path);\n              choose(row);\n            }}\n            data-change={row.node.change}\n            className={cx(\n              \"group relative flex h-7 cursor-pointer items-center gap-1.5 rounded-md pr-2 select-none\",\n              \"transition-colors duration-150 ease-out motion-reduce:transition-none\",\n              isSelected\n                ? \"bg-zinc-950/[0.06] dark:bg-white/[0.09]\"\n                : \"hover:bg-zinc-950/[0.04] dark:hover:bg-white/[0.06]\",\n              \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500\",\n            )}\n            style={{ paddingLeft: `${(row.level - 1) * 16 + 6}px` }}\n          >\n            {/* Indent guides: one hairline per ancestor folder. */}\n            {Array.from({ length: row.level - 1 }, (_, depth) => (\n              <span\n                key={depth}\n                aria-hidden=\"true\"\n                className=\"absolute inset-y-0 w-px bg-zinc-950/[0.07] dark:bg-white/[0.08]\"\n                style={{ left: `${depth * 16 + 13.5}px` }}\n              />\n            ))}\n            <span aria-hidden=\"true\" className=\"flex size-4 shrink-0 items-center justify-center text-zinc-400 dark:text-zinc-500\">\n              {row.folder ? (\n                <svg\n                  viewBox=\"0 0 16 16\"\n                  fill=\"none\"\n                  className={cx(\n                    \"size-3.5 transition-[rotate,color] duration-150 ease-out motion-reduce:transition-none group-hover:text-zinc-600 dark:group-hover:text-zinc-300\",\n                    row.open && \"rotate-90\",\n                  )}\n                >\n                  <path d=\"m6.25 4.5 3.5 3.5-3.5 3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                </svg>\n              ) : null}\n            </span>\n            <TreeIcon folder={row.folder} open={row.open} />\n            <span\n              className={cx(\n                \"min-w-0 flex-1 truncate font-mono text-[13px]\",\n                row.node.change === \"deleted\"\n                  ? \"text-zinc-500 line-through decoration-zinc-500/60\"\n                  : row.folder\n                    ? \"text-zinc-700 dark:text-zinc-300\"\n                    : \"text-zinc-950 dark:text-white\",\n              )}\n            >\n              {row.node.name}\n            </span>\n            {hidden > 0 ? (\n              <span className=\"shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums\">\n                {hidden} {hidden === 1 ? \"file\" : \"files\"}\n              </span>\n            ) : null}\n            {!row.folder && (row.node.additions || row.node.deletions) ? (\n              <span className=\"flex shrink-0 gap-1.5 font-mono text-[11px] tabular-nums\">\n                {row.node.additions ? (\n                  <span className=\"text-emerald-600 dark:text-emerald-400\">\n                    +{row.node.additions}\n                    <span className=\"sr-only\"> lines added</span>\n                  </span>\n                ) : null}\n                {row.node.deletions ? (\n                  <span className=\"text-red-600 dark:text-red-400\">\n                    −{row.node.deletions}\n                    <span className=\"sr-only\"> lines removed</span>\n                  </span>\n                ) : null}\n              </span>\n            ) : null}\n            {change ? (\n              <span className={cx(\"w-3 shrink-0 text-center font-mono text-[11px] font-semibold\", change.tone)} title={change.label}>\n                <span aria-hidden=\"true\">{change.letter}</span>\n                <span className=\"sr-only\">, {change.label}</span>\n              </span>\n            ) : !row.folder ? (\n              <span aria-hidden=\"true\" className=\"w-3 shrink-0\" />\n            ) : null}\n          </li>\n        );\n      })}\n    </ul>\n  );\n}\n\nfunction TreeIcon({ folder, open }: { folder: boolean; open: boolean }) {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 16 16\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.25\"\n      strokeLinejoin=\"round\"\n      strokeLinecap=\"round\"\n      className=\"size-4 shrink-0 text-zinc-500\"\n    >\n      {folder ? (\n        open ? (\n          <path d=\"M2 12.5V4.25c0-.41.34-.75.75-.75h3.1l1.4 1.5h5.5c.41 0 .75.34.75.75V7M2 12.5l1.55-4.9a.75.75 0 0 1 .72-.53h9.48a.5.5 0 0 1 .48.65L12.9 12a.75.75 0 0 1-.72.5H2Z\" />\n        ) : (\n          <path d=\"M2 4.25c0-.41.34-.75.75-.75h3.1l1.4 1.5h6c.41 0 .75.34.75.75v6.5c0 .41-.34.75-.75.75H2.75a.75.75 0 0 1-.75-.75V4.25Z\" />\n        )\n      ) : (\n        <>\n          <path d=\"M4 1.75h5l3 3v9.5H4V1.75Z\" />\n          <path d=\"M9 1.75v3h3\" />\n        </>\n      )}\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { FileTree, type FileTreeNode } from \"@/components/shaken/agent/file-tree\";\n\nconst changes: FileTreeNode[] = [\n  {\n    name: \"src\",\n    children: [\n      {\n        name: \"billing\",\n        children: [\n          { name: \"invoice.ts\", change: \"modified\", additions: 48, deletions: 12 },\n          { name: \"proration.ts\", change: \"added\", additions: 96 },\n          { name: \"legacy-tax.ts\", change: \"deleted\", deletions: 141 },\n        ],\n      },\n      {\n        name: \"components\",\n        children: [\n          { name: \"PlanPicker.tsx\", change: \"modified\", additions: 22, deletions: 9 },\n          { name: \"UsageMeter.tsx\", change: \"renamed\", additions: 3, deletions: 3 },\n        ],\n      },\n      { name: \"routes.ts\", change: \"modified\", additions: 4, deletions: 1 },\n    ],\n  },\n  {\n    name: \"tests\",\n    children: [{ name: \"proration.test.ts\", change: \"added\", additions: 74 }],\n  },\n  { name: \"package.json\", change: \"modified\", additions: 1, deletions: 1 },\n];\n\nexport default function FileTreeExample() {\n  const [selected, setSelected] = useState<string | null>(\"src/billing/proration.ts\");\n  return (\n    <div className=\"w-full max-w-sm overflow-hidden rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\">\n      <div className=\"flex items-baseline justify-between gap-3 border-b border-zinc-950/[0.07] px-4 py-3 dark:border-white/[0.08]\">\n        <p className=\"text-sm font-semibold text-zinc-950 dark:text-white\">8 files changed</p>\n        <p className=\"font-mono text-xs tabular-nums\">\n          <span className=\"text-emerald-600 dark:text-emerald-400\">+248</span>{\" \"}\n          <span className=\"text-red-600 dark:text-red-400\">−167</span>\n        </p>\n      </div>\n      <FileTree nodes={changes} selectedPath={selected} onSelect={setSelected} className=\"p-1.5\" />\n    </div>\n  );\n}\n"
  }
}
