Skip to content
Shaken UI
Sign in

File Tree

Save

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.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

File Tree preview

8 files changed

+248 โˆ’167

  • src
  • billing
  • invoice.ts+48 lines addedโˆ’12 lines removed, modified
  • proration.ts+96 lines added, added
  • legacy-tax.tsโˆ’141 lines removed, deleted
  • components
  • PlanPicker.tsx+22 lines addedโˆ’9 lines removed, modified
  • UsageMeter.tsx+3 lines addedโˆ’3 lines removed, renamed
  • routes.ts+4 lines addedโˆ’1 lines removed, modified
  • tests
  • proration.test.ts+74 lines added, added
  • package.json+1 lines addedโˆ’1 lines removed, modified

Installation

npx @shakenui/cli add file-tree

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add file-tree --dry-run

Usage

file-tree-example.tsx
"use client";

import { useState } from "react";
import { FileTree, type FileTreeNode } from "@/components/shaken/agent/file-tree";

const changes: FileTreeNode[] = [
  {
    name: "src",
    children: [
      {
        name: "billing",
        children: [
          { name: "invoice.ts", change: "modified", additions: 48, deletions: 12 },
          { name: "proration.ts", change: "added", additions: 96 },
          { name: "legacy-tax.ts", change: "deleted", deletions: 141 },
        ],
      },
      {
        name: "components",
        children: [
          { name: "PlanPicker.tsx", change: "modified", additions: 22, deletions: 9 },
          { name: "UsageMeter.tsx", change: "renamed", additions: 3, deletions: 3 },
        ],
      },
      { name: "routes.ts", change: "modified", additions: 4, deletions: 1 },
    ],
  },
  {
    name: "tests",
    children: [{ name: "proration.test.ts", change: "added", additions: 74 }],
  },
  { name: "package.json", change: "modified", additions: 1, deletions: 1 },
];

export default function FileTreeExample() {
  const [selected, setSelected] = useState<string | null>("src/billing/proration.ts");
  return (
    <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)]">
      <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]">
        <p className="text-sm font-semibold text-zinc-950 dark:text-white">8 files changed</p>
        <p className="font-mono text-xs tabular-nums">
          <span className="text-emerald-600 dark:text-emerald-400">+248</span>{" "}
          <span className="text-red-600 dark:text-red-400">โˆ’167</span>
        </p>
      </div>
      <FileTree nodes={changes} selectedPath={selected} onSelect={setSelected} className="p-1.5" />
    </div>
  );
}

API

PropTypeDefaultDescription
nodes{ name, children?, change?, additions?, deletions? }[]โ€”The tree. Folders have children; files may carry a change of added, modified, deleted, or renamed and line counts.
defaultExpandedstring[] | "all""all"Folder paths that start open, such as src/billing.
expanded / onExpandedChangestring[] / (paths) => voidโ€”Controlled open folders.
selectedPath / onSelectstring | null / (path, node) => voidโ€”Makes files selectable; Enter, Space, or a click chooses a file.
labelstring"Changed files"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.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/file-tree.tsxfile-tree
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/file-tree/0.1.0.json.

agent/file-tree.tsxShow
agent/file-tree.tsx
"use client";

import { type KeyboardEvent, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

export type FileChange = "added" | "modified" | "deleted" | "renamed";

export interface FileTreeNode {
  /** File or folder name, without slashes. */
  name: string;
  /** Present on folders, even when empty. */
  children?: FileTreeNode[];
  /** What the agent did to the file. Folders leave it unset. */
  change?: FileChange;
  /** Lines added. */
  additions?: number;
  /** Lines removed. */
  deletions?: number;
}

export interface FileTreeProps {
  nodes: FileTreeNode[];
  /** Folder paths that start open, like `src/components`. Defaults to every folder. */
  defaultExpanded?: string[] | "all";
  /** Controlled open folders. Pair with `onExpandedChange`. */
  expanded?: string[];
  onExpandedChange?: (expanded: string[]) => void;
  /** Controlled selected file path. */
  selectedPath?: string | null;
  /** Called when a file is chosen with a click, Enter, or Space. Makes the tree selectable. */
  onSelect?: (path: string, node: FileTreeNode) => void;
  /** Accessible name of the tree. */
  label?: string;
  className?: string;
}

const changes: Record<FileChange, { letter: string; label: string; tone: string }> = {
  added: { letter: "A", label: "added", tone: "text-emerald-600 dark:text-emerald-400" },
  modified: { letter: "M", label: "modified", tone: "text-amber-600 dark:text-amber-400" },
  deleted: { letter: "D", label: "deleted", tone: "text-red-600 dark:text-red-400" },
  renamed: { letter: "R", label: "renamed", tone: "text-sky-600 dark:text-sky-400" },
};

interface Row {
  node: FileTreeNode;
  path: string;
  parent: string | null;
  level: number;
  setSize: number;
  position: number;
  folder: boolean;
  open: boolean;
}

function allFolders(nodes: FileTreeNode[], prefix = ""): string[] {
  return nodes.flatMap((node) => {
    if (!node.children) return [];
    const path = prefix + node.name;
    return [path, ...allFolders(node.children, `${path}/`)];
  });
}

function visibleRows(nodes: FileTreeNode[], open: Set<string>, parent: string | null = null, level = 1): Row[] {
  return nodes.flatMap((node, index) => {
    const path = parent ? `${parent}/${node.name}` : node.name;
    const folder = node.children !== undefined;
    const isOpen = folder && open.has(path);
    const row: Row = { node, path, parent, level, setSize: nodes.length, position: index + 1, folder, open: isOpen };
    return isOpen ? [row, ...visibleRows(node.children ?? [], open, path, level + 1)] : [row];
  });
}

function changedFiles(node: FileTreeNode): number {
  if (!node.children) return node.change ? 1 : 0;
  return node.children.reduce((sum, child) => sum + changedFiles(child), 0);
}

/**
 * The files an agent changed, as a folder tree. Folders open and close with a click or the arrow
 * keys; each file shows an A, M, D, or R marker and its added and removed line counts.
 */
export function FileTree({
  nodes,
  defaultExpanded = "all",
  expanded: expandedProp,
  onExpandedChange,
  selectedPath,
  onSelect,
  label = "Changed files",
  className,
}: FileTreeProps) {
  const [uncontrolled, setUncontrolled] = useState<string[]>(() =>
    defaultExpanded === "all" ? allFolders(nodes) : defaultExpanded,
  );
  const expanded = expandedProp ?? uncontrolled;
  const open = useMemo(() => new Set(expanded), [expanded]);
  const rows = useMemo(() => visibleRows(nodes, open), [nodes, open]);
  const [internalSelected, setInternalSelected] = useState<string | null>(null);
  const selected = selectedPath !== undefined ? selectedPath : internalSelected;
  const selectable = onSelect !== undefined || selectedPath !== undefined;
  const [focused, setFocused] = useState<string | null>(null);
  const items = useRef(new Map<string, HTMLLIElement>());

  // The roving tab stop: the focused row, else the selected file, else the first row.
  const tabStop = rows.find((row) => row.path === focused)?.path ?? rows.find((row) => row.path === selected)?.path ?? rows[0]?.path;

  function setExpanded(next: string[]) {
    if (expandedProp === undefined) setUncontrolled(next);
    onExpandedChange?.(next);
  }

  function toggle(path: string, force?: boolean) {
    const isOpen = open.has(path);
    const next = force ?? !isOpen;
    if (next === isOpen) return;
    setExpanded(next ? [...expanded, path] : expanded.filter((item) => item !== path));
  }

  function focus(path: string | undefined) {
    if (!path) return;
    setFocused(path);
    items.current.get(path)?.focus();
  }

  function choose(row: Row) {
    if (row.folder) {
      toggle(row.path);
      return;
    }
    if (!selectable) return;
    if (selectedPath === undefined) setInternalSelected(row.path);
    onSelect?.(row.path, row.node);
  }

  function onKeyDown(event: KeyboardEvent<HTMLLIElement>, row: Row, index: number) {
    let handled = true;
    switch (event.key) {
      case "ArrowDown":
        focus(rows[index + 1]?.path);
        break;
      case "ArrowUp":
        focus(rows[index - 1]?.path);
        break;
      case "Home":
        focus(rows[0]?.path);
        break;
      case "End":
        focus(rows[rows.length - 1]?.path);
        break;
      case "ArrowRight":
        if (row.folder && !row.open) toggle(row.path, true);
        else if (row.folder && row.node.children?.length) focus(rows[index + 1]?.path);
        break;
      case "ArrowLeft":
        if (row.folder && row.open) toggle(row.path, false);
        else if (row.parent) focus(row.parent);
        break;
      case "Enter":
      case " ":
        choose(row);
        break;
      default:
        // Type-ahead: jump to the next visible row whose name starts with the typed character.
        if (event.key.length === 1 && /\S/.test(event.key) && !event.metaKey && !event.ctrlKey && !event.altKey) {
          const key = event.key.toLowerCase();
          const ordered = [...rows.slice(index + 1), ...rows.slice(0, index)];
          focus(ordered.find((item) => item.node.name.toLowerCase().startsWith(key))?.path);
        } else handled = false;
    }
    if (handled) {
      event.preventDefault();
      event.stopPropagation();
    }
  }

  return (
    <ul role="tree" aria-label={label} className={cx("grid text-sm", className)}>
      {rows.map((row, index) => {
        const change = row.node.change ? changes[row.node.change] : undefined;
        const isSelected = selectable && !row.folder && row.path === selected;
        const hidden = row.folder && !row.open ? changedFiles(row.node) : 0;
        return (
          <li
            key={row.path}
            ref={(element) => {
              if (element) items.current.set(row.path, element);
              else items.current.delete(row.path);
            }}
            role="treeitem"
            aria-level={row.level}
            aria-setsize={row.setSize}
            aria-posinset={row.position}
            aria-expanded={row.folder ? row.open : undefined}
            aria-selected={selectable && !row.folder ? isSelected : undefined}
            tabIndex={row.path === tabStop ? 0 : -1}
            onFocus={() => setFocused(row.path)}
            onKeyDown={(event) => onKeyDown(event, row, index)}
            onClick={() => {
              setFocused(row.path);
              choose(row);
            }}
            data-change={row.node.change}
            className={cx(
              "group relative flex h-7 cursor-pointer items-center gap-1.5 rounded-md pr-2 select-none",
              "transition-colors duration-150 ease-out motion-reduce:transition-none",
              isSelected
                ? "bg-zinc-950/[0.06] dark:bg-white/[0.09]"
                : "hover:bg-zinc-950/[0.04] dark:hover:bg-white/[0.06]",
              "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
            )}
            style={{ paddingLeft: `${(row.level - 1) * 16 + 6}px` }}
          >
            {/* Indent guides: one hairline per ancestor folder. */}
            {Array.from({ length: row.level - 1 }, (_, depth) => (
              <span
                key={depth}
                aria-hidden="true"
                className="absolute inset-y-0 w-px bg-zinc-950/[0.07] dark:bg-white/[0.08]"
                style={{ left: `${depth * 16 + 13.5}px` }}
              />
            ))}
            <span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center text-zinc-400 dark:text-zinc-500">
              {row.folder ? (
                <svg
                  viewBox="0 0 16 16"
                  fill="none"
                  className={cx(
                    "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",
                    row.open && "rotate-90",
                  )}
                >
                  <path d="m6.25 4.5 3.5 3.5-3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              ) : null}
            </span>
            <TreeIcon folder={row.folder} open={row.open} />
            <span
              className={cx(
                "min-w-0 flex-1 truncate font-mono text-[13px]",
                row.node.change === "deleted"
                  ? "text-zinc-500 line-through decoration-zinc-500/60"
                  : row.folder
                    ? "text-zinc-700 dark:text-zinc-300"
                    : "text-zinc-950 dark:text-white",
              )}
            >
              {row.node.name}
            </span>
            {hidden > 0 ? (
              <span className="shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums">
                {hidden} {hidden === 1 ? "file" : "files"}
              </span>
            ) : null}
            {!row.folder && (row.node.additions || row.node.deletions) ? (
              <span className="flex shrink-0 gap-1.5 font-mono text-[11px] tabular-nums">
                {row.node.additions ? (
                  <span className="text-emerald-600 dark:text-emerald-400">
                    +{row.node.additions}
                    <span className="sr-only"> lines added</span>
                  </span>
                ) : null}
                {row.node.deletions ? (
                  <span className="text-red-600 dark:text-red-400">
                    โˆ’{row.node.deletions}
                    <span className="sr-only"> lines removed</span>
                  </span>
                ) : null}
              </span>
            ) : null}
            {change ? (
              <span className={cx("w-3 shrink-0 text-center font-mono text-[11px] font-semibold", change.tone)} title={change.label}>
                <span aria-hidden="true">{change.letter}</span>
                <span className="sr-only">, {change.label}</span>
              </span>
            ) : !row.folder ? (
              <span aria-hidden="true" className="w-3 shrink-0" />
            ) : null}
          </li>
        );
      })}
    </ul>
  );
}

function TreeIcon({ folder, open }: { folder: boolean; open: boolean }) {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.25"
      strokeLinejoin="round"
      strokeLinecap="round"
      className="size-4 shrink-0 text-zinc-500"
    >
      {folder ? (
        open ? (
          <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" />
        ) : (
          <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" />
        )
      ) : (
        <>
          <path d="M4 1.75h5l3 3v9.5H4V1.75Z" />
          <path d="M9 1.75v3h3" />
        </>
      )}
    </svg>
  );
}