Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

14.5 KB
Raw Blame
/**
 * The file tree: one row per entry on screen, indented by depth, a chevron and a folder glyph on
 * directories, a page glyph on files. Clicking a directory opens or closes it, clicking a file
 * hands it to the caller.
 *
 * The caller brings the rows (tree-rows.ts states their shape) and nothing else about how they
 * were produced: the Workspace panel lists one directory per level as it is opened, the plugin
 * browser groups a listing it already holds. What this owns is the drawing and the interaction —
 * indentation, glyphs, the selected and hover treatment, the ARIA tree semantics and the
 * keyboard walk.
 *
 * Keyboard: the WAI-ARIA tree pattern with a roving tab stop — one row is in the tab order
 * (the focused one, else the selected one, else the first), arrows move between rows and
 * open/close directories (treeKeyStep), Enter and Space act like a click.
 *
 * Rows carry `data-tree-path` / `data-tree-kind`, which is how a caller that handles a pointer
 * event over the whole tree (the Workspace panel's drag-and-drop, its context menu) resolves
 * the row under the pointer.
 *
 * A row names itself from what it draws. `rowLabel` is the one way out, for a row whose visible
 * text is not the whole of what it means — the handbook's pinned index.
 *
 * The rows stay one flat list; what nests is the drawing. An open directory's descendants go
 * in a `role="group"` box whose height is animated (file-tree.css), so a subtree grows out of its
 * directory's row and shrinks back into it. Only the directory the caller says was just toggled
 * animates, so a re-render, a filter or an unrelated commit animates nothing. Closing is the
 * awkward half: the rows are gone from `rows` by the time the view hears about it, so the view
 * keeps the last committed rows and re-renders the closed directory's own descendants, inert, for
 * as long as the shrink lasts.
 */
import { useEffect, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
import { ICON_SIZE } from "../../../icon-scale";
import { Chevron } from "../../icons/chevron/chevron";
import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";
import { ICONS } from "../../icons/icons";
import { subtreeEnd, treeKeyStep } from "./tree-rows";
import type { FileTreeRow } from "./tree-rows";
import "./file-tree.css";

/** Left padding of a depth-0 row, in px; deeper rows add `TREE_INDENT_PX` per level. */
const TREE_PAD_PX = 6;

/** Indent per nesting level, in px. */
const TREE_INDENT_PX = 14;

/** Width of the chevron column, in px — `w-3.5`, mirrored so an empty directory's line can clear it. */
const CHEVRON_COL_PX = 14;

/**
 * How long a closing subtree is kept on screen when its animation never reports back. Under
 * reduced motion the keyframes are off, so no `animationend` ever arrives and this timer is the
 * only thing that drops the retained rows. Comfortably past the 200ms shrink.
 */
const CLOSE_FALLBACK_MS = 260;

/** The directory whose open or close the tree should animate. `serial` makes toggling the same directory again a new event. */
export interface TreeToggle {
  dir: string;
  open: boolean;
  serial: number;
}

export interface FileTreeProps<Row extends FileTreeRow> {
  rows: readonly Row[];
  /** The tree's accessible name. */
  label: string;
  /** The row drawn as selected, and the tab stop's fallback. */
  selectedPath: string | null;
  /** Directories whose listing is in flight: the row dims and reports `aria-busy`. */
  loadingDirs?: ReadonlySet<string>;
  /** The folder a hovering drag would drop into, ringed while it is; null while nothing is dragged. */
  dropTargetDir?: string | null;
  /** A row to bring into view; a new object scrolls again even for the same path. */
  scrollTo?: { path: string } | null;
  /** The directory last opened or closed, whose subtree animates. Null: nothing to animate. */
  toggled?: TreeToggle | null;
  /**
   * A row's tooltip, when it says more than the row shows (a size, an exact time): it then shows
   * over the row's name in full. Without it the tooltip is the path, shown only over a name cut
   * short.
   */
  rowTitle?: (row: Row) => string;
  /**
   * A row's accessible name, for the row whose visible text leaves out what the row means — the
   * handbook's pinned index says on screen only a file name, and why it is pinned would
   * otherwise live in the tooltip alone. Undefined (the default, and every ordinary row): the
   * row names itself from what it draws.
   */
  rowLabel?: (row: Row) => string | undefined;
  /** Trailing content on a row, after its name — the Workspace's file sizes. */
  rowTrailing?: (row: Row) => ReactNode;
  /** What an open directory holding nothing says in place of its children; omitted, it says nothing. */
  emptyLabel?: string;
  /** Extra classes on the tree container — its own layout and scrolling belong to the caller. */
  className?: string;
  /** Shown in place of the rows when there are none: the caller's empty or no-match state. */
  children?: ReactNode;
  onToggleDir: (dir: string) => void;
  onOpenFile: (path: string) => void;
}

export function FileTree<Row extends FileTreeRow>({
  rows,
  label,
  selectedPath,
  loadingDirs,
  dropTargetDir = null,
  scrollTo = null,
  toggled = null,
  rowTitle,
  rowLabel,
  rowTrailing,
  emptyLabel,
  className = "",
  children,
  onToggleDir,
  onOpenFile,
}: FileTreeProps<Row>) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [focused, setFocused] = useState<string | null>(null);

  // The descendants of directories that have just closed, by directory path. They are no
  // longer in `rows` — the caller closed the directory in the same commit that reported the
  // toggle — so they are captured from the previous commit's rows and drawn until the shrink
  // is over. They are never in `rows`, and so never in treeKeyStep, the tab stop or onScreen.
  const [closing, setClosing] = useState<ReadonlyMap<string, readonly Row[]>>(() => new Map());
  // The serial of the toggle already acted on. The serial, not the object: a filter hands the
  // prop null and then hands the very same toggle back when it is cleared, and replaying that
  // close would shrink a ghost subtree out of a directory the user never touched.
  const [seenSerial, setSeenSerial] = useState<number>(toggled?.serial ?? 0);
  const prevRowsRef = useRef<readonly Row[]>(rows);

  if (toggled === null) {
    // A filter redraws the tree from a different row set; nothing left over belongs to it.
    if (closing.size > 0) setClosing(new Map());
  } else if (toggled.serial !== seenSerial) {
    // Adjusting state during render rather than in an effect: the retained rows have to be in
    // the same paint that dropped them, or the subtree blinks out and then shrinks from nothing.
    setSeenSerial(toggled.serial);
    if (toggled.open) {
      // Re-opened while shrinking: the live group takes over, animating open from where it is.
      if (closing.has(toggled.dir)) {
        const next = new Map(closing);
        next.delete(toggled.dir);
        setClosing(next);
      }
    } else {
      const prev = prevRowsRef.current;
      const at = prev.findIndex((r) => r.path === toggled.dir);
      const kept = at < 0 ? [] : prev.slice(at + 1, subtreeEnd(prev, at));
      if (kept.length > 0) setClosing(new Map(closing).set(toggled.dir, kept));
    }
  }

  useEffect(() => {
    prevRowsRef.current = rows;
  }, [rows]);

  const dropClosing = (dir: string): void => {
    setClosing((prev) => {
      if (!prev.has(dir)) return prev;
      const next = new Map(prev);
      next.delete(dir);
      return next;
    });
  };

  useEffect(() => {
    if (closing.size === 0) return;
    const timers = [...closing.keys()].map((dir) =>
      setTimeout(() => dropClosing(dir), CLOSE_FALLBACK_MS),
    );
    return () => {
      for (const timer of timers) clearTimeout(timer);
    };
  }, [closing]);

  const rowElement = (path: string): HTMLElement | null =>
    containerRef.current?.querySelector<HTMLElement>(`[data-tree-path="${CSS.escape(path)}"]`) ??
    null;

  useEffect(() => {
    if (scrollTo === null) return;
    if (scrollTo.path === "") containerRef.current?.scrollTo({ top: 0 });
    else rowElement(scrollTo.path)?.scrollIntoView({ block: "nearest" });
  }, [scrollTo]);

  const activate = (row: Row): void => {
    setFocused(row.path);
    if (row.kind === "dir") onToggleDir(row.path);
    else onOpenFile(row.path);
  };

  const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>): void => {
    if (e.key === "Enter" || e.key === " ") {
      const row = rows.find((r) => r.path === focused);
      if (row === undefined) return;
      e.preventDefault();
      activate(row);
      return;
    }
    const step = treeKeyStep(rows, focused, e.key);
    if (step === null) return;
    e.preventDefault();
    if (step.focus !== undefined) {
      setFocused(step.focus);
      rowElement(step.focus)?.focus();
    }
    if (step.expand !== undefined) onToggleDir(step.expand);
    if (step.collapse !== undefined) onToggleDir(step.collapse);
  };

  // The one row in the tab order. A focused row that scrolled out of the rows (its
  // directory closed) hands the stop back to the selection or the first row.
  const onScreen = (path: string | null): boolean =>
    path !== null && rows.some((r) => r.path === path);
  const tabStop = onScreen(focused)
    ? focused
    : onScreen(selectedPath)
      ? selectedPath
      : (rows[0]?.path ?? null);

  /** One row. A retained row is a leftover of a closing subtree: it draws, and does nothing else. */
  const renderRow = (row: Row, retained: boolean): ReactNode => {
    const selected = !retained && row.path === selectedPath;
    const dropHere = !retained && row.kind === "dir" && row.path === dropTargetDir;
    const loading = row.kind === "dir" && loadingDirs !== undefined && loadingDirs.has(row.path);
    return (
      <div
        key={row.path}
        role="treeitem"
        tabIndex={retained || row.path !== tabStop ? -1 : 0}
        aria-level={row.depth + 1}
        aria-posinset={row.posInSet}
        aria-setsize={row.setSize}
        aria-selected={selected}
        {...(row.kind === "dir" ? { "aria-expanded": row.expanded } : {})}
        aria-busy={loading || undefined}
        // A retained row carries no path: rowElement() and a caller's pointer hit test both
        // resolve a row by this attribute, and neither may land on one that is on its way out.
        {...(retained ? {} : { "data-tree-path": row.path, "data-tree-kind": row.kind })}
        data-tooltip={rowTitle?.(row) ?? row.path}
        data-tooltip-extra={rowTitle !== undefined || undefined}
        aria-label={rowLabel?.(row)}
        {...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}
        style={{ paddingLeft: TREE_PAD_PX + row.depth * TREE_INDENT_PX }}
        className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-fg-subtle/60 ${
          dropHere
            ? "bg-tone-info-bg ring-2 ring-inset ring-tone-info-emphasis/60"
            : selected
              ? "bg-line-muted text-fg"
              : "text-fg hover:bg-surface-muted"
        } ${loading ? "opacity-60" : ""}`}
      >
        <span className="flex w-3.5 shrink-0 justify-center text-fg-subtle" aria-hidden>
          {row.kind === "dir" && <Chevron open={row.expanded} size={ICON_SIZE.chevronDense} />}
        </span>
        <GlyphIcon
          d={row.kind === "dir" ? (row.expanded ? ICONS.folderOpen : ICONS.folder) : ICONS.file}
          size={ICON_SIZE.rowLead}
          className="text-fg-subtle"
        />
        <span className="min-w-0 flex-1 truncate">{row.name}</span>
        {rowTrailing?.(row)}
      </div>
    );
  };

  /** An open directory with nothing in it says so, in place of the children it lacks. */
  const renderEmptyLine = (row: Row): ReactNode => (
    <p
      key={`empty:${row.path}`}
      className="py-1 pr-2 text-xs text-fg-subtle"
      style={{ paddingLeft: TREE_PAD_PX + (row.depth + 1) * TREE_INDENT_PX + CHEVRON_COL_PX }}
    >
      {emptyLabel}
    </p>
  );

  /**
   * The rows of `list` in `[start, end)`, with each open directory's descendants nested in a
   * group below it. `retained` marks a closing subtree, which draws its own nested groups but
   * animates nothing and takes no part in interaction.
   */
  const renderRange = (
    list: readonly Row[],
    start: number,
    end: number,
    retained: boolean,
  ): ReactNode[] => {
    const out: ReactNode[] = [];
    let i = start;
    while (i < end) {
      const row = list[i]!;
      out.push(renderRow(row, retained));
      if (row.kind !== "dir") {
        i += 1;
        continue;
      }
      const childrenEnd = subtreeEnd(list, i);
      if (row.expanded && row.loaded) {
        // The group mounts only once the listing is there, so a first open of an unloaded
        // directory animates when its rows arrive rather than around an empty box.
        const opening = !retained && toggled !== null && toggled.open && toggled.dir === row.path;
        out.push(
          <div
            key={`group:${row.path}`}
            role="group"
            aria-label={row.name}
            className={`tree-group ${opening ? "tree-group-open" : ""}`}
          >
            <div>
              {!row.empty
                ? renderRange(list, i + 1, childrenEnd, retained)
                : emptyLabel === undefined
                  ? null
                  : renderEmptyLine(row)}
            </div>
          </div>,
        );
      } else if (!retained && closing.has(row.path)) {
        const kept = closing.get(row.path)!;
        out.push(
          <div
            key={`closing:${row.path}`}
            role="group"
            aria-hidden
            inert
            className="tree-group tree-group-close"
            onAnimationEnd={(e) => {
              if (e.target === e.currentTarget) dropClosing(row.path);
            }}
          >
            <div>{renderRange(kept, 0, kept.length, true)}</div>
          </div>,
        );
      }
      i = childrenEnd;
    }
    return out;
  };

  return (
    <div
      ref={containerRef}
      role="tree"
      aria-label={label}
      onKeyDown={onKeyDown}
      className={`py-1 ${className}`}
    >
      {rows.length === 0
        ? children
        : // `role="group"` is the tree pattern's own container for one level, so the rows inside
          // one are still `treeitem`s of this tree and keep stating their own aria-level,
          // aria-posinset and aria-setsize.
          renderRange(rows, 0, rows.length, false)}
    </div>
  );
}