Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion apps/web/src/components/DiffPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { useFilesystemReadAccess } from "~/state/filesystem";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { useFileContextMenuHandler } from "../fileContextMenu";
import { type DraftId } from "../composerDraftStore";
import { openDiffFilePrimaryAction } from "../diffFileActions";
import { openDiffFilePrimaryAction, resolveDiffPathForWorkspace } from "../diffFileActions";
import { toolCallDiff } from "../lib/toolCallDiff";
import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries";
import { revisionedQuery } from "~/state/revisionedQuery";
Expand Down Expand Up @@ -862,6 +862,16 @@ export default function DiffPanel({
)?.cwd,
};
};
// A mention names the file from the thread's folder, the way the file viewer opens it.
const threadMentionPath = (filePath: string) => {
const repositoryFile = repositoryFileTarget(filePath);
if (repositoryFile?.insideThreadFolder === false) return null;
return resolveDiffPathForWorkspace({
filePath,
workspaceRoot: activeCwd,
repositoryRoot: repositoryFile ? undefined : diffPathRepositoryRoot,
});
};
const openDiffFile = (filePath: string) => {
const repositoryFile = repositoryFileTarget(filePath);
openDiffFilePrimaryAction({
Expand Down Expand Up @@ -1798,6 +1808,8 @@ export default function DiffPanel({
selectedPath={selectedFilePath}
revealRequestId={selectedFileRevealRequestId}
onSelectFile={revealDiffFile}
workspaceRoot={activeCwd}
mentionPath={threadMentionPath}
/>
</FileExplorerPane>
) : null}
Expand Down
87 changes: 86 additions & 1 deletion apps/web/src/components/diffs/DiffFileTree.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { FileTree } from "@pierre/trees";
import { expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";

import { ComposerHandleContext, type ComposerHandleRef } from "~/composerHandleContext";
import { dismissContextMenu } from "~/contextMenuFallback";

import { render } from "../../../test/render";
import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree";

Expand All @@ -16,7 +19,12 @@ it("expands every folder without asking the tree about all folders for each one"
using getItem = vi.spyOn(FileTree.prototype, "getItem");
await using _screen = await render(
<div className="flex h-[600px] flex-col">
<DiffFileTree entries={entries} onSelectFile={() => {}} ariaLabel="Changed files" />
<DiffFileTree
entries={entries}
onSelectFile={() => {}}
workspaceRoot="/repo"
ariaLabel="Changed files"
/>
</div>,
);
const collapseAll = page.getByRole("button", { name: "Collapse all folders" });
Expand All @@ -31,3 +39,80 @@ it("expands every folder without asking the tree about all folders for each one"
// grew with the square of the folder count (hundreds of thousands at 600 folders).
expect(getItem.mock.calls.length).toBeLessThan(FOLDERS * 2 * 20);
});

function findTreeRow(path: string): HTMLElement | null {
for (const host of document.querySelectorAll("*")) {
const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
if (row) return row;
}
return null;
}

function rightClick(row: HTMLElement) {
row.dispatchEvent(
new MouseEvent("contextmenu", { bubbles: true, cancelable: true, composed: true, button: 2 }),
);
}

it("copies a folder's path and a file's name from the right-click menu without opening the file", async () => {
const onSelectFile = vi.fn();
await using _screen = await render(
<div className="flex h-[600px] flex-col">
<DiffFileTree
entries={[
{ path: "apps/web/src/a.ts", status: "modified" },
{ path: "apps/web/src/b.ts", status: "added" },
]}
onSelectFile={onSelectFile}
workspaceRoot="/repo"
ariaLabel="Changed files"
/>
</div>,
);
using _menu = { [Symbol.dispose]: () => dismissContextMenu() };
using clipboard = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);

// Empty folders flatten into one "apps / web / src" row.
await vi.waitFor(() => expect(findTreeRow("apps/web/src/")).not.toBeNull());
rightClick(findTreeRow("apps/web/src/")!);
const copyPath = page.getByRole("menuitem", { name: "Copy path", exact: true });
await expect.element(copyPath).toBeVisible();
// No chat is open, so there is nothing to add the row to.
await expect.element(page.getByRole("menuitem", { name: "Add to chat" })).not.toBeInTheDocument();
await userEvent.click(copyPath);
await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("apps/web/src"));

rightClick(findTreeRow("apps/web/src/a.ts")!);
await userEvent.click(page.getByRole("menuitem", { name: "Copy name", exact: true }));
await vi.waitFor(() => expect(clipboard).toHaveBeenLastCalledWith("a.ts"));
expect(onSelectFile).not.toHaveBeenCalled();
});

it("adds a row to the open chat by the thread's path", async () => {
const insertTextAtEnd = vi.fn(() => true);
const composerRef = { current: { insertTextAtEnd } } as unknown as ComposerHandleRef;
await using _screen = await render(
<ComposerHandleContext value={composerRef}>
<div className="flex h-[600px] flex-col">
<DiffFileTree
entries={[{ path: "apps/web/src/a.ts", status: "modified" }]}
onSelectFile={() => {}}
workspaceRoot="/repo/apps/web"
// The thread works in the repository's apps/web folder.
mentionPath={(path) => path.replace(/^apps\/web\//, "")}
ariaLabel="Changed files"
/>
</div>
</ComposerHandleContext>,
);
using _menu = { [Symbol.dispose]: () => dismissContextMenu() };

await vi.waitFor(() => expect(findTreeRow("apps/web/src/a.ts")).not.toBeNull());
rightClick(findTreeRow("apps/web/src/a.ts")!);
await userEvent.click(page.getByRole("menuitem", { name: "Add to chat", exact: true }));
await vi.waitFor(() =>
expect(insertTextAtEnd).toHaveBeenCalledWith("[a.ts](src/a.ts) ", {
ensureLeadingBoundary: true,
}),
);
});
59 changes: 58 additions & 1 deletion apps/web/src/components/diffs/DiffFileTree.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import type { GitStatusEntry } from "@pierre/trees";
import type {
ContextMenuItem as TreeContextMenuItem,
ContextMenuOpenContext as TreeContextMenuOpenContext,
GitStatusEntry,
} from "@pierre/trees";
import { FileTree, useFileTree } from "@pierre/trees/react";
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import * as AsyncResult from "effect/reactivity/AsyncResult";
import { T, useGT } from "gt-react";
import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";

import { useComposerHandleContext } from "~/composerHandleContext";
import { useStableCallback } from "~/hooks/useStableCallback";
import { useTheme } from "~/hooks/useTheme";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import {
PIERRE_TREE_UNSAFE_CSS,
pierreTreeStyle,
Expand All @@ -18,13 +27,21 @@ import {
setAllDirectoriesExpanded,
subscribeOncePerTask,
} from "../files/fileTreeExpansion";
import {
addFileTreeRowToChat,
addToChatMenuItem,
copyFileTreeRow,
fileTreeCopyMenuItems,
useTreeContextMenuAnchor,
} from "../files/fileTreeRowMenu";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
buildDiffFileTreeUpdates,
compareDiffFileTreeEntries,
collectDirectoryPaths,
diffFileTreeModel,
diffFileTreeRow,
type DiffFileTreeEntry,
} from "./diffFileTree.logic";
import { diffFileTreePositions } from "@t3tools/client-runtime/diff-file-order";
Expand All @@ -34,6 +51,10 @@ export type { DiffFileTreeEntry } from "./diffFileTree.logic";
interface DiffFileTreeProps {
readonly entries: ReadonlyArray<DiffFileTreeEntry>;
readonly onSelectFile: (path: string) => void;
/** Host folder the diff paths belong to; copied paths use its separators. */
readonly workspaceRoot: string | undefined;
/** The open thread's path for a row; Add to chat is offered only where it returns one. */
readonly mentionPath?: (path: string) => string | null;
readonly selectedPath?: string | null;
readonly revealRequestId?: number;
readonly ariaLabel: string;
Expand All @@ -45,6 +66,8 @@ interface DiffFileTreeProps {
export function DiffFileTree({
entries,
onSelectFile,
workspaceRoot,
mentionPath,
selectedPath = null,
revealRequestId = 0,
ariaLabel,
Expand Down Expand Up @@ -89,7 +112,40 @@ export function DiffFileTree({
}
});

const contextMenuAnchor = useTreeContextMenuAnchor();
const composerRef = useComposerHandleContext();
const showRowContextMenu = useStableCallback(
(item: TreeContextMenuItem, context: TreeContextMenuOpenContext) => {
const api = readLocalApi();
if (!api) {
context.close();
return;
}
const row = diffFileTreeRow(item.path, presented.selectionPath);
const position = contextMenuAnchor.takeOver(context);
void settlePromise(async () => {
// A pull request opened outside a thread has no chat to add to.
const threadPath = composerRef?.current == null ? null : (mentionPath?.(row.path) ?? null);
const clicked = await api.contextMenu.show(
[...fileTreeCopyMenuItems(), ...(threadPath === null ? [] : [addToChatMenuItem()])],
position,
);
if (clicked === "add-to-chat") {
if (threadPath !== null) addFileTreeRowToChat(composerRef, threadPath);
} else if (clicked !== null) await copyFileTreeRow(clicked, row, workspaceRoot);
}).then((result) => {
if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
});
},
);

const { model } = useFileTree({
composition: {
contextMenu: {
triggerMode: "right-click",
onOpen: (item, context) => showRowContextMenu(item, context),
},
},
density: "compact",
flattenEmptyDirectories: true,
initialExpansion: "open",
Expand Down Expand Up @@ -255,6 +311,7 @@ export function DiffFileTree({
);
if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));
}}
onContextMenuCapture={contextMenuAnchor.onContextMenuCapture}
className="min-h-0 flex-1 overflow-hidden"
style={pierreTreeStyle(resolvedTheme)}
onPointerOver={titleClippedPierreTreeRow}
Expand Down
19 changes: 18 additions & 1 deletion apps/web/src/components/diffs/diffFileTree.logic.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { FileDiffMetadata } from "@pierre/diffs";
import { describe, expect, it } from "vite-plus/test";

import { buildDiffFileTreeUpdates, diffFileTreeEntries } from "./diffFileTree.logic";
import {
buildDiffFileTreeUpdates,
diffFileTreeEntries,
diffFileTreeModel,
diffFileTreeRow,
} from "./diffFileTree.logic";

function file(type: FileDiffMetadata["type"], name: string, prevName = name): FileDiffMetadata {
return { type, name, prevName } as FileDiffMetadata;
Expand Down Expand Up @@ -40,3 +45,15 @@ describe("buildDiffFileTreeUpdates", () => {
]);
});
});

describe("diffFileTreeRow", () => {
it("names a file that shares its path with a folder by its real path", () => {
const presented = diffFileTreeModel(["docs", "docs/guide.md"]);
const [aliasedFile] = presented.paths;
expect(aliasedFile).not.toBe("docs");
expect(diffFileTreeRow(aliasedFile!, presented.selectionPath)).toEqual({
path: "docs",
name: "docs",
});
});
});
6 changes: 6 additions & 0 deletions apps/web/src/components/diffs/diffFileTree.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ export function diffFileTreeModel(paths: ReadonlyArray<string>) {
};
}

/** A row's path as the diff names it (a folder without its trailing slash) and its last segment. */
export function diffFileTreeRow(modelPath: string, selectionPath: (modelPath: string) => string) {
const path = selectionPath(modelPath).replace(/\/$/, "");
return { path, name: basenameOfPath(path) };
}

export function collectDirectoryPaths(paths: ReadonlyArray<string>): ReadonlyArray<string> {
const directories = new Set<string>();
for (const path of paths) {
Expand Down
23 changes: 23 additions & 0 deletions apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,29 @@ describe("FileBrowserPanel", () => {
await vi.waitFor(() => expect((row.getRootNode() as ShadowRoot).activeElement).toBe(row));
});

it("copies a folder's path as the panel shows it", async () => {
await using _screen = await render(
<FileBrowserPanel
environmentId={EnvironmentId.make("env-files")}
cwd="/repo"
projectName="repo"
selectedPath={null}
selectedPathRevealId={0}
onOpenFile={() => {}}
workspaceMutationId={null}
hostFolder
/>,
);
using _menu = { [Symbol.dispose]: () => dismissContextMenu() };
using clipboard = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
findTreeRow("src/")!.dispatchEvent(
new MouseEvent("contextmenu", { bubbles: true, cancelable: true, composed: true, button: 2 }),
);
await userEvent.click(page.getByRole("menuitem", { name: "Copy path", exact: true }));
await vi.waitFor(() => expect(clipboard).toHaveBeenCalledWith("/repo/src"));
});

it("dragging a file row carries a composer mention without opening it, and dragend releases it", async () => {
const onOpenFile = vi.fn();
await using _screen = await render(
Expand Down
Loading
Loading