fix(web): browse folders from file breadcrumbs (#8910)

Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-01 23:15:04 -04:00
1 parent fea1af81fd
commit 47a95332a2
5 files changed
+431 -40

No files matched your search

@@ -0,0 +1,276 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { ArrowLeftIcon, ChevronRightIcon, LoaderCircleIcon, RotateCwIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { PierreEntryIcon } from "~/components/chat/PierreEntryIcon";
import {
Menu,
MenuGroup,
MenuItem,
MenuPopup,
MenuSeparator,
MenuTrigger,
} from "~/components/ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { useTheme } from "~/hooks/useTheme";
import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
import { cn } from "~/lib/utils";
import { isAbsolutePath } from "~/terminal-links";
import {
type FileBreadcrumb,
fileBreadcrumbChildren,
fileBreadcrumbParent,
fileBreadcrumbs,
} from "./filePath";
import { useProjectEntriesQuery } from "./projectFilesQueryState";
interface FileBreadcrumbsProps {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly onOpenFile: (relativePath: string) => void;
readonly projectName: string;
readonly relativePath: string;
readonly workspaceMutationId: string | null;
}
function pathLabel(path: string, projectName: string): string {
return path.slice(path.lastIndexOf("/") + 1) || projectName;
}
function BreadcrumbLabel(props: {
readonly current?: boolean;
readonly label: string;
readonly pathLabel: string;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<span
className={cn(
"block max-w-40 truncate rounded-sm px-0.5",
props.current ? "font-medium text-foreground" : "text-muted-foreground",
)}
/>
}
>
{props.label}
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-80">
{props.pathLabel}
</TooltipPopup>
</Tooltip>
);
}
function BreadcrumbMenuContent(props: {
readonly cwd: string;
readonly currentFilePath: string;
readonly directoryPath: string;
readonly environmentId: EnvironmentId;
readonly onDirectoryChange: (path: string) => void;
readonly onOpenChange: (open: boolean) => void;
readonly onOpenFile: (path: string) => void;
readonly projectName: string;
readonly rootPath: string;
readonly workspaceMutationId: string | null;
}) {
const entriesQuery = useProjectEntriesQuery(props.environmentId, props.cwd);
useWorkspaceMutationRefresh({
mutationId: props.workspaceMutationId,
refresh: entriesQuery.refresh,
resourceKey: `files:${props.environmentId}:${props.cwd}`,
});
const { resolvedTheme } = useTheme();
const entries = entriesQuery.data?.entries ?? [];
const entriesTruncated = entriesQuery.data?.truncated ?? false;
const children = useMemo(
() => fileBreadcrumbChildren(entries, props.directoryPath),
[entries, props.directoryPath],
);
const directoryAvailable =
props.directoryPath === "" ||
entries.some((entry) => entry.kind === "directory" && entry.path === props.directoryPath);
const parentPath = fileBreadcrumbParent(props.directoryPath);
const canGoBack =
props.directoryPath !== props.rootPath &&
parentPath !== null &&
(props.rootPath === "" ||
parentPath === props.rootPath ||
parentPath.startsWith(`${props.rootPath}/`));
return (
<MenuPopup
align="start"
side="bottom"
className="w-max min-w-32 max-w-[min(19rem,var(--available-width))]"
onKeyDown={(event) => {
if (event.key !== "ArrowLeft" || !canGoBack || parentPath === null) return;
event.preventDefault();
event.stopPropagation();
props.onDirectoryChange(parentPath);
}}
>
{canGoBack && parentPath !== null ? (
<>
<MenuItem closeOnClick={false} onClick={() => props.onDirectoryChange(parentPath)}>
<ArrowLeftIcon />
<span className="truncate">Back to {pathLabel(parentPath, props.projectName)}</span>
</MenuItem>
<MenuSeparator />
</>
) : null}
<MenuGroup key={props.directoryPath}>
{entriesQuery.isPending && entriesQuery.data === null ? (
<MenuItem disabled>
<LoaderCircleIcon className="animate-spin" />
Loading folder…
</MenuItem>
) : entriesQuery.error && entriesQuery.data === null ? (
<MenuItem closeOnClick={false} onClick={entriesQuery.refresh}>
<RotateCwIcon />
<span className="min-w-0 flex-1 truncate">Retry loading folder</span>
</MenuItem>
) : !directoryAvailable && !entriesTruncated ? (
<MenuItem disabled>This folder is no longer available.</MenuItem>
) : children.length === 0 ? (
<MenuItem disabled>
{entriesTruncated
? "No entries from this folder are available in the partial workspace index."
: "This folder is empty."}
</MenuItem>
) : (
children.map((entry) => {
const isCurrentFile = entry.kind === "file" && entry.path === props.currentFilePath;
return (
<MenuItem
key={entry.path}
closeOnClick={entry.kind === "file"}
aria-current={isCurrentFile ? "page" : undefined}
className={cn(isCurrentFile && "bg-foreground/[0.08]")}
onClick={() => {
if (entry.kind === "directory") {
props.onDirectoryChange(entry.path);
return;
}
props.onOpenChange(false);
props.onOpenFile(entry.path);
}}
>
<PierreEntryIcon pathValue={entry.path} kind={entry.kind} theme={resolvedTheme} />
<Tooltip>
<TooltipTrigger render={<span className="min-w-0 flex-1 truncate" />}>
{entry.label}
</TooltipTrigger>
<TooltipPopup side="right" className="max-w-80">
{entry.path}
</TooltipPopup>
</Tooltip>
{entry.kind === "directory" ? <ChevronRightIcon /> : null}
</MenuItem>
);
})
)}
</MenuGroup>
{entriesQuery.error && entriesQuery.data !== null ? (
<>
<MenuSeparator />
<MenuItem closeOnClick={false} onClick={entriesQuery.refresh}>
<RotateCwIcon />
Refresh failed — retry
</MenuItem>
</>
) : null}
{entriesTruncated ? (
<>
<MenuSeparator />
<MenuItem disabled>Some workspace entries are not shown.</MenuItem>
</>
) : null}
</MenuPopup>
);
}
function DirectoryBreadcrumb(props: FileBreadcrumbsProps & { readonly crumb: FileBreadcrumb }) {
const [open, setOpen] = useState(false);
const [directoryPath, setDirectoryPath] = useState(props.crumb.path);
useEffect(() => {
setOpen(false);
setDirectoryPath(props.crumb.path);
}, [props.crumb.path, props.relativePath]);
const handleOpenChange = (nextOpen: boolean) => {
setOpen(nextOpen);
if (nextOpen) setDirectoryPath(props.crumb.path);
};
return (
<Menu open={open} onOpenChange={handleOpenChange}>
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<button
type="button"
aria-label={`Browse ${props.crumb.label}`}
className="relative block max-w-40 cursor-pointer rounded-sm px-0.5 text-left text-muted-foreground outline-none pointer-coarse:after:-inset-y-3 pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-popup-open:bg-accent data-popup-open:text-foreground"
/>
}
/>
}
>
<span className="block truncate">{props.crumb.label}</span>
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-80">
{props.crumb.path || props.projectName}
</TooltipPopup>
</Tooltip>
{open ? (
<BreadcrumbMenuContent
cwd={props.cwd}
currentFilePath={props.relativePath}
directoryPath={directoryPath}
environmentId={props.environmentId}
onDirectoryChange={setDirectoryPath}
onOpenChange={handleOpenChange}
onOpenFile={props.onOpenFile}
projectName={props.projectName}
rootPath={props.crumb.path}
workspaceMutationId={props.workspaceMutationId}
/>
) : null}
</Menu>
);
}
export function FileBreadcrumbs(props: FileBreadcrumbsProps) {
const hostPath = isAbsolutePath(props.relativePath);
const breadcrumbs = useMemo(
() => fileBreadcrumbs(props.projectName, props.relativePath),
[props.projectName, props.relativePath],
);
return breadcrumbs.map((crumb, index) => (
<div
key={crumb.path || "project"}
className="flex min-w-0 shrink-0 items-center"
data-current-file-crumb={crumb.kind === "file"}
>
{index > 0 ? (
<ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
) : null}
{crumb.kind === "file" ? (
<span aria-current="page">
<BreadcrumbLabel current label={crumb.label} pathLabel={crumb.path} />
</span>
) : hostPath ? (
<BreadcrumbLabel label={crumb.label} pathLabel={crumb.path} />
) : (
<DirectoryBreadcrumb {...props} crumb={crumb} />
)}
</div>
));
}
@@ -16,7 +16,7 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
import { Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -49,6 +49,7 @@ import { useAtomCommand } from "~/state/use-atom-command";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
import FileBrowserPanel from "./FileBrowserPanel";
import { FileBreadcrumbs } from "./FileBreadcrumbs";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import {
type FileCommentAnnotationEntry,
@@ -63,7 +64,6 @@ import { installFileEditorDismissal } from "./fileEditorDismissal";
import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
import { projectFileCacheKey, projectFileEditorCacheKey } from "./fileContentRevision";
import { fileBreadcrumbs } from "./filePath";
import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";
import { FileSaveCoordinator } from "./fileSaveCoordinator";
import {
@@ -991,10 +991,6 @@ export default function FilePreviewPanel({
isPreviewSupportedInRuntime() &&
isBrowserPreviewFile(relativePath);
const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
const breadcrumbs = useMemo(
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
[projectName, relativePath],
);
const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
useWorkspaceMutationRefresh({
enabled: relativePath !== null && !isMedia && !isPdf && !selectedFilePending,
@@ -1062,36 +1058,14 @@ export default function FilePreviewPanel({
data-file-breadcrumbs
>
<div className="flex h-full w-max min-w-full items-center text-xs">
{breadcrumbs.map((crumb, index) => (
<div
key={crumb.path || "project"}
className="flex min-w-0 shrink-0 items-center"
data-current-file-crumb={crumb.kind === "file"}
>
{index > 0 ? (
<ChevronRight className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
) : null}
<Tooltip>
<TooltipTrigger
render={
<span
className={cn(
"max-w-40 truncate",
crumb.kind === "file"
? "font-medium text-foreground"
: "text-muted-foreground",
)}
/>
}
>
{crumb.label}
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-80">
{crumb.path || projectName}
</TooltipPopup>
</Tooltip>
</div>
))}
<FileBreadcrumbs
cwd={cwd}
environmentId={environmentId}
onOpenFile={onOpenFile}
projectName={projectName}
relativePath={relativePath}
workspaceMutationId={workspaceMutationId}
/>
</div>
</ScrollArea>
{absolutePath &&
+50 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { fileBreadcrumbs } from "./filePath";
import { fileBreadcrumbChildren, fileBreadcrumbParent, fileBreadcrumbs } from "./filePath";
describe("fileBreadcrumbs", () => {
it("builds project, directory, and file crumbs", () => {
@@ -39,3 +39,52 @@ describe("fileBreadcrumbs", () => {
]);
});
});
describe("fileBreadcrumbChildren", () => {
const entries = [
{ path: "README.md", kind: "file" as const },
{ path: "src", kind: "directory" as const },
{ path: "src-old", kind: "directory" as const },
{ path: "src/index.ts", kind: "file" as const },
{ path: "src/lib", kind: "directory" as const },
{ path: "src/lib/file10.ts", kind: "file" as const },
{ path: "src/lib/file2.ts", kind: "file" as const },
{ path: "src-old/index.ts", kind: "file" as const },
];
it("returns only the immediate children of the project root", () => {
expect(fileBreadcrumbChildren(entries, "")).toEqual([
{ path: "src", kind: "directory", label: "src" },
{ path: "src-old", kind: "directory", label: "src-old" },
{ path: "README.md", kind: "file", label: "README.md" },
]);
});
it("honors segment boundaries and sorts folders before files", () => {
expect(fileBreadcrumbChildren(entries, "src")).toEqual([
{ path: "src/lib", kind: "directory", label: "lib" },
{ path: "src/index.ts", kind: "file", label: "index.ts" },
]);
});
it("uses natural file-name ordering", () => {
expect(fileBreadcrumbChildren(entries, "src/lib").map((entry) => entry.label)).toEqual([
"file2.ts",
"file10.ts",
]);
});
it("returns an empty list for an empty or missing directory", () => {
expect(fileBreadcrumbChildren(entries, "missing")).toEqual([]);
});
});
describe("fileBreadcrumbParent", () => {
it.each([
["src/lib", "src"],
["src", ""],
["", null],
])("returns the parent of %j", (path, expected) => {
expect(fileBreadcrumbParent(path)).toBe(expected);
});
});
+32
View File
@@ -1,3 +1,4 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { isWindowsAbsolutePath } from "@t3tools/shared/path";
import { isAbsolutePath } from "~/terminal-links";
@@ -8,6 +9,10 @@ export interface FileBreadcrumb {
kind: "project" | "directory" | "file";
}
export interface FileBreadcrumbChild extends ProjectEntry {
label: string;
}
/**
* Crumbs for a workspace-relative path start at the project. An absolute host
* path is outside the workspace, so its crumbs start at the filesystem root.
@@ -26,3 +31,30 @@ export function fileBreadcrumbs(projectName: string, relativePath: string): File
})),
];
}
export function fileBreadcrumbChildren(
entries: readonly ProjectEntry[],
directoryPath: string,
): FileBreadcrumbChild[] {
const prefix = directoryPath ? `${directoryPath}/` : "";
return entries
.flatMap((entry) => {
if (!entry.path.startsWith(prefix)) return [];
const label = entry.path.slice(prefix.length);
if (!label || label.includes("/")) return [];
return [{ ...entry, label }];
})
.toSorted((left, right) => {
if (left.kind !== right.kind) return left.kind === "directory" ? -1 : 1;
return left.label.localeCompare(right.label, undefined, {
numeric: true,
sensitivity: "base",
});
});
}
export function fileBreadcrumbParent(directoryPath: string): string | null {
if (!directoryPath) return null;
const separatorIndex = directoryPath.lastIndexOf("/");
return separatorIndex === -1 ? "" : directoryPath.slice(0, separatorIndex);
}
@@ -1,4 +1,8 @@
import { EnvironmentId, type ProjectReadFileResult } from "@t3tools/contracts";
import {
EnvironmentId,
type ProjectListEntriesResult,
type ProjectReadFileResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -71,7 +75,7 @@ vi.mock("~/state/queries", () => ({
}));
import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
import { useProjectFileQuery } from "./projectFilesQueryState";
import { useProjectEntriesQuery, useProjectFileQuery } from "./projectFilesQueryState";
const environmentId = EnvironmentId.make("environment-1");
@@ -92,13 +96,20 @@ function file(contents: string): ProjectReadFileResult {
};
}
function projectEntries(paths: readonly string[]): ProjectListEntriesResult {
return {
entries: paths.map((path) => ({ path, kind: "file" })),
truncated: false,
};
}
async function flushEffects(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe("project file query refresh", () => {
describe("project query refresh", () => {
beforeEach(() => {
projectMocks.listEntries.mockReset();
projectMocks.optimisticFile.mockReset();
@@ -158,6 +169,55 @@ describe("project file query refresh", () => {
}
});
it("revalidates cached entries when a workspace mutation is observed after mounting", async () => {
const requests: Array<ReturnType<typeof deferred<ProjectListEntriesResult>>> = [];
const entriesAtom = Atom.make(
Effect.promise(() => {
const request = deferred<ProjectListEntriesResult>();
requests.push(request);
return request.promise;
}),
).pipe(Atom.swr({ staleTime: 30_000, revalidateOnMount: true }));
const registry = AtomRegistry.make();
const unmount = registry.mount(entriesAtom);
projectMocks.listEntries.mockReturnValue(entriesAtom);
atomHooks.registry = registry;
let renderedPaths: readonly string[] = [];
const render = (mutationId: string | null) => {
reactHooks.beginRender();
const query = useProjectEntriesQuery(environmentId, "/repo");
renderedPaths = query.data?.entries.map((entry) => entry.path) ?? [];
useWorkspaceMutationRefresh({
mutationId,
refresh: query.refresh,
resourceKey: "files:environment-1:/repo",
});
};
try {
await flushEffects();
expect(requests).toHaveLength(1);
requests[0]!.resolve(projectEntries(["src/old.ts"]));
await flushEffects();
render("mutation-1");
expect(renderedPaths).toEqual(["src/old.ts"]);
await flushEffects();
expect(requests).toHaveLength(2);
requests[1]!.resolve(projectEntries(["src/new.ts"]));
await flushEffects();
render("mutation-1");
expect(renderedPaths).toEqual(["src/new.ts"]);
expect(requests).toHaveLength(2);
} finally {
unmount();
registry.dispose();
atomHooks.registry = null;
}
});
it("does not issue a file read for a disabled image preview", async () => {
const requests: Array<ReturnType<typeof deferred<ProjectReadFileResult>>> = [];
const readAtom = Atom.make(