Skip to content
TypeScript

perf(web): the file browser panel compiles with the React Compiler (#20483)

Julius Marmingea77cbf0d5ed9
diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts
index b6fec3e629c..fbbc30589ef 100644
--- a/apps/web/reactCompiledFiles.ts
+++ b/apps/web/reactCompiledFiles.ts
@@ -58,4 +58,5 @@ export const REACT_COMPILED_FILES = [
"apps/web/src/components/usage/UsagePage.tsx",
"apps/web/src/components/ProviderUpdateEnvironmentRows.tsx",
"apps/web/src/components/files/useDirectoryEntries.ts",
+ "apps/web/src/components/files/FileBrowserPanel.tsx",
] as const;
diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx
index ca11fbd958f..bbc0b53412c 100644
--- a/apps/web/src/components/files/FileBrowserPanel.tsx
+++ b/apps/web/src/components/files/FileBrowserPanel.tsx
@@ -5,9 +5,12 @@ import type {
} from "@pierre/trees";
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
import { FileTree, useFileTree, useFileTreeSearch, useFileTreeSelector } from "@pierre/trees/react";
+import { settlePromise } from "@t3tools/client-runtime/state/runtime";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
+import * as AsyncResult from "effect/reactivity/AsyncResult";
+import * as Cause from "effect/Cause";
import { ChevronsDownUp, ChevronsUpDown } from "lucide";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState, type RefObject } from "react";
import { Button } from "~/components/ui/button";
import { InputGroup, InputGroupInput } from "~/components/ui/input-group";
@@ -16,6 +19,7 @@ import { toastManager } from "~/components/ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { useComposerHandleContext } from "~/composerHandleContext";
import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
+import { useStableCallback } from "~/hooks/useStableCallback";
import { useTheme } from "~/hooks/useTheme";
import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu";
@@ -101,6 +105,47 @@ function FileSearchField(props: {
);
}
+// The tree diffs `treePaths` by identity, so these derivations must stay cached
+// across the hooks that read them.
+function useTreeEntries(
+ directoryEntries: readonly ProjectEntry[],
+ searchEntries: readonly ProjectEntry[],
+ searchPending: boolean,
+ query: string,
+) {
+ "use memo";
+ const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
+ if (query.trim() && !searchPending) {
+ for (const entry of searchEntries) {
+ if (!result.has(entry.path)) result.set(entry.path, entry);
+ const segments = entry.path.split("/");
+ for (let index = 1; index < segments.length; index++) {
+ const path = segments.slice(0, index).join("/");
+ if (!result.has(path)) result.set(path, { path, kind: "directory" });
+ }
+ }
+ }
+ const entries = [...result.values()];
+ const entryKinds: ReadonlyMap<string, ProjectEntry["kind"]> = new Map(
+ entries.map((entry) => [entry.path, entry.kind] as const),
+ );
+ const treePaths = entries.map(treePath);
+ const directoryPaths = entries.filter((entry) => entry.kind === "directory").map(treePath);
+ return { entries, entryKinds, treePaths, directoryPaths };
+}
+
+function useDragMentionController(
+ cwd: string,
+ hostFolder: boolean,
+ treeModelRef: RefObject<ReturnType<typeof useFileTree>["model"] | null>,
+) {
+ "use memo";
+ return createFileTreeDragMentionController({
+ deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
+ ...(hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {}),
+ });
+}
+
export default function FileBrowserPanel({
environmentId,
cwd,
@@ -132,30 +177,13 @@ export default function FileBrowserPanel({
{ environmentId, cwd: hostFolder ? null : cwd, query: query.slice(0, 256) },
200,
);
- const entries = useMemo(() => {
- const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));
- if (query.trim() && !pathSearch.isPending) {
- for (const entry of pathSearch.entries) {
- if (!result.has(entry.path)) result.set(entry.path, entry);
- const segments = entry.path.split("/");
- for (let index = 1; index < segments.length; index++) {
- const path = segments.slice(0, index).join("/");
- if (!result.has(path)) result.set(path, { path, kind: "directory" });
- }
- }
- }
- return [...result.values()];
- }, [directoryEntries, pathSearch.entries, pathSearch.isPending, query]);
- const entryKinds = useMemo(
- () => new Map(entries.map((entry) => [entry.path, entry.kind] as const)),
- [entries],
- );
- const entryKindsRef = useRef<ReadonlyMap<string, ProjectEntry["kind"]>>(entryKinds);
- const treePaths = useMemo(() => entries.map(treePath), [entries]);
- const directoryPaths = useMemo(
- () => entries.filter((entry) => entry.kind === "directory").map(treePath),
- [entries],
+ const { entries, entryKinds, treePaths, directoryPaths } = useTreeEntries(
+ directoryEntries,
+ pathSearch.entries,
+ pathSearch.isPending,
+ query,
);
+ const entryKindsRef = useRef(entryKinds);
const previousTreePathsRef = useRef<readonly string[] | null>(null);
const syncingSelectionRef = useRef(false);
const treeSelectionPathRef = useRef<string | null>(null);
@@ -173,100 +201,94 @@ export default function FileBrowserPanel({
return () => document.removeEventListener("contextmenu", capturePointer, true);
}, []);
- const showEntryContextMenu = async (
- item: TreeContextMenuItem,
- context: TreeContextMenuOpenContext,
- ) => {
- const api = readLocalApi();
- if (!api) {
- context.close();
- return;
- }
- const relativePath = item.path.replace(/\/$/, "");
- const mention = serializeComposerFileLink(panelPath(relativePath));
- const pointer = contextMenuPointerRef.current;
- const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
- const anchorRect = context.anchorElement.getBoundingClientRect();
- const position = pointerIsFresh
- ? { x: pointer.x, y: pointer.y }
- : { x: anchorRect.left, y: anchorRect.bottom };
- const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };
- const fileMenuItems = fileContextMenu.buildItems(fileTarget);
- try {
- const clicked = await api.contextMenu.show(
- [
- ...fileMenuItems,
- { id: "copy-mention", label: "Copy mention" },
- { id: "add-to-chat", label: "Add to chat" },
- ],
- position,
- );
- if (clicked === null) return;
- // "Open with" submenu selections report the child id ("editor:<id>"),
- // which is not present in the top-level item list.
- const isFileMenuAction =
- fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
- if (isFileMenuAction) {
- await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
+ const showEntryContextMenu = useStableCallback(
+ (item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => {
+ const api = readLocalApi();
+ if (!api) {
+ context.close();
return;
}
- if (clicked === "copy-mention") {
- try {
- await writeTextToClipboard(mention);
- toastManager.add({ type: "success", title: "Mention copied", description: relativePath });
- } catch (error) {
- toastManager.add({
- type: "error",
- title: "Failed to copy mention",
- description: error instanceof Error ? error.message : "An error occurred.",
- });
+ const relativePath = item.path.replace(/\/$/, "");
+ const mention = serializeComposerFileLink(panelPath(relativePath));
+ const pointer = contextMenuPointerRef.current;
+ const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;
+ const anchorRect = context.anchorElement.getBoundingClientRect();
+ const position = pointerIsFresh
+ ? { x: pointer.x, y: pointer.y }
+ : { x: anchorRect.left, y: anchorRect.bottom };
+ const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };
+ const fileMenuItems = fileContextMenu.buildItems(fileTarget);
+ void settlePromise(async () => {
+ const clicked = await api.contextMenu.show(
+ [
+ ...fileMenuItems,
+ { id: "copy-mention", label: "Copy mention" },
+ { id: "add-to-chat", label: "Add to chat" },
+ ],
+ position,
+ );
+ if (clicked === null) return;
+ // "Open with" submenu selections report the child id ("editor:<id>"),
+ // which is not present in the top-level item list.
+ const isFileMenuAction =
+ fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");
+ if (isFileMenuAction) {
+ await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);
+ return;
}
- return;
- }
- if (clicked === "add-to-chat") {
- const composer = composerRef?.current;
- if (!composer) {
- toastManager.add({
- type: "error",
- title: "Unable to add to chat",
- description: "Open a chat for this project and try again.",
- });
+ if (clicked === "copy-mention") {
+ try {
+ await writeTextToClipboard(mention);
+ toastManager.add({
+ type: "success",
+ title: "Mention copied",
+ description: relativePath,
+ });
+ } catch (error) {
+ toastManager.add({
+ type: "error",
+ title: "Failed to copy mention",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ });
+ }
return;
}
- const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
- if (!inserted) {
- toastManager.add({
- type: "error",
- title: "Unable to add to chat",
- description: "The chat isn't ready to accept input right now.",
- });
+ if (clicked === "add-to-chat") {
+ const composer = composerRef?.current;
+ if (!composer) {
+ toastManager.add({
+ type: "error",
+ title: "Unable to add to chat",
+ description: "Open a chat for this project and try again.",
+ });
+ return;
+ }
+ const inserted = composer.insertTextAtEnd(`${mention} `, { ensureLeadingBoundary: true });
+ if (!inserted) {
+ toastManager.add({
+ type: "error",
+ title: "Unable to add to chat",
+ description: "The chat isn't ready to accept input right now.",
+ });
+ }
}
- }
- } finally {
- context.close();
- }
- };
- const showEntryContextMenuRef = useRef(showEntryContextMenu);
- useEffect(() => {
- showEntryContextMenuRef.current = showEntryContextMenu;
- });
+ }).then((result) => {
+ context.close();
+ // Keep surfacing unexpected failures as unhandled rejections.
+ if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
+ });
+ },
+ );
const loadingDirectoriesRef = useRef(loadingDirectories);
const treeModelRef = useRef<ReturnType<typeof useFileTree>["model"] | null>(null);
- const dragMention = useMemo(
- () =>
- createFileTreeDragMentionController({
- deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),
- ...(hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {}),
- }),
- [cwd, hostFolder],
- );
+ const dragMention = useDragMentionController(cwd, hostFolder, treeModelRef);
const { model } = useFileTree({
composition: {
contextMenu: {
triggerMode: "right-click",
onOpen: (item, context) => {
- void showEntryContextMenuRef.current(item, context);
+ showEntryContextMenu(item, context);
},
},
},