sailfork / t3code-github / apps/ mobile/ src/ features/ files/ FileTreeBrowser.tsx

import { NativeScrollView } from "../../native/NativeScrollViewMarker";
import { Button } from "../../components/ui/Button";
import { LegendList } from "@legendapp/list/react-native";
import type { ProjectEntry } from "@t3tools/contracts";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { SymbolView } from "../../components/ui/AppSymbol";
import { useEffect, useRef, useState } from "react";
import { Pressable, RefreshControl, View } from "react-native";

import { AppText as Text } from "../../components/ui/AppText";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
import { cn } from "../../lib/cn";
import { useContentTopInset } from "../../components/ui/useBarInset";
import {
  buildFileTree,
  flattenFileTree,
  type FileTreeNode,
  type VisibleFileTreeNode,
} from "./fileTree";

const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;

function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
  const cached = fileTreeCache.get(entries);
  if (cached !== undefined) {
    return cached;
  }
  const tree = buildFileTree(entries);
  fileTreeCache.set(entries, tree);
  return tree;
}

const FileTreeRow = function FileTreeRow(props: {
  readonly item: VisibleFileTreeNode;
  readonly selected: boolean;
  readonly expanded: boolean;
  readonly loading: boolean;
  readonly onPressDirectory: (path: string, expand: boolean) => void;
  readonly onPreviewFile?: (path: string) => void;
  readonly onPressFile: (path: string) => void;
}) {
  const { node, depth } = props.item;

  return (
    <Pressable
      accessibilityRole="button"
      accessibilityLabel={node.path}
      accessibilityState={{ selected: props.selected }}
      onPressIn={() => {
        if (node.kind === "file") {
          props.onPreviewFile?.(node.path);
        }
      }}
      onPress={() => {
        if (node.kind === "directory") {
          props.onPressDirectory(node.path, !props.expanded);
          return;
        }
        props.onPressFile(node.path);
      }}
      className={cn(
        "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
        props.selected && "bg-thread-selected",
      )}
      style={{ paddingLeft: 8 + depth * 18 }}
    >
      {node.kind === "directory" ? (
        <SymbolView
          name={props.expanded ? "chevron.down" : "chevron.right"}
          size={12}
          tintColorClassName="accent-icon-muted"
          type="monochrome"
        />
      ) : (
        <View className="w-3" />
      )}
      <PierreEntryIcon path={node.path} kind={node.kind} size={17} />
      <Text
        className={cn(
          "min-w-0 flex-1 text-sm leading-normal",
          props.selected
            ? "font-t3-bold text-thread-selected-foreground"
            : node.ignored
              ? "font-t3-medium text-foreground-tertiary"
              : "font-t3-medium text-foreground-secondary",
        )}
        numberOfLines={1}
      >
        {node.name}
      </Text>
      {node.kind === "directory" && props.expanded && props.loading ? (
        <AppActivityIndicator size="small" accessibilityLabel={`Loading ${node.name}`} />
      ) : null}
    </Pressable>
  );
};

export function FileTreeBrowser(props: {
  readonly revealSelection: (path: string | null) => void;
  readonly expandedPaths: ReadonlySet<string>;
  readonly setExpandedPaths: (
    update: (current: ReadonlySet<string>) => ReadonlySet<string>,
  ) => void;
  readonly entries: ReadonlyArray<ProjectEntry>;
  readonly error: string | null;
  readonly isPending: boolean;
  readonly isRefreshing: boolean;
  readonly searchQuery: string;
  readonly searchResultPaths: ReadonlySet<string> | null;
  readonly searchTruncated: boolean;
  readonly selectedPath: string | null;
  readonly loadingDirectories: ReadonlySet<string>;
  readonly onLoadDirectory: (path: string, retry?: boolean) => void;
  readonly onPreviewFile?: (path: string) => void;
  readonly onRefresh: () => void;
  readonly onSelectFile: (path: string) => void;
}) {
  const { expandedPaths, setExpandedPaths } = props;
  const [pendingSelection, setPendingSelection] = useState<{
    readonly path: string;
    readonly selectedPathAtPress: string | null;
  } | null>(null);
  const headerInset = useContentTopInset();
  const {
    onLoadDirectory,
    onPreviewFile,
    onSelectFile,
    loadingDirectories,
    selectedPath: controlledSelectedPath,
  } = props;
  const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const selectedPath =
    pendingSelection?.selectedPathAtPress === controlledSelectedPath
      ? pendingSelection.path
      : controlledSelectedPath;
  const tree = cachedFileTree(props.entries);
  const visibleNodes = flattenFileTree({
    nodes: tree,
    expanded: expandedPaths,
    searchResultPaths: props.searchResultPaths,
  });

  const { revealSelection } = props;
  // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands the controlled selection's ancestor directories in the file tree state
  useEffect(() => {
    revealSelection(controlledSelectedPath);
  }, [controlledSelectedPath, revealSelection]);

  // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests listings for expanded directories that are not yet loaded or pending
  useEffect(() => {
    const visit = (nodes: ReadonlyArray<FileTreeNode>) => {
      for (const node of nodes) {
        if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue;
        onLoadDirectory(node.path);
        visit(node.children);
      }
    };
    visit(tree);
  }, [tree, expandedPaths, onLoadDirectory]);

  // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the pending selection timer on unmount
  useEffect(
    () => () => {
      if (pendingSelectionTimeoutRef.current !== null) {
        clearTimeout(pendingSelectionTimeoutRef.current);
      }
    },
    [],
  );

  const toggleDirectory = (path: string, expand: boolean) => {
    if (expand) onLoadDirectory(path, true);
    setExpandedPaths((current) => {
      const next = new Set(current);
      if (next.has(path)) {
        next.delete(path);
      } else {
        next.add(path);
      }
      return next;
    });
  };
  const handleSelectFile = (path: string) => {
    if (pendingSelectionTimeoutRef.current !== null) {
      clearTimeout(pendingSelectionTimeoutRef.current);
    }
    setPendingSelection({
      path,
      selectedPathAtPress: controlledSelectedPath,
    });
    pendingSelectionTimeoutRef.current = setTimeout(() => {
      pendingSelectionTimeoutRef.current = null;
      setPendingSelection((current) => (current?.path === path ? null : current));
    }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
    onSelectFile(path);
  };
  const renderItem = ({ item }: { readonly item: VisibleFileTreeNode }) => (
    <FileTreeRow
      item={item}
      selected={item.node.kind === "file" && item.node.path === selectedPath}
      expanded={expandedPaths.has(item.node.path)}
      loading={loadingDirectories.has(item.node.path)}
      onPressDirectory={toggleDirectory}
      onPreviewFile={onPreviewFile}
      onPressFile={handleSelectFile}
    />
  );

  const extraData = { expandedPaths, loadingDirectories, selectedPath };

  // Keep the list as direct screen content so UIKit can apply header insets.
  return (
    <LegendList
      renderScrollComponent={NativeScrollView}
      contentInsetStartAdjustment={headerInset}
      alwaysBounceVertical
      className="flex-1"
      data={visibleNodes}
      keyExtractor={(item) => item.node.path}
      contentInsetAdjustmentBehavior="automatic"
      automaticallyAdjustsScrollIndicatorInsets
      keyboardDismissMode="on-drag"
      keyboardShouldPersistTaps="handled"
      estimatedItemSize={42}
      recycleItems
      maintainVisibleContentPosition
      extraData={extraData}
      contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
      refreshControl={
        <RefreshControl refreshing={props.isRefreshing} onRefresh={props.onRefresh} />
      }
      renderItem={renderItem}
      ListHeaderComponent={
        <>
          {props.error && props.entries.length > 0 ? (
            <Text accessibilityRole="alert" className="mx-4 my-2 text-xs text-foreground-muted">
              {props.error}
            </Text>
          ) : null}
          {props.searchTruncated ? (
            <Text className="mx-4 my-2 text-xs text-foreground-muted">
              More search results available. Refine your search to see them.
            </Text>
          ) : null}
        </>
      }
      ListEmptyComponent={
        <View className="px-4 py-5">
          {props.error && props.entries.length === 0 ? (
            <>
              <Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
              <Text
                accessibilityRole="alert"
                className="mt-1 text-xs leading-normal text-foreground-muted"
              >
                {props.error}
              </Text>
              <View className="mt-3">
                <Button
                  label="Try again"
                  tone="secondary"
                  onPress={props.onRefresh}
                  disabled={props.isPending}
                />
              </View>
            </>
          ) : props.isPending ? (
            <AppActivityIndicator size="small" />
          ) : (
            <>
              <Text className="text-sm font-t3-bold text-foreground">No files found</Text>
              <Text className="mt-1 text-xs leading-normal text-foreground-muted">
                {props.searchQuery.trim().length > 0
                  ? "Try a different search."
                  : "The workspace is empty."}
              </Text>
            </>
          )}
        </View>
      }
    />
  );
}