Add workspace file browser and preview panel (#3087)
This commit is contained in:
1 parent
477795697d
commit
de8bdc10fa
62 files changed
+2850
-9551
No files matched your search
@@ -4357,6 +4357,42 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.listEntries and projects.readFile", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-files-" });
|
||||
yield* fs.makeDirectory(path.join(workspaceDir, "src"), { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(workspaceDir, "src", "index.ts"),
|
||||
"export const answer = 42;\n",
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
Effect.all({
|
||||
listing: client[WS_METHODS.projectsListEntries]({ cwd: workspaceDir }),
|
||||
file: client[WS_METHODS.projectsReadFile]({
|
||||
cwd: workspaceDir,
|
||||
relativePath: "src/index.ts",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isTrue(response.listing.entries.some((entry) => entry.path === "src/index.ts"));
|
||||
assert.deepEqual(response.file, {
|
||||
relativePath: "src/index.ts",
|
||||
contents: "export const answer = 42;\n",
|
||||
byteLength: 26,
|
||||
truncated: false,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -87,6 +87,35 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("list", () => {
|
||||
it.effect("returns the complete cached workspace index", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "README.md");
|
||||
yield* writeTextFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const result = yield* workspaceEntries.list({ cwd });
|
||||
|
||||
expect(result.entries).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ path: "src", kind: "directory" },
|
||||
{ path: "src/components", kind: "directory", parentPath: "src" },
|
||||
{
|
||||
path: "src/components/Composer.tsx",
|
||||
kind: "file",
|
||||
parentPath: "src/components",
|
||||
},
|
||||
{ path: "README.md", kind: "file" },
|
||||
]),
|
||||
);
|
||||
expect(result.entries.some((entry) => entry.path.startsWith("node_modules"))).toBe(false);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("search", () => {
|
||||
it.effect("returns files and directories relative to cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -530,9 +530,24 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const list: WorkspaceEntriesShape["list"] = Effect.fn("WorkspaceEntries.list")(function* (input) {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe(
|
||||
Effect.map((index) => ({
|
||||
entries: index.entries.map(({ path: entryPath, kind, parentPath }) => ({
|
||||
path: entryPath,
|
||||
kind,
|
||||
...(parentPath ? { parentPath } : {}),
|
||||
})),
|
||||
truncated: index.truncated,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
browse,
|
||||
invalidate,
|
||||
list,
|
||||
search,
|
||||
} satisfies WorkspaceEntriesShape;
|
||||
});
|
||||
|
||||
@@ -54,6 +54,64 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => {
|
||||
describe("readFile", () => {
|
||||
it.effect("reads UTF-8 files relative to the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "src/index.ts", "export const answer = 42;\n");
|
||||
|
||||
const result = yield* workspaceFileSystem.readFile({
|
||||
cwd,
|
||||
relativePath: "src/index.ts",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
relativePath: "src/index.ts",
|
||||
contents: "export const answer = 42;\n",
|
||||
byteLength: 26,
|
||||
truncated: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects reads outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
|
||||
const error = yield* workspaceFileSystem
|
||||
.readFile({ cwd, relativePath: "../escape.md" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects symlinks that resolve outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* makeTempDir;
|
||||
const outsideDir = yield* makeTempDir;
|
||||
yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
|
||||
yield* fileSystem.symlink(
|
||||
path.join(outsideDir, "secret.txt"),
|
||||
path.join(cwd, "linked-secret.txt"),
|
||||
);
|
||||
|
||||
const error = yield* workspaceFileSystem
|
||||
.readFile({ cwd, relativePath: "linked-secret.txt" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("resolves outside the project root");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("writeFile", () => {
|
||||
it.effect("writes files relative to the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import fsPromises from "node:fs/promises";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -11,12 +14,74 @@ import {
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
|
||||
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
export const makeWorkspaceFileSystem = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const readFile: WorkspaceFileSystemShape["readFile"] = Effect.fn("WorkspaceFileSystem.readFile")(
|
||||
function* (input) {
|
||||
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const [realWorkspaceRoot, realTargetPath] = await Promise.all([
|
||||
fsPromises.realpath(input.cwd),
|
||||
fsPromises.realpath(target.absolutePath),
|
||||
]);
|
||||
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
|
||||
if (
|
||||
relativeRealPath.startsWith(`..${path.sep}`) ||
|
||||
relativeRealPath === ".." ||
|
||||
path.isAbsolute(relativeRealPath)
|
||||
) {
|
||||
throw new Error("Workspace file path resolves outside the project root.");
|
||||
}
|
||||
|
||||
const handle = await fsPromises.open(realTargetPath, "r");
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile()) {
|
||||
throw new Error("Workspace path is not a file.");
|
||||
}
|
||||
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
|
||||
const buffer = Buffer.alloc(bytesToRead);
|
||||
const { bytesRead } = await handle.read(buffer, 0, bytesToRead, 0);
|
||||
const fileBytes = buffer.subarray(0, bytesRead);
|
||||
if (fileBytes.includes(0)) {
|
||||
throw new Error("Binary files cannot be previewed as text.");
|
||||
}
|
||||
const contents = new TextDecoder("utf-8").decode(fileBytes);
|
||||
return {
|
||||
relativePath: target.relativePath,
|
||||
contents,
|
||||
byteLength: stat.size,
|
||||
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
|
||||
};
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemError({
|
||||
cwd: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
operation: "workspaceFileSystem.readFile",
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return result;
|
||||
},
|
||||
);
|
||||
|
||||
const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn(
|
||||
"WorkspaceFileSystem.writeFile",
|
||||
)(function* (input) {
|
||||
@@ -52,7 +117,7 @@ export const makeWorkspaceFileSystem = Effect.gen(function* () {
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
return { relativePath: target.relativePath };
|
||||
});
|
||||
return { writeFile } satisfies WorkspaceFileSystemShape;
|
||||
return { readFile, writeFile } satisfies WorkspaceFileSystemShape;
|
||||
});
|
||||
|
||||
export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem);
|
||||
@@ -13,6 +13,8 @@ import type * as Effect from "effect/Effect";
|
||||
import type {
|
||||
FilesystemBrowseInput,
|
||||
FilesystemBrowseResult,
|
||||
ProjectListEntriesInput,
|
||||
ProjectListEntriesResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -50,6 +52,13 @@ export interface WorkspaceEntriesShape {
|
||||
input: FilesystemBrowseInput,
|
||||
) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
|
||||
|
||||
/**
|
||||
* List the cached workspace index for a project root.
|
||||
*/
|
||||
readonly list: (
|
||||
input: ProjectListEntriesInput,
|
||||
) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
|
||||
|
||||
/**
|
||||
* Search indexed workspace entries for files and directories matching the
|
||||
* provided query.
|
||||
|
||||
@@ -10,7 +10,12 @@ import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts";
|
||||
import type {
|
||||
ProjectReadFileInput,
|
||||
ProjectReadFileResult,
|
||||
ProjectWriteFileInput,
|
||||
ProjectWriteFileResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts";
|
||||
|
||||
export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceFileSystemError>()(
|
||||
@@ -22,12 +27,26 @@ export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceF
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspaceFileSystemShape - Service API for workspace-relative file operations.
|
||||
*/
|
||||
export interface WorkspaceFileSystemShape {
|
||||
/**
|
||||
* Read a UTF-8 text file relative to the workspace root.
|
||||
*/
|
||||
readonly readFile: (
|
||||
input: ProjectReadFileInput,
|
||||
) => Effect.Effect<
|
||||
ProjectReadFileResult,
|
||||
WorkspaceFileSystemError | WorkspacePathOutsideRootError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Write a file relative to the workspace root.
|
||||
*
|
||||
|
||||
@@ -34,6 +34,8 @@ import {
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectListEntriesError,
|
||||
ProjectReadFileError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
RelayClientInstallFailedError,
|
||||
@@ -160,6 +162,8 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.sourceControlCloneRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsListEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsReadFile, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
@@ -1172,6 +1176,33 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsListEntries]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsListEntries,
|
||||
workspaceEntries.list(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectListEntriesError({
|
||||
message: `Failed to list workspace entries: ${cause.detail}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsReadFile]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsReadFile,
|
||||
workspaceFileSystem.readFile(input).pipe(
|
||||
Effect.mapError((cause) => {
|
||||
const message = isWorkspacePathOutsideRootError(cause)
|
||||
? "Workspace file path must stay within the project root."
|
||||
: `Failed to read workspace file: ${cause.detail}`;
|
||||
return new ProjectReadFileError({ message, cause });
|
||||
}),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsWriteFile]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsWriteFile,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Third-Party Notices
|
||||
|
||||
## vscode-icons
|
||||
|
||||
The custom file icon symbols in `src/pierre-icons.ts` are adapted from the
|
||||
[`vscode-icons`](https://github.com/vscode-icons/vscode-icons) project.
|
||||
|
||||
Copyright (c) 2016 Roberto Huertas
|
||||
|
||||
Licensed under the MIT License. The full license text is available in the
|
||||
upstream repository: <https://github.com/vscode-icons/vscode-icons/blob/master/LICENSE>.
|
||||
@@ -27,6 +27,7 @@
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
|
||||
@@ -50,6 +50,7 @@ vi.mock("../browser/openFileInPreview", async (importOriginal) => ({
|
||||
import ChatMarkdown from "./ChatMarkdown";
|
||||
import { serializeTableElementToCsv, serializeTableElementToMarkdown } from "../markdown-clipboard";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
|
||||
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("environment-test"),
|
||||
@@ -63,6 +64,7 @@ describe("ChatMarkdown", () => {
|
||||
openUrlInPreviewMock.mockClear();
|
||||
contextMenuShowMock.mockReset();
|
||||
readLocalApiMock.mockClear();
|
||||
useRightPanelStore.setState({ byThreadKey: {} });
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
@@ -248,6 +250,92 @@ describe("ChatMarkdown", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens code file links in the right-panel file preview", async () => {
|
||||
const screen = await render(
|
||||
<ChatMarkdown
|
||||
text="[ChatMarkdown.tsx](apps/web/src/components/ChatMarkdown.tsx#L978)"
|
||||
cwd="/repo/project"
|
||||
threadRef={threadRef}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
await page.getByRole("link", { name: "ChatMarkdown.tsx · L978" }).click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(
|
||||
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef),
|
||||
).toMatchObject({
|
||||
isOpen: true,
|
||||
activeSurfaceId: "file:apps/web/src/components/ChatMarkdown.tsx",
|
||||
});
|
||||
expect(openInPreferredEditorMock).not.toHaveBeenCalled();
|
||||
expect(openFileInPreviewMock).not.toHaveBeenCalled();
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens HTML and PDF file links in the integrated browser preview", async () => {
|
||||
const screen = await render(
|
||||
<ChatMarkdown
|
||||
text="[report.html](report.html) [report.pdf](report.pdf)"
|
||||
cwd="/repo/project"
|
||||
threadRef={threadRef}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
await page.getByRole("link", { name: "report.html" }).click();
|
||||
await page.getByRole("link", { name: "report.pdf" }).click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(openFileInPreviewMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
threadRef,
|
||||
"/repo/project/report.html",
|
||||
);
|
||||
expect(openFileInPreviewMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
threadRef,
|
||||
"/repo/project/report.pdf",
|
||||
);
|
||||
expect(openInPreferredEditorMock).not.toHaveBeenCalled();
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps opening file links in the editor from the context menu", async () => {
|
||||
contextMenuShowMock.mockResolvedValue("open");
|
||||
const filePath = "/repo/project/src/index.ts";
|
||||
const screen = await render(
|
||||
<ChatMarkdown text="[index.ts](src/index.ts)" cwd="/repo/project" threadRef={threadRef} />,
|
||||
);
|
||||
|
||||
try {
|
||||
page
|
||||
.getByRole("link", { name: "index.ts" })
|
||||
.element()
|
||||
.dispatchEvent(
|
||||
new MouseEvent("contextmenu", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 4,
|
||||
clientY: 8,
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), filePath);
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a favicon with the leading segment of a wrapping URL", async () => {
|
||||
const url = "https://github.com/pingdotgg/t3code/pull/3017/changes";
|
||||
const screen = await render(
|
||||
@@ -429,7 +517,7 @@ describe("ChatMarkdown", () => {
|
||||
|
||||
// Language with a known icon: icon XOR text — never the redundant pair.
|
||||
const languageOnly = titles[0]!;
|
||||
const hasIcon = languageOnly.querySelector("img") != null;
|
||||
const hasIcon = languageOnly.querySelector("svg[data-pierre-icon]") != null;
|
||||
const hasText = (languageOnly.textContent ?? "").includes("ts");
|
||||
expect(hasIcon || hasText).toBe(true);
|
||||
expect(hasIcon && hasText).toBe(false);
|
||||
@@ -446,7 +534,7 @@ describe("ChatMarkdown", () => {
|
||||
expect(titles[1]!.textContent).toBe("src/main.ts");
|
||||
|
||||
// Unknown language: no icon attempt, text label.
|
||||
expect(titles[2]!.querySelector("img")).toBeNull();
|
||||
expect(titles[2]!.querySelector("svg[data-pierre-icon]")).toBeNull();
|
||||
expect(titles[2]!.textContent).toBe("text");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
|
||||
@@ -33,12 +33,8 @@ import remarkBreaks from "remark-breaks";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
|
||||
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
|
||||
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import {
|
||||
getVscodeIconUrlForEntry,
|
||||
hasSpecificVscodeIconForFileName,
|
||||
syntheticFileNameForLanguageId,
|
||||
} from "../vscode-icons";
|
||||
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
||||
import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { Button } from "./ui/button";
|
||||
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsible";
|
||||
@@ -62,6 +58,7 @@ import {
|
||||
} from "../markdown-links";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { cn } from "../lib/utils";
|
||||
import { useRightPanelStore } from "../rightPanelStore";
|
||||
import { isPreviewSupportedInRuntime } from "../previewStateStore";
|
||||
import {
|
||||
isBrowserPreviewFile,
|
||||
@@ -443,22 +440,17 @@ function MarkdownCodeBlockTitleContent({
|
||||
language: string;
|
||||
theme: "light" | "dark";
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
|
||||
if (fenceTitle) {
|
||||
return (
|
||||
<>
|
||||
<VscodeEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
|
||||
<PierreEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
|
||||
<span className="truncate">{fenceTitle}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const fileName = syntheticFileNameForLanguageId(language);
|
||||
const iconUrl = hasSpecificVscodeIconForFileName(fileName, theme)
|
||||
? getVscodeIconUrlForEntry(fileName, "file", theme)
|
||||
: null;
|
||||
if (!iconUrl || failedIconUrl === iconUrl) {
|
||||
if (!hasSpecificPierreIconForFileName(fileName)) {
|
||||
return <span className="truncate">{language}</span>;
|
||||
}
|
||||
return (
|
||||
@@ -468,15 +460,7 @@ function MarkdownCodeBlockTitleContent({
|
||||
<span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
|
||||
}
|
||||
>
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden
|
||||
className="size-3.5 shrink-0"
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
<PierreEntryIcon pathValue={fileName} kind="file" theme={theme} className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{language}</TooltipPopup>
|
||||
</Tooltip>
|
||||
@@ -674,6 +658,7 @@ interface MarkdownFileLinkProps {
|
||||
targetPath: string;
|
||||
iconPath: string;
|
||||
displayPath: string;
|
||||
workspaceRelativePath: string | null;
|
||||
label: string;
|
||||
copyMarkdown: string;
|
||||
theme: "light" | "dark";
|
||||
@@ -997,13 +982,14 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
targetPath,
|
||||
iconPath,
|
||||
displayPath,
|
||||
workspaceRelativePath,
|
||||
label,
|
||||
copyMarkdown,
|
||||
theme,
|
||||
threadRef,
|
||||
className,
|
||||
}: MarkdownFileLinkProps) {
|
||||
const handleOpen = useCallback(() => {
|
||||
const handleOpenInEditor = useCallback(() => {
|
||||
const api = readLocalApi();
|
||||
if (!api) {
|
||||
toastManager.add({
|
||||
@@ -1024,6 +1010,14 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
});
|
||||
}, [targetPath]);
|
||||
|
||||
const handleOpenInFilePreview = useCallback(() => {
|
||||
if (!threadRef || !workspaceRelativePath) {
|
||||
handleOpenInEditor();
|
||||
return;
|
||||
}
|
||||
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath);
|
||||
}, [handleOpenInEditor, threadRef, workspaceRelativePath]);
|
||||
|
||||
const handleOpenInBrowser = useCallback(() => {
|
||||
if (!threadRef) return;
|
||||
void openFileInPreview(threadRef, iconPath).catch((error) => {
|
||||
@@ -1092,7 +1086,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
);
|
||||
|
||||
if (clicked === "open") {
|
||||
handleOpen();
|
||||
handleOpenInEditor();
|
||||
return;
|
||||
}
|
||||
if (clicked === "open-in-browser") {
|
||||
@@ -1107,7 +1101,15 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
handleCopy(targetPath, "Full path");
|
||||
}
|
||||
},
|
||||
[displayPath, handleCopy, handleOpen, handleOpenInBrowser, iconPath, targetPath, threadRef],
|
||||
[
|
||||
displayPath,
|
||||
handleCopy,
|
||||
handleOpenInBrowser,
|
||||
handleOpenInEditor,
|
||||
iconPath,
|
||||
targetPath,
|
||||
threadRef,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -1121,7 +1123,11 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleOpen();
|
||||
if (threadRef && isPreviewSupportedInRuntime() && isBrowserPreviewFile(iconPath)) {
|
||||
handleOpenInBrowser();
|
||||
return;
|
||||
}
|
||||
handleOpenInFilePreview();
|
||||
}}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
@@ -1150,6 +1156,7 @@ function areMarkdownFileLinkPropsEqual(
|
||||
previous.targetPath === next.targetPath &&
|
||||
previous.iconPath === next.iconPath &&
|
||||
previous.displayPath === next.displayPath &&
|
||||
previous.workspaceRelativePath === next.workspaceRelativePath &&
|
||||
previous.label === next.label &&
|
||||
previous.copyMarkdown === next.copyMarkdown &&
|
||||
previous.theme === next.theme &&
|
||||
@@ -1274,6 +1281,7 @@ function ChatMarkdown({
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
iconPath={fileLinkMeta.filePath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
|
||||
label={labelParts.join(" · ")}
|
||||
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
|
||||
theme={resolvedTheme}
|
||||
|
||||
@@ -53,7 +53,7 @@ import {
|
||||
resetSavedEnvironmentRuntimeStoreForTests,
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
} from "../environments/runtime";
|
||||
} from "../environments/runtime/catalog";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
@@ -2110,6 +2110,360 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps panel toggles fixed and can maximize the right panel", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: WIDE_FOOTER_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-maximize-right-panel" as MessageId,
|
||||
targetText: "maximize right panel",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const terminalToggle = await waitForElement(
|
||||
() =>
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Toggle terminal drawer"]'),
|
||||
"Unable to find terminal drawer toggle.",
|
||||
);
|
||||
const rightPanelToggle = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Toggle right panel"]'),
|
||||
"Unable to find right panel toggle.",
|
||||
);
|
||||
const headerActions = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-chat-header-actions]"),
|
||||
"Unable to find chat header actions.",
|
||||
);
|
||||
const chatHeader = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-chat-header]"),
|
||||
"Unable to find chat header.",
|
||||
);
|
||||
const panelLayoutControls = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-panel-layout-controls]"),
|
||||
"Unable to find panel layout controls.",
|
||||
);
|
||||
expect(chatHeader.getBoundingClientRect().height).toBe(52);
|
||||
expect(panelLayoutControls.getBoundingClientRect().height).toBe(52);
|
||||
expect(panelLayoutControls.getBoundingClientRect().top).toBe(
|
||||
chatHeader.getBoundingClientRect().top,
|
||||
);
|
||||
const initialTerminalRect = terminalToggle.getBoundingClientRect();
|
||||
const initialRightPanelRect = rightPanelToggle.getBoundingClientRect();
|
||||
const initialControlRects = [initialTerminalRect, initialRightPanelRect];
|
||||
expect(document.querySelector('button[aria-label="Maximize panel"]')).toBeNull();
|
||||
expect(initialControlRects.every((rect) => rect.width === 28 && rect.height === 28)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(initialControlRects.every((rect) => rect.top === initialControlRects[0]?.top)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(initialRightPanelRect.left - initialTerminalRect.right).toBe(4);
|
||||
expect(
|
||||
initialTerminalRect.left -
|
||||
(headerActions.lastElementChild?.getBoundingClientRect().right ?? Number.NaN),
|
||||
).toBe(4);
|
||||
|
||||
document.documentElement.classList.add("wco");
|
||||
expect(panelLayoutControls.getBoundingClientRect().height).toBe(52);
|
||||
expect(panelLayoutControls.getBoundingClientRect().top).toBe(
|
||||
chatHeader.getBoundingClientRect().top,
|
||||
);
|
||||
document.documentElement.classList.remove("wco");
|
||||
|
||||
rightPanelToggle.click();
|
||||
|
||||
const maximizeButton = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Maximize panel"]'),
|
||||
"Unable to find maximize panel button.",
|
||||
);
|
||||
const rightPanelTabbar = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-right-panel-tabbar]"),
|
||||
"Unable to find right panel tab bar.",
|
||||
);
|
||||
const maximizeRect = maximizeButton.getBoundingClientRect();
|
||||
const rightPanelTabbarRect = rightPanelTabbar.getBoundingClientRect();
|
||||
expect(document.querySelector('button[aria-label="Add panel surface"]')).toBeNull();
|
||||
expect(rightPanelTabbarRect.height).toBe(52);
|
||||
expect(rightPanelTabbarRect.top).toBe(chatHeader.getBoundingClientRect().top);
|
||||
expect(maximizeRect.width).toBe(28);
|
||||
expect(maximizeRect.height).toBe(28);
|
||||
expect(maximizeRect.top).toBe(initialTerminalRect.top);
|
||||
expect(initialTerminalRect.left - maximizeRect.right).toBe(4);
|
||||
expect(terminalToggle.getBoundingClientRect().left).toBeCloseTo(initialTerminalRect.left, 1);
|
||||
expect(rightPanelToggle.getBoundingClientRect().left).toBeCloseTo(
|
||||
initialRightPanelRect.left,
|
||||
1,
|
||||
);
|
||||
|
||||
useRightPanelStore.getState().openFile(THREAD_REF, "components.json");
|
||||
const fileTabIcon = await waitForElement(
|
||||
() =>
|
||||
document.querySelector<SVGElement>(
|
||||
'[data-right-panel-tabbar] [data-pierre-icon][data-icon-token="json"]',
|
||||
),
|
||||
"Unable to find the Pierre file icon in the file tab.",
|
||||
);
|
||||
expect(fileTabIcon.closest("button")?.textContent).toContain("components.json");
|
||||
|
||||
document.documentElement.classList.add("wco");
|
||||
expect(rightPanelTabbar.getBoundingClientRect().height).toBe(
|
||||
panelLayoutControls.getBoundingClientRect().height,
|
||||
);
|
||||
expect(rightPanelTabbar.getBoundingClientRect().top).toBe(
|
||||
panelLayoutControls.getBoundingClientRect().top,
|
||||
);
|
||||
document.documentElement.classList.remove("wco");
|
||||
|
||||
maximizeButton.click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const chatColumn = document.querySelector<HTMLElement>(
|
||||
'[data-chat-column-maximized-away="true"]',
|
||||
);
|
||||
const panel = document.querySelector<HTMLElement>(
|
||||
'[data-preview-panel-mode="inline"][data-preview-panel-maximized="true"]',
|
||||
);
|
||||
expect(chatColumn?.getBoundingClientRect().width).toBe(0);
|
||||
expect(panel?.getBoundingClientRect().width).toBeGreaterThan(1_000);
|
||||
expect(
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Restore panel size"]'),
|
||||
).not.toBeNull();
|
||||
expect(terminalToggle.getBoundingClientRect().left).toBeCloseTo(
|
||||
initialTerminalRect.left,
|
||||
1,
|
||||
);
|
||||
expect(rightPanelToggle.getBoundingClientRect().left).toBeCloseTo(
|
||||
initialRightPanelRect.left,
|
||||
1,
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("scrolls file tabs and preserves the workspace explorer across file previews", async () => {
|
||||
const workspaceEntries = [
|
||||
{ path: "src", kind: "directory" as const },
|
||||
{ path: "src/index.ts", kind: "file" as const },
|
||||
{ path: "src/router.ts", kind: "file" as const },
|
||||
{ path: "src/store.ts", kind: "file" as const },
|
||||
{ path: "src/styles.css", kind: "file" as const },
|
||||
{ path: "src/large.ts", kind: "file" as const },
|
||||
{ path: "e2e", kind: "directory" as const },
|
||||
{ path: "e2e/test-results", kind: "directory" as const },
|
||||
{
|
||||
path: "e2e/test-results/playwright-integration-results",
|
||||
kind: "directory" as const,
|
||||
},
|
||||
{
|
||||
path: "e2e/test-results/playwright-integration-results/chromium-desktop-project",
|
||||
kind: "directory" as const,
|
||||
},
|
||||
{
|
||||
path: "e2e/test-results/playwright-integration-results/chromium-desktop-project/.last-run.json",
|
||||
kind: "file" as const,
|
||||
},
|
||||
{ path: "README.md", kind: "file" as const },
|
||||
{ path: "AGENTS.md", kind: "file" as const },
|
||||
{ path: "package.json", kind: "file" as const },
|
||||
{ path: "tsconfig.json", kind: "file" as const },
|
||||
];
|
||||
const mounted = await mountChatView({
|
||||
viewport: WIDE_FOOTER_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-file-tabs-and-tree-state" as MessageId,
|
||||
targetText: "keep file tabs readable and preserve tree state",
|
||||
}),
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.projectsListEntries) {
|
||||
return { entries: workspaceEntries, truncated: false };
|
||||
}
|
||||
if (body._tag === WS_METHODS.projectsReadFile) {
|
||||
const relativePath =
|
||||
typeof body.relativePath === "string" ? body.relativePath : "file.ts";
|
||||
const contents =
|
||||
relativePath === "src/large.ts"
|
||||
? Array.from(
|
||||
{ length: 5_000 },
|
||||
(_, index) => `export const line${index + 1} = ${index + 1};`,
|
||||
).join("\n")
|
||||
: `// ${relativePath}\n`;
|
||||
return {
|
||||
relativePath,
|
||||
contents,
|
||||
byteLength: new TextEncoder().encode(contents).byteLength,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
useRightPanelStore.getState().open(THREAD_REF, "files");
|
||||
|
||||
const explorer = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-file-browser-panel]"),
|
||||
"Unable to find the workspace file explorer.",
|
||||
);
|
||||
|
||||
for (const entry of workspaceEntries) {
|
||||
if (entry.kind === "file") {
|
||||
useRightPanelStore.getState().openFile(THREAD_REF, entry.path);
|
||||
}
|
||||
}
|
||||
|
||||
const tabList = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-right-panel-tab-list]"),
|
||||
"Unable to find the right panel tab list.",
|
||||
);
|
||||
const tabViewport = await waitForElement(
|
||||
() => tabList.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]'),
|
||||
"Unable to find the right panel tab viewport.",
|
||||
);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const fileTabs = Array.from(tabList.querySelectorAll<HTMLElement>("[data-active-tab]"));
|
||||
expect(fileTabs.length).toBe(
|
||||
workspaceEntries.filter((entry) => entry.kind === "file").length,
|
||||
);
|
||||
expect(tabViewport.scrollWidth).toBeGreaterThan(tabViewport.clientWidth);
|
||||
expect(tabViewport.scrollLeft).toBeGreaterThan(0);
|
||||
expect(tabList.querySelector('[data-slot="scroll-area-scrollbar"]')).toBeNull();
|
||||
expect(
|
||||
fileTabs.every((tab) => {
|
||||
const width = tab.getBoundingClientRect().width;
|
||||
return width >= 100 && width <= 176;
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(document.querySelector<HTMLElement>("[data-file-browser-panel]")).toBe(explorer);
|
||||
});
|
||||
|
||||
useRightPanelStore.getState().openFile(THREAD_REF, "src/index.ts");
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector<HTMLElement>("[data-file-browser-panel]")).toBe(explorer);
|
||||
});
|
||||
|
||||
useRightPanelStore
|
||||
.getState()
|
||||
.openFile(
|
||||
THREAD_REF,
|
||||
"e2e/test-results/playwright-integration-results/chromium-desktop-project/.last-run.json",
|
||||
);
|
||||
await mounted.setContainerSize({ width: 800, height: WIDE_FOOTER_VIEWPORT.height });
|
||||
const breadcrumbs = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("[data-file-breadcrumbs]"),
|
||||
"Unable to find the responsive file breadcrumbs.",
|
||||
);
|
||||
const breadcrumbViewport = await waitForElement(
|
||||
() => breadcrumbs.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]'),
|
||||
"Unable to find the file breadcrumb viewport.",
|
||||
);
|
||||
const currentCrumb = await waitForElement(
|
||||
() =>
|
||||
Array.from(
|
||||
breadcrumbs.querySelectorAll<HTMLElement>("[data-current-file-crumb='true']"),
|
||||
).find((crumb) => crumb.textContent === ".last-run.json") ?? null,
|
||||
"Unable to find the current file breadcrumb.",
|
||||
);
|
||||
const explorerToggle = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Hide file explorer"]'),
|
||||
"Unable to find the file explorer toggle.",
|
||||
);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const viewportRect = breadcrumbViewport.getBoundingClientRect();
|
||||
const currentCrumbRect = currentCrumb.getBoundingClientRect();
|
||||
expect(breadcrumbViewport.scrollWidth).toBeGreaterThan(breadcrumbViewport.clientWidth);
|
||||
expect(breadcrumbViewport.scrollLeft).toBeGreaterThan(0);
|
||||
expect(breadcrumbs.querySelector('[data-slot="scroll-area-scrollbar"]')).toBeNull();
|
||||
expect(currentCrumbRect.right).toBeLessThanOrEqual(viewportRect.right + 1);
|
||||
expect(viewportRect.right).toBeLessThan(explorerToggle.getBoundingClientRect().left);
|
||||
expect(explorerToggle.getAttribute("aria-pressed")).toBe("true");
|
||||
expect(explorerToggle.getBoundingClientRect().width).toBe(28);
|
||||
expect(explorerToggle.getBoundingClientRect().height).toBe(28);
|
||||
});
|
||||
|
||||
const fileSearchButton = await waitForElement(
|
||||
() =>
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Search workspace files"]'),
|
||||
"Unable to find the workspace file search button.",
|
||||
);
|
||||
fileSearchButton.click();
|
||||
const fileTree = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>("file-tree-container"),
|
||||
"Unable to find the file tree host.",
|
||||
);
|
||||
const fileSearchInput = await waitForElement(
|
||||
() =>
|
||||
fileTree.shadowRoot?.querySelector<HTMLInputElement>("[data-file-tree-search-input]") ??
|
||||
null,
|
||||
"Unable to find the file tree search input.",
|
||||
);
|
||||
fileSearchInput.focus();
|
||||
const searchKeyEvent = new KeyboardEvent("keydown", {
|
||||
key: "r",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true,
|
||||
});
|
||||
fileSearchInput.dispatchEvent(searchKeyEvent);
|
||||
await waitForLayout();
|
||||
expect(searchKeyEvent.defaultPrevented).toBe(false);
|
||||
expect(fileTree.shadowRoot?.activeElement).toBe(fileSearchInput);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe("");
|
||||
|
||||
useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts");
|
||||
const codeVirtualizer = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>(".file-preview-virtualizer"),
|
||||
"Unable to find the virtualized file preview.",
|
||||
);
|
||||
expect(codeVirtualizer.querySelector("diffs-container")).not.toBeNull();
|
||||
expect(codeVirtualizer.classList.contains("overflow-auto")).toBe(true);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("removes persisted file tabs when a draft workspace no longer exists", async () => {
|
||||
const orphanedDraftId = DraftId.make("draft-orphaned-file-panel");
|
||||
const orphanedThreadId = "thread-orphaned-file-panel" as ThreadId;
|
||||
const orphanedThreadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, orphanedThreadId);
|
||||
useComposerDraftStore.getState().setProjectDraftThreadId(
|
||||
{
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
projectId: "project-deleted" as ProjectId,
|
||||
},
|
||||
orphanedDraftId,
|
||||
{ threadId: orphanedThreadId },
|
||||
);
|
||||
useRightPanelStore.getState().openFile(orphanedThreadRef, "conductor.json");
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: WIDE_FOOTER_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-orphaned-file-panel" as MessageId,
|
||||
targetText: "orphaned persisted file panel",
|
||||
}),
|
||||
initialPath: `/draft/${orphanedDraftId}`,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(
|
||||
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, orphanedThreadRef),
|
||||
).toEqual({
|
||||
isOpen: false,
|
||||
activeSurfaceId: null,
|
||||
surfaces: [],
|
||||
});
|
||||
expect(document.querySelector("[data-right-panel-tabbar]")).toBeNull();
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps multiple terminal panel surfaces separate from the bottom drawer", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: WIDE_FOOTER_VIEWPORT,
|
||||
@@ -2126,11 +2480,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
rightPanelToggle.click();
|
||||
|
||||
const addSurface = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Add panel surface"]'),
|
||||
"Unable to find add panel surface button.",
|
||||
);
|
||||
expect(document.body.textContent).toContain("Open a surface");
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent).toContain("Open a surface");
|
||||
});
|
||||
expect(document.querySelector('button[aria-label="Add panel surface"]')).toBeNull();
|
||||
expect(
|
||||
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF),
|
||||
).toEqual({
|
||||
@@ -2140,16 +2493,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.terminalOpen)).toBe(false);
|
||||
|
||||
addSurface.click();
|
||||
|
||||
const terminalItem = await waitForElement(
|
||||
const emptyStateTerminalButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(
|
||||
(item) => item.textContent?.trim() === "Terminal",
|
||||
Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) =>
|
||||
button.textContent?.includes("Start a shell in this workspace."),
|
||||
) ?? null,
|
||||
"Unable to find Terminal panel menu item.",
|
||||
"Unable to find the empty-state Terminal button.",
|
||||
);
|
||||
terminalItem.click();
|
||||
emptyStateTerminalButton.click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(
|
||||
@@ -2159,6 +2510,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
).toEqual(["term-1"]);
|
||||
});
|
||||
|
||||
const addSurface = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Add panel surface"]'),
|
||||
"Unable to find add panel surface button beside the tabs.",
|
||||
);
|
||||
addSurface.click();
|
||||
const secondTerminalItem = await waitForElement(
|
||||
() =>
|
||||
|
||||
@@ -35,7 +35,7 @@ import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useVcsStatus } from "~/lib/vcsStatusState";
|
||||
import { usePrimaryEnvironmentId } from "../environments/primary";
|
||||
import { usePrimaryEnvironmentId } from "../environments/primary/context";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { resolveAssetUrl } from "../assets/assetUrls";
|
||||
import { isElectron } from "../env";
|
||||
@@ -67,7 +67,7 @@ import {
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../pendingUserInput";
|
||||
import { selectProjectsAcrossEnvironments, useStore } from "../store";
|
||||
import { selectEnvironmentState, selectProjectsAcrossEnvironments, useStore } from "../store";
|
||||
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
@@ -111,6 +111,8 @@ const PreviewPanel = lazy(() =>
|
||||
import("./preview/PreviewPanel").then((mod) => ({ default: mod.PreviewPanel })),
|
||||
);
|
||||
const DiffPanel = lazy(() => import("./DiffPanel"));
|
||||
const FilePreviewPanel = lazy(() => import("./files/FilePreviewPanel"));
|
||||
const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();
|
||||
import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import PlanSidebar from "./PlanSidebar";
|
||||
@@ -137,10 +139,10 @@ import {
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import {
|
||||
reconnectSavedEnvironment,
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
} from "../environments/runtime";
|
||||
} from "../environments/runtime/catalog";
|
||||
import { reconnectSavedEnvironment } from "../environments/runtime/service";
|
||||
import { buildDraftThreadRouteParams } from "../threadRoutes";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
@@ -167,6 +169,7 @@ import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
|
||||
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
|
||||
import { MessagesTimeline } from "./chat/MessagesTimeline";
|
||||
import { ChatHeader } from "./chat/ChatHeader";
|
||||
import { PanelLayoutControls } from "./chat/PanelLayoutControls";
|
||||
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
|
||||
import { NoActiveThreadState } from "./NoActiveThreadState";
|
||||
import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
@@ -256,10 +259,12 @@ type EnvironmentUnavailableState = {
|
||||
|
||||
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
|
||||
|
||||
function eventTargetElement(target: EventTarget | null): Element | null {
|
||||
if (target instanceof Element) return target;
|
||||
if (target instanceof Node) return target.parentElement;
|
||||
return null;
|
||||
function eventPathContainsSelector(event: Event, selector: string): boolean {
|
||||
const path = event.composedPath();
|
||||
if (path.length === 0 && event.target) {
|
||||
path.push(event.target);
|
||||
}
|
||||
return path.some((target) => target instanceof Element && target.closest(selector));
|
||||
}
|
||||
|
||||
function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
|
||||
@@ -267,9 +272,8 @@ function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return false;
|
||||
if (event.key.length !== 1) return false;
|
||||
|
||||
const target = eventTargetElement(event.target);
|
||||
if (target?.closest(TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false;
|
||||
if (target?.closest(TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
|
||||
if (eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false;
|
||||
if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
|
||||
if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
|
||||
|
||||
return true;
|
||||
@@ -1055,7 +1059,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
|
||||
);
|
||||
});
|
||||
|
||||
export default function ChatView(props: ChatViewProps) {
|
||||
function ChatViewContent(props: ChatViewProps) {
|
||||
const {
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -1152,6 +1156,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
>({});
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
|
||||
ApprovalRequestId[]
|
||||
@@ -1324,6 +1331,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const planSidebarOpen = activeRightPanelKind === "plan";
|
||||
const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();
|
||||
const rightPanelOpen = rightPanelState.isOpen;
|
||||
const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet;
|
||||
const rightPanelMaximized =
|
||||
canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;
|
||||
const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1358,11 +1368,58 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const activeProject = useStore(
|
||||
useMemo(() => createProjectSelectorByRef(activeProjectRef), [activeProjectRef]),
|
||||
);
|
||||
const activeProjectKey = activeProject
|
||||
? `${activeProject.environmentId}:${activeProject.cwd}`
|
||||
: null;
|
||||
const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState<
|
||||
ReadonlyMap<string, ReadonlySet<string>>
|
||||
>(() => new Map());
|
||||
const pendingFileSurfaceIds = activeProjectKey
|
||||
? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS)
|
||||
: EMPTY_PENDING_FILE_SURFACE_IDS;
|
||||
const handleFilePendingChange = useCallback(
|
||||
(relativePath: string, pending: boolean) => {
|
||||
if (!activeProjectKey) return;
|
||||
setPendingFileSurfaceIdsByProject((currentByProject) => {
|
||||
const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS;
|
||||
const surfaceId = `file:${relativePath}`;
|
||||
if (current.has(surfaceId) === pending) return currentByProject;
|
||||
|
||||
const next = new Set(current);
|
||||
if (pending) {
|
||||
next.add(surfaceId);
|
||||
} else {
|
||||
next.delete(surfaceId);
|
||||
}
|
||||
|
||||
const nextByProject = new Map(currentByProject);
|
||||
if (next.size === 0) {
|
||||
nextByProject.delete(activeProjectKey);
|
||||
} else {
|
||||
nextByProject.set(activeProjectKey, next);
|
||||
}
|
||||
return nextByProject;
|
||||
});
|
||||
},
|
||||
[activeProjectKey],
|
||||
);
|
||||
const activeEnvironmentBootstrapComplete = useStore((state) =>
|
||||
activeThread
|
||||
? selectEnvironmentState(state, activeThread.environmentId).bootstrapComplete
|
||||
: false,
|
||||
);
|
||||
const configuredPreviewUrls = useMemo(
|
||||
() => getConfiguredPreviewUrls(activeProject?.scripts),
|
||||
[activeProject?.scripts],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return;
|
||||
useRightPanelStore
|
||||
.getState()
|
||||
.reconcileFileSurfaces(activeThreadRef, activeProject !== undefined);
|
||||
}, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (routeKind !== "server") {
|
||||
return;
|
||||
@@ -2209,6 +2266,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}),
|
||||
[terminalUiState.terminalOpen],
|
||||
);
|
||||
const terminalToggleShortcutLabel = shortcutLabelForCommand(keybindings, "terminal.toggle");
|
||||
const rightPanelToggleShortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");
|
||||
const splitTerminalShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions),
|
||||
[keybindings, terminalShortcutLabelOptions],
|
||||
@@ -2257,6 +2316,14 @@ export default function ChatView(props: ChatViewProps) {
|
||||
onDiffPanelOpen,
|
||||
threadId,
|
||||
]);
|
||||
const addFilesSurface = () => {
|
||||
if (!activeThreadRef || !activeProject) return;
|
||||
useRightPanelStore.getState().open(activeThreadRef, "files");
|
||||
};
|
||||
const openFileSurface = (relativePath: string) => {
|
||||
if (!activeThreadRef || !activeProject) return;
|
||||
useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
|
||||
};
|
||||
// Right-panel arbitration:
|
||||
// - The diff panel's openness is mirrored by the `?diff=1` URL search
|
||||
// param so it deep-links cleanly. The store still records preview/plan
|
||||
@@ -2979,12 +3046,14 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, [activePlan?.turnId, activeThreadRef, planSidebarOpen, sidebarProposedPlan?.turnId]);
|
||||
const closePlanSidebar = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
setMaximizedRightPanelThreadKey(null);
|
||||
useRightPanelStore.getState().close(activeThreadRef);
|
||||
planSidebarDismissedForTurnRef.current =
|
||||
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
}, [activePlan?.turnId, activeThreadRef, sidebarProposedPlan?.turnId]);
|
||||
const closePreviewPanel = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
setMaximizedRightPanelThreadKey(null);
|
||||
useRightPanelStore.getState().close(activeThreadRef);
|
||||
}, [activeThreadRef]);
|
||||
const activateRightPanelSurface = useCallback(
|
||||
@@ -3018,8 +3087,17 @@ export default function ChatView(props: ChatViewProps) {
|
||||
);
|
||||
const toggleRightPanel = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
if (rightPanelOpen) {
|
||||
setMaximizedRightPanelThreadKey(null);
|
||||
}
|
||||
useRightPanelStore.getState().toggleVisibility(activeThreadRef);
|
||||
}, [activeThreadRef]);
|
||||
}, [activeThreadRef, rightPanelOpen]);
|
||||
const toggleRightPanelMaximized = () => {
|
||||
if (!canMaximizeRightPanel) return;
|
||||
setMaximizedRightPanelThreadKey((threadKey) =>
|
||||
threadKey === routeThreadKey ? null : routeThreadKey,
|
||||
);
|
||||
};
|
||||
const closeRightPanelSurface = useCallback(
|
||||
(surface: RightPanelSurface) => {
|
||||
if (!activeThreadRef) return;
|
||||
@@ -4481,23 +4559,43 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">
|
||||
<div className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">
|
||||
{isElectron && activeThreadRef ? (
|
||||
<PreviewAutomationOwner threadRef={activeThreadRef} visible={previewPanelOpen} />
|
||||
) : null}
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden">
|
||||
<PanelLayoutControls
|
||||
terminalAvailable={Boolean(activeProject)}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
terminalShortcutLabel={terminalToggleShortcutLabel}
|
||||
rightPanelAvailable={Boolean(activeProject)}
|
||||
rightPanelOpen={rightPanelOpen}
|
||||
rightPanelShortcutLabel={rightPanelToggleShortcutLabel}
|
||||
rightPanelMaximized={rightPanelMaximized}
|
||||
canMaximizeRightPanel={canMaximizeRightPanel}
|
||||
onToggleTerminal={toggleTerminalVisibility}
|
||||
onToggleRightPanel={toggleRightPanel}
|
||||
onToggleRightPanelMaximized={toggleRightPanelMaximized}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 min-w-0 flex-col overflow-hidden",
|
||||
rightPanelMaximized ? "w-0 flex-none" : "flex-1",
|
||||
)}
|
||||
data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}
|
||||
>
|
||||
{/* Top bar */}
|
||||
<header
|
||||
data-chat-header
|
||||
className={cn(
|
||||
"border-b border-border",
|
||||
isElectron
|
||||
? cn(
|
||||
"drag-region flex h-[52px] items-center px-3 sm:px-5 wco:h-[env(titlebar-area-height)]",
|
||||
"workspace-topbar drag-region px-3 sm:px-5",
|
||||
reserveTitleBarControlInset &&
|
||||
!inlineRightPanelOwnsTitleBar &&
|
||||
"wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
"wco:pr-[var(--workspace-native-controls-inset)]",
|
||||
)
|
||||
: "pb-2 pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-2 sm:pb-3 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-3",
|
||||
: "workspace-topbar pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]",
|
||||
)}
|
||||
>
|
||||
<ChatHeader
|
||||
@@ -4513,17 +4611,12 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
terminalAvailable={Boolean(activeProject)}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
rightPanelAvailable={Boolean(activeProject)}
|
||||
rightPanelOpen={rightPanelOpen}
|
||||
gitCwd={gitCwd}
|
||||
onRunProjectScript={runProjectScript}
|
||||
onAddProjectScript={saveProjectScript}
|
||||
onUpdateProjectScript={updateProjectScript}
|
||||
onDeleteProjectScript={deleteProjectScript}
|
||||
onToggleTerminal={toggleTerminalVisibility}
|
||||
onToggleRightPanel={toggleRightPanel}
|
||||
rightPanelOpen={rightPanelOpen}
|
||||
/>
|
||||
</header>
|
||||
|
||||
@@ -4730,8 +4823,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{!shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? (
|
||||
<RightPanelTabs
|
||||
mode="inline"
|
||||
maximized={rightPanelMaximized}
|
||||
surfaces={rightPanelState.surfaces}
|
||||
activeSurfaceId={activeRightPanelSurface?.id ?? null}
|
||||
pendingSurfaceIds={pendingFileSurfaceIds}
|
||||
previewSessions={activePreviewState.sessions}
|
||||
terminalLabelsById={activeTerminalLabelsById}
|
||||
onActivate={activateRightPanelSurface}
|
||||
@@ -4739,8 +4834,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
onAddBrowser={createBrowserSurface}
|
||||
onAddTerminal={addTerminalSurface}
|
||||
onAddDiff={addDiffSurface}
|
||||
onAddFiles={addFilesSurface}
|
||||
browserAvailable={isPreviewSupportedInRuntime()}
|
||||
diffAvailable={isServerThread && isGitRepo}
|
||||
filesAvailable={Boolean(activeProject)}
|
||||
>
|
||||
{activeRightPanelSurface?.kind === "preview" ? (
|
||||
<Suspense fallback={null}>
|
||||
@@ -4771,11 +4868,27 @@ export default function ChatView(props: ChatViewProps) {
|
||||
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
|
||||
/>
|
||||
) : activeRightPanelSurface?.kind === "diff" ? (
|
||||
<DiffWorkerPoolProvider>
|
||||
<Suspense fallback={null}>
|
||||
<DiffPanel mode="embedded" />
|
||||
</Suspense>
|
||||
</DiffWorkerPoolProvider>
|
||||
<Suspense fallback={null}>
|
||||
<DiffPanel mode="embedded" />
|
||||
</Suspense>
|
||||
) : (activeRightPanelSurface?.kind === "files" ||
|
||||
activeRightPanelSurface?.kind === "file") &&
|
||||
activeProject ? (
|
||||
<Suspense fallback={null}>
|
||||
<FilePreviewPanel
|
||||
key={`${activeProject.environmentId}:${activeProject.cwd}`}
|
||||
environmentId={activeProject.environmentId}
|
||||
cwd={activeProject.cwd}
|
||||
projectName={activeProject.name}
|
||||
relativePath={
|
||||
activeRightPanelSurface.kind === "file"
|
||||
? activeRightPanelSurface.relativePath
|
||||
: null
|
||||
}
|
||||
onOpenFile={openFileSurface}
|
||||
onPendingChange={handleFilePendingChange}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
</RightPanelTabs>
|
||||
) : null}
|
||||
@@ -4786,6 +4899,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
mode="sheet"
|
||||
surfaces={rightPanelState.surfaces}
|
||||
activeSurfaceId={activeRightPanelSurface?.id ?? null}
|
||||
pendingSurfaceIds={pendingFileSurfaceIds}
|
||||
previewSessions={activePreviewState.sessions}
|
||||
terminalLabelsById={activeTerminalLabelsById}
|
||||
onActivate={activateRightPanelSurface}
|
||||
@@ -4793,8 +4907,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
onAddBrowser={createBrowserSurface}
|
||||
onAddTerminal={addTerminalSurface}
|
||||
onAddDiff={addDiffSurface}
|
||||
onAddFiles={addFilesSurface}
|
||||
browserAvailable={isPreviewSupportedInRuntime()}
|
||||
diffAvailable={isServerThread && isGitRepo}
|
||||
filesAvailable={Boolean(activeProject)}
|
||||
>
|
||||
{activeRightPanelSurface?.kind === "preview" ? (
|
||||
<Suspense fallback={null}>
|
||||
@@ -4825,11 +4941,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
|
||||
/>
|
||||
) : activeRightPanelSurface?.kind === "diff" ? (
|
||||
<DiffWorkerPoolProvider>
|
||||
<Suspense fallback={null}>
|
||||
<DiffPanel mode="embedded" />
|
||||
</Suspense>
|
||||
</DiffWorkerPoolProvider>
|
||||
<Suspense fallback={null}>
|
||||
<DiffPanel mode="embedded" />
|
||||
</Suspense>
|
||||
) : activeRightPanelSurface?.kind === "plan" ? (
|
||||
<PlanSidebar
|
||||
activePlan={activePlan}
|
||||
@@ -4843,6 +4957,24 @@ export default function ChatView(props: ChatViewProps) {
|
||||
mode="embedded"
|
||||
onClose={closePlanSidebar}
|
||||
/>
|
||||
) : (activeRightPanelSurface?.kind === "files" ||
|
||||
activeRightPanelSurface?.kind === "file") &&
|
||||
activeProject ? (
|
||||
<Suspense fallback={null}>
|
||||
<FilePreviewPanel
|
||||
key={`${activeProject.environmentId}:${activeProject.cwd}`}
|
||||
environmentId={activeProject.environmentId}
|
||||
cwd={activeProject.cwd}
|
||||
projectName={activeProject.name}
|
||||
relativePath={
|
||||
activeRightPanelSurface.kind === "file"
|
||||
? activeRightPanelSurface.relativePath
|
||||
: null
|
||||
}
|
||||
onOpenFile={openFileSurface}
|
||||
onPendingChange={handleFilePendingChange}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
</RightPanelTabs>
|
||||
</RightPanelSheet>
|
||||
@@ -4854,3 +4986,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ChatView(props: ChatViewProps) {
|
||||
return (
|
||||
<DiffWorkerPoolProvider>
|
||||
<ChatViewContent {...props} />
|
||||
</DiffWorkerPoolProvider>
|
||||
);
|
||||
}
|
||||
@@ -64,7 +64,7 @@ import {
|
||||
type TerminalContextDraft,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath } from "~/vscode-icons";
|
||||
import { basenameOfPath } from "~/pierre-icons";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
|
||||
@@ -47,6 +47,7 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
highlighterOptions={{
|
||||
theme: diffThemeName,
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
useTokenTransformer: true,
|
||||
}}
|
||||
>
|
||||
<DiffWorkerThemeSync themeName={diffThemeName} />
|
||||
|
||||
@@ -10,13 +10,11 @@ export function NoActiveThreadState() {
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 sm:px-5",
|
||||
isElectron
|
||||
? "drag-region flex h-[52px] items-center wco:h-[env(titlebar-area-height)]"
|
||||
: "py-2 sm:py-3",
|
||||
isElectron ? "workspace-topbar drag-region" : "workspace-topbar",
|
||||
)}
|
||||
>
|
||||
{isElectron ? (
|
||||
<span className="text-xs text-muted-foreground/50 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]">
|
||||
<span className="text-xs text-muted-foreground/50 wco:pr-[var(--workspace-native-controls-inset)]">
|
||||
No active thread
|
||||
</span>
|
||||
) : (
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
|
||||
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
|
||||
import { ClipboardList, FileDiff, Globe2, Plus, TerminalSquare, X } from "lucide-react";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { isElectron } from "~/env";
|
||||
import type { RightPanelSurface } from "~/rightPanelStore";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { faviconUrlForOrigin } from "~/lib/favicon";
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
|
||||
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
|
||||
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
||||
|
||||
interface RightPanelTabsProps {
|
||||
mode: PreviewPanelMode;
|
||||
maximized?: boolean;
|
||||
surfaces: readonly RightPanelSurface[];
|
||||
activeSurfaceId: string | null;
|
||||
pendingSurfaceIds: ReadonlySet<string>;
|
||||
previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
|
||||
terminalLabelsById: ReadonlyMap<string, string>;
|
||||
onActivate: (surface: RightPanelSurface) => void;
|
||||
@@ -23,8 +28,10 @@ interface RightPanelTabsProps {
|
||||
onAddBrowser: () => void;
|
||||
onAddTerminal: () => void;
|
||||
onAddDiff: () => void;
|
||||
onAddFiles: () => void;
|
||||
browserAvailable: boolean;
|
||||
diffAvailable: boolean;
|
||||
filesAvailable: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
@@ -32,8 +39,10 @@ function RightPanelEmptyState(props: {
|
||||
onAddBrowser: () => void;
|
||||
onAddTerminal: () => void;
|
||||
onAddDiff: () => void;
|
||||
onAddFiles: () => void;
|
||||
browserAvailable: boolean;
|
||||
diffAvailable: boolean;
|
||||
filesAvailable: boolean;
|
||||
}) {
|
||||
const actions = [
|
||||
{
|
||||
@@ -50,6 +59,13 @@ function RightPanelEmptyState(props: {
|
||||
available: true,
|
||||
onClick: props.onAddTerminal,
|
||||
},
|
||||
{
|
||||
label: "Files",
|
||||
description: "Browse and read workspace files.",
|
||||
icon: Files,
|
||||
available: props.filesAvailable,
|
||||
onClick: props.onAddFiles,
|
||||
},
|
||||
{
|
||||
label: "Diff",
|
||||
description: "Review changes in this thread.",
|
||||
@@ -68,7 +84,7 @@ function RightPanelEmptyState(props: {
|
||||
Choose what to show in the right panel.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{actions.map((action) => {
|
||||
const Icon = action.icon;
|
||||
return (
|
||||
@@ -101,6 +117,10 @@ function surfaceTitle(
|
||||
switch (surface.kind) {
|
||||
case "diff":
|
||||
return "Diff";
|
||||
case "files":
|
||||
return "Files";
|
||||
case "file":
|
||||
return surface.relativePath.slice(surface.relativePath.lastIndexOf("/") + 1);
|
||||
case "terminal":
|
||||
return (
|
||||
terminalLabelsById.get(surface.activeTerminalId) ??
|
||||
@@ -140,9 +160,11 @@ function PreviewFavicon({ url }: { url: string | null }) {
|
||||
function SurfaceIcon({
|
||||
surface,
|
||||
sessions,
|
||||
theme,
|
||||
}: {
|
||||
surface: RightPanelSurface;
|
||||
sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
|
||||
theme: "light" | "dark";
|
||||
}) {
|
||||
switch (surface.kind) {
|
||||
case "preview": {
|
||||
@@ -152,6 +174,17 @@ function SurfaceIcon({
|
||||
}
|
||||
case "diff":
|
||||
return <FileDiff className="size-3.5 shrink-0" />;
|
||||
case "files":
|
||||
return <Files className="size-3.5 shrink-0" />;
|
||||
case "file":
|
||||
return (
|
||||
<PierreEntryIcon
|
||||
pathValue={surface.relativePath}
|
||||
kind="file"
|
||||
theme={theme}
|
||||
className="size-3.5"
|
||||
/>
|
||||
);
|
||||
case "terminal":
|
||||
return <TerminalSquare className="size-3.5 shrink-0" />;
|
||||
case "plan":
|
||||
@@ -161,80 +194,124 @@ function SurfaceIcon({
|
||||
|
||||
export function RightPanelTabs(props: RightPanelTabsProps) {
|
||||
const ownsDesktopTitleBar = isElectron && props.mode === "inline";
|
||||
const { resolvedTheme } = useTheme();
|
||||
const tabListRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
|
||||
activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
}, [props.activeSurfaceId]);
|
||||
|
||||
return (
|
||||
<PreviewPanelShell mode={props.mode}>
|
||||
<PreviewPanelShell
|
||||
mode={props.mode}
|
||||
{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex shrink-0 items-center px-2",
|
||||
ownsDesktopTitleBar
|
||||
? "drag-region h-[52px] wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]"
|
||||
: "h-10",
|
||||
"px-2 pr-28",
|
||||
props.mode === "inline" ? "workspace-topbar" : "flex h-10 shrink-0 items-center",
|
||||
ownsDesktopTitleBar &&
|
||||
"drag-region wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
|
||||
)}
|
||||
data-right-panel-tabbar
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">
|
||||
{props.surfaces.map((surface) => {
|
||||
const active = surface.id === props.activeSurfaceId;
|
||||
const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
|
||||
return (
|
||||
<div
|
||||
key={surface.id}
|
||||
className={cn(
|
||||
"group flex h-7 min-w-0 max-w-52 items-center gap-1.5 rounded-md px-2 text-sm",
|
||||
active
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-1.5"
|
||||
onClick={() => props.onActivate(surface)}
|
||||
>
|
||||
<SurfaceIcon surface={surface} sessions={props.previewSessions} />
|
||||
<span className="truncate">{title}</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>{title}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded p-0.5 opacity-0 hover:bg-muted group-hover:opacity-100 focus:opacity-100"
|
||||
aria-label={`Close ${title}`}
|
||||
onClick={() => props.onCloseSurface(surface)}
|
||||
<ScrollArea
|
||||
ref={tabListRef}
|
||||
hideScrollbars
|
||||
scrollFade
|
||||
className="min-w-0 flex-1 rounded-none"
|
||||
data-right-panel-tab-list
|
||||
>
|
||||
<div className="flex h-full w-max min-w-full items-center gap-1">
|
||||
{props.surfaces.map((surface) => {
|
||||
const active = surface.id === props.activeSurfaceId;
|
||||
const pending = props.pendingSurfaceIds.has(surface.id);
|
||||
const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
|
||||
return (
|
||||
<div
|
||||
key={surface.id}
|
||||
data-active-tab={active}
|
||||
className={cn(
|
||||
"group flex h-7 min-w-25 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm",
|
||||
active
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
className="relative ml-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label="Add panel surface"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
|
||||
<MenuItem onClick={props.onAddBrowser} disabled={!props.browserAvailable}>
|
||||
<Globe2 />
|
||||
Browser
|
||||
</MenuItem>
|
||||
<MenuItem onClick={props.onAddTerminal}>
|
||||
<TerminalSquare />
|
||||
Terminal
|
||||
</MenuItem>
|
||||
<MenuItem onClick={props.onAddDiff} disabled={!props.diffAvailable}>
|
||||
<FileDiff />
|
||||
Diff
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-1.5"
|
||||
onClick={() => props.onActivate(surface)}
|
||||
>
|
||||
<SurfaceIcon
|
||||
surface={surface}
|
||||
sessions={props.previewSessions}
|
||||
theme={resolvedTheme}
|
||||
/>
|
||||
<span className="truncate">{title}</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>{title}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"relative flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted focus:opacity-100",
|
||||
pending ? "opacity-100" : "opacity-0 group-hover:opacity-100",
|
||||
)}
|
||||
aria-label={`Close ${title}`}
|
||||
onClick={() => props.onCloseSurface(surface)}
|
||||
>
|
||||
{pending ? (
|
||||
<>
|
||||
<span
|
||||
className="size-2 rounded-full bg-current group-hover:hidden"
|
||||
aria-hidden
|
||||
/>
|
||||
<X className="hidden size-3 group-hover:block" />
|
||||
</>
|
||||
) : (
|
||||
<X className="size-3" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{props.surfaces.length > 0 ? (
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
className="relative inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label="Add panel surface"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
|
||||
<MenuItem onClick={props.onAddBrowser} disabled={!props.browserAvailable}>
|
||||
<Globe2 />
|
||||
Browser
|
||||
</MenuItem>
|
||||
<MenuItem onClick={props.onAddTerminal}>
|
||||
<TerminalSquare />
|
||||
Terminal
|
||||
</MenuItem>
|
||||
<MenuItem onClick={props.onAddFiles} disabled={!props.filesAvailable}>
|
||||
<Files />
|
||||
Files
|
||||
</MenuItem>
|
||||
<MenuItem onClick={props.onAddDiff} disabled={!props.diffAvailable}>
|
||||
<FileDiff />
|
||||
Diff
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
) : null}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
{props.activeSurfaceId === null ? (
|
||||
@@ -242,8 +319,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
|
||||
onAddBrowser={props.onAddBrowser}
|
||||
onAddTerminal={props.onAddTerminal}
|
||||
onAddDiff={props.onAddDiff}
|
||||
onAddFiles={props.onAddFiles}
|
||||
browserAvailable={props.browserAvailable}
|
||||
diffAvailable={props.diffAvailable}
|
||||
filesAvailable={props.filesAvailable}
|
||||
/>
|
||||
) : (
|
||||
props.children
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
import { PierreEntryIcon } from "./PierreEntryIcon";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
@@ -177,7 +177,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
{hasDirectoryNodes || depth > 0 ? (
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
) : null}
|
||||
<VscodeEntryIcon
|
||||
<PierreEntryIcon
|
||||
pathValue={node.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
|
||||
@@ -79,7 +79,7 @@ import {
|
||||
} from "./composerProviderState";
|
||||
import { ContextWindowMeter } from "./ContextWindowMeter";
|
||||
import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { basenameOfPath } from "../../vscode-icons";
|
||||
import { basenameOfPath } from "../../pierre-icons";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { Separator } from "../ui/separator";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
@@ -9,14 +9,12 @@ import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { type DraftId } from "~/composerDraftStore";
|
||||
import { PanelBottomIcon, PanelRightIcon } from "lucide-react";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
|
||||
import { Toggle } from "../ui/toggle";
|
||||
import { SidebarTrigger } from "../ui/sidebar";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../environments/primary";
|
||||
import { shortcutLabelForCommand } from "../../keybindings";
|
||||
import { usePrimaryEnvironmentId } from "../../environments/primary/context";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
@@ -29,17 +27,12 @@ interface ChatHeaderProps {
|
||||
preferredScriptId: string | null;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
terminalAvailable: boolean;
|
||||
terminalOpen: boolean;
|
||||
rightPanelAvailable: boolean;
|
||||
rightPanelOpen: boolean;
|
||||
gitCwd: string | null;
|
||||
onRunProjectScript: (script: ProjectScript) => void;
|
||||
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
|
||||
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
|
||||
onDeleteProjectScript: (scriptId: string) => Promise<void>;
|
||||
onToggleTerminal: () => void;
|
||||
onToggleRightPanel: () => void;
|
||||
rightPanelOpen: boolean;
|
||||
}
|
||||
|
||||
export function shouldShowOpenInPicker(input: {
|
||||
@@ -65,17 +58,12 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
preferredScriptId,
|
||||
keybindings,
|
||||
availableEditors,
|
||||
terminalAvailable,
|
||||
terminalOpen,
|
||||
rightPanelAvailable,
|
||||
rightPanelOpen,
|
||||
gitCwd,
|
||||
onRunProjectScript,
|
||||
onAddProjectScript,
|
||||
onUpdateProjectScript,
|
||||
onDeleteProjectScript,
|
||||
onToggleTerminal,
|
||||
onToggleRightPanel,
|
||||
rightPanelOpen,
|
||||
}: ChatHeaderProps) {
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const showOpenInPicker = shouldShowOpenInPicker({
|
||||
@@ -83,9 +71,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
activeThreadEnvironmentId,
|
||||
primaryEnvironmentId,
|
||||
});
|
||||
const terminalShortcutLabel = shortcutLabelForCommand(keybindings, "terminal.toggle");
|
||||
const rightPanelShortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");
|
||||
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
|
||||
@@ -104,7 +89,13 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3">
|
||||
<div
|
||||
data-chat-header-actions
|
||||
className={cn(
|
||||
"flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3",
|
||||
rightPanelOpen ? "pr-0" : "pr-16",
|
||||
)}
|
||||
>
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
@@ -130,50 +121,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{...(draftId ? { draftId } : {})}
|
||||
/>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={!terminalAvailable}
|
||||
>
|
||||
<PanelBottomIcon className="size-3.5" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{terminalAvailable
|
||||
? `Toggle terminal drawer${terminalShortcutLabel ? ` (${terminalShortcutLabel})` : ""}`
|
||||
: "Terminal drawer is unavailable"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={rightPanelOpen}
|
||||
onPressedChange={onToggleRightPanel}
|
||||
aria-label="Toggle right panel"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={!rightPanelAvailable}
|
||||
>
|
||||
<PanelRightIcon className="size-3.5" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{rightPanelAvailable
|
||||
? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}`
|
||||
: "Right panel is unavailable"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "../ui/command";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
import { PierreEntryIcon } from "./PierreEntryIcon";
|
||||
|
||||
export type ComposerCommandItem =
|
||||
| {
|
||||
@@ -228,7 +228,7 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
}}
|
||||
>
|
||||
{props.item.type === "path" ? (
|
||||
<VscodeEntryIcon
|
||||
<PierreEntryIcon
|
||||
pathValue={props.item.path}
|
||||
kind={props.item.pathKind}
|
||||
theme={props.resolvedTheme}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { inferEntryKindFromPath } from "../../vscode-icons";
|
||||
import { inferEntryKindFromPath } from "../../pierre-icons";
|
||||
import {
|
||||
CHAT_INLINE_CHIP_CLASS_NAME,
|
||||
CHAT_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "../composerInlineChip";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
import { PierreEntryIcon } from "./PierreEntryIcon";
|
||||
|
||||
export const FILE_TAG_CHIP_CLASS_NAME = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
export const CHAT_FILE_TAG_CHIP_CLASS_NAME = CHAT_INLINE_CHIP_CLASS_NAME;
|
||||
@@ -19,7 +19,7 @@ export function FileTagChipContent(props: {
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<VscodeEntryIcon
|
||||
<PierreEntryIcon
|
||||
pathValue={props.path}
|
||||
kind={inferEntryKindFromPath(props.path)}
|
||||
theme={props.theme}
|
||||
|
||||
@@ -7,8 +7,6 @@ import { page } from "vite-plus/test/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { getVscodeIconUrlForEntry } from "../../vscode-icons";
|
||||
|
||||
const scrollToEndSpy = vi.fn();
|
||||
const getStateSpy = vi.fn(() => ({ isAtEnd: true }));
|
||||
|
||||
@@ -392,14 +390,12 @@ describe("MessagesTimeline", () => {
|
||||
const assistantFileLink = document.querySelector(
|
||||
'[data-message-role="assistant"] .chat-markdown-file-link',
|
||||
);
|
||||
const icon = assistantFileLink?.querySelector("img");
|
||||
const icon = assistantFileLink?.querySelector("svg[data-pierre-icon]");
|
||||
|
||||
expect(assistantFileLink?.textContent).toContain("package.json");
|
||||
expect(assistantFileLink?.textContent).toContain("L25");
|
||||
expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json:25");
|
||||
expect(icon?.getAttribute("src")).toBe(
|
||||
getVscodeIconUrlForEntry("/repo/project/path/to/package.json", "file", "dark"),
|
||||
);
|
||||
expect(icon?.getAttribute("data-pierre-icon")).toBe("t3-file-icon-package-json");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react";
|
||||
import { memo } from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { Toggle } from "../ui/toggle";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
interface PanelLayoutControlsProps {
|
||||
terminalAvailable: boolean;
|
||||
terminalOpen: boolean;
|
||||
terminalShortcutLabel: string | null;
|
||||
rightPanelAvailable: boolean;
|
||||
rightPanelOpen: boolean;
|
||||
rightPanelShortcutLabel: string | null;
|
||||
rightPanelMaximized: boolean;
|
||||
canMaximizeRightPanel: boolean;
|
||||
onToggleTerminal: () => void;
|
||||
onToggleRightPanel: () => void;
|
||||
onToggleRightPanelMaximized: () => void;
|
||||
}
|
||||
|
||||
export const PanelLayoutControls = memo(function PanelLayoutControls({
|
||||
terminalAvailable,
|
||||
terminalOpen,
|
||||
terminalShortcutLabel,
|
||||
rightPanelAvailable,
|
||||
rightPanelOpen,
|
||||
rightPanelShortcutLabel,
|
||||
rightPanelMaximized,
|
||||
canMaximizeRightPanel,
|
||||
onToggleTerminal,
|
||||
onToggleRightPanel,
|
||||
onToggleRightPanelMaximized,
|
||||
}: PanelLayoutControlsProps) {
|
||||
return (
|
||||
<div className={cn("workspace-titlebar-controls z-50 gap-1")} data-panel-layout-controls>
|
||||
{rightPanelOpen ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={rightPanelMaximized}
|
||||
onPressedChange={onToggleRightPanelMaximized}
|
||||
aria-label={rightPanelMaximized ? "Restore panel size" : "Maximize panel"}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!canMaximizeRightPanel}
|
||||
>
|
||||
{rightPanelMaximized ? (
|
||||
<Minimize2Icon className="size-3.5" />
|
||||
) : (
|
||||
<Maximize2Icon className="size-3.5" />
|
||||
)}
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{canMaximizeRightPanel
|
||||
? rightPanelMaximized
|
||||
? "Restore panel size"
|
||||
: "Maximize panel"
|
||||
: "Panel maximization is unavailable at this width"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!terminalAvailable}
|
||||
>
|
||||
<PanelBottomIcon className="size-3.5" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{terminalAvailable
|
||||
? `Toggle terminal drawer${terminalShortcutLabel ? ` (${terminalShortcutLabel})` : ""}`
|
||||
: "Terminal drawer is unavailable"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={rightPanelOpen}
|
||||
onPressedChange={onToggleRightPanel}
|
||||
aria-label="Toggle right panel"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!rightPanelAvailable}
|
||||
>
|
||||
<PanelRightIcon className="size-3.5" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{rightPanelAvailable
|
||||
? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}`
|
||||
: "Right panel is unavailable"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { FileIcon, FolderIcon } from "lucide-react";
|
||||
import { memo, useInsertionEffect, useMemo } from "react";
|
||||
|
||||
import { ensurePierreIconSprite, resolvePierreIconForEntry } from "../../pierre-icons";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const ICON_COLORS: Record<string, readonly [light: string, dark: string]> = {
|
||||
astro: ["#a631be", "#d568ea"],
|
||||
babel: ["#d5a910", "#ffd452"],
|
||||
bash: ["#199f43", "#5ecc71"],
|
||||
biome: ["#1a85d4", "#69b1ff"],
|
||||
bootstrap: ["#693acf", "#9d6afb"],
|
||||
browserslist: ["#d5a910", "#ffd452"],
|
||||
bun: ["#594c5b", "#79697b"],
|
||||
c: ["#1a85d4", "#69b1ff"],
|
||||
claude: ["#d47628", "#ffa359"],
|
||||
cpp: ["#1a85d4", "#69b1ff"],
|
||||
css: ["#693acf", "#9d6afb"],
|
||||
database: ["#a631be", "#d568ea"],
|
||||
default: ["#84848a", "#adadb1"],
|
||||
docker: ["#1a85d4", "#69b1ff"],
|
||||
eslint: ["#693acf", "#9d6afb"],
|
||||
git: ["#ff8c5b", "#d5512f"],
|
||||
go: ["#1ca1c7", "#68cdf2"],
|
||||
graphql: ["#d32a61", "#ff678d"],
|
||||
html: ["#d47628", "#ffa359"],
|
||||
image: ["#d32a61", "#ff678d"],
|
||||
javascript: ["#d5a910", "#ffd452"],
|
||||
json: ["#d47628", "#ffa359"],
|
||||
markdown: ["#199f43", "#5ecc71"],
|
||||
mcp: ["#17a5af", "#64d1db"],
|
||||
nextjs: ["#84848a", "#adadb1"],
|
||||
npm: ["#d52c36", "#ff6762"],
|
||||
oxc: ["#1ca1c7", "#68cdf2"],
|
||||
postcss: ["#d52c36", "#ff6762"],
|
||||
prettier: ["#17a5af", "#64d1db"],
|
||||
python: ["#1a85d4", "#69b1ff"],
|
||||
react: ["#1ca1c7", "#68cdf2"],
|
||||
ruby: ["#d52c36", "#ff6762"],
|
||||
rust: ["#d47628", "#ffa359"],
|
||||
sass: ["#d32a61", "#ff678d"],
|
||||
stylelint: ["#84848a", "#adadb1"],
|
||||
svelte: ["#d52c36", "#ff6762"],
|
||||
svg: ["#d47628", "#ffa359"],
|
||||
svgo: ["#199f43", "#5ecc71"],
|
||||
swift: ["#d47628", "#ffa359"],
|
||||
table: ["#17a5af", "#64d1db"],
|
||||
tailwind: ["#1ca1c7", "#68cdf2"],
|
||||
terraform: ["#693acf", "#9d6afb"],
|
||||
text: ["#84848a", "#adadb1"],
|
||||
typescript: ["#1a85d4", "#69b1ff"],
|
||||
vite: ["#a631be", "#d568ea"],
|
||||
vscode: ["#1a85d4", "#69b1ff"],
|
||||
vue: ["#199f43", "#5ecc71"],
|
||||
wasm: ["#693acf", "#9d6afb"],
|
||||
webpack: ["#1a85d4", "#69b1ff"],
|
||||
yml: ["#d52c36", "#ff6762"],
|
||||
zig: ["#d47628", "#ffa359"],
|
||||
zip: ["#d47628", "#ffa359"],
|
||||
};
|
||||
|
||||
export const PierreEntryIcon = memo(function PierreEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
theme: "light" | "dark";
|
||||
className?: string;
|
||||
}) {
|
||||
useInsertionEffect(ensurePierreIconSprite, []);
|
||||
const icon = useMemo(
|
||||
() => resolvePierreIconForEntry(props.pathValue, props.kind),
|
||||
[props.kind, props.pathValue],
|
||||
);
|
||||
|
||||
if (!icon) {
|
||||
return props.kind === "directory" ? (
|
||||
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
) : (
|
||||
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
);
|
||||
}
|
||||
|
||||
const colors = ICON_COLORS[icon.token ?? "default"] ?? ICON_COLORS.default;
|
||||
return (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-pierre-icon={icon.name}
|
||||
data-icon-token={icon.token}
|
||||
className={cn("size-4 shrink-0", props.className)}
|
||||
style={{ color: colors?.[props.theme === "light" ? 0 : 1] }}
|
||||
viewBox="0 0 16 16"
|
||||
>
|
||||
<use href={`#${icon.name}`} />
|
||||
</svg>
|
||||
);
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import { memo, useMemo, useState } from "react";
|
||||
import { getVscodeIconUrlForEntry } from "../../vscode-icons";
|
||||
import { FileIcon, FolderIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
theme: "light" | "dark";
|
||||
className?: string;
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
const iconUrl = useMemo(
|
||||
() => getVscodeIconUrlForEntry(props.pathValue, props.kind, props.theme),
|
||||
[props.kind, props.pathValue, props.theme],
|
||||
);
|
||||
const failed = failedIconUrl === iconUrl;
|
||||
|
||||
if (failed) {
|
||||
return props.kind === "directory" ? (
|
||||
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
) : (
|
||||
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className={cn("size-4 shrink-0", props.className)}
|
||||
loading="lazy"
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
|
||||
import { FileTree, useFileTree } from "@pierre/trees/react";
|
||||
import { RefreshCw, Search } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { T3_PIERRE_ICONS } from "~/pierre-icons";
|
||||
|
||||
import { useProjectEntriesQuery } from "./projectFilesQueryState";
|
||||
|
||||
interface FileBrowserPanelProps {
|
||||
environmentId: EnvironmentId;
|
||||
cwd: string;
|
||||
projectName: string;
|
||||
onOpenFile: (relativePath: string) => void;
|
||||
}
|
||||
|
||||
const TREE_UNSAFE_CSS = `
|
||||
:host {
|
||||
--trees-bg-override: transparent;
|
||||
--trees-selected-bg-override: color-mix(in srgb, currentColor 12%, transparent);
|
||||
--trees-hover-bg-override: color-mix(in srgb, currentColor 7%, transparent);
|
||||
--trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);
|
||||
--trees-font-family-override: var(--font-sans);
|
||||
--trees-font-size-override: 12px;
|
||||
}
|
||||
button[data-type='item'] { border-radius: 5px; }
|
||||
`;
|
||||
|
||||
function treePath(entry: ProjectEntry): string {
|
||||
return entry.kind === "directory" ? `${entry.path}/` : entry.path;
|
||||
}
|
||||
|
||||
export default function FileBrowserPanel({
|
||||
environmentId,
|
||||
cwd,
|
||||
projectName,
|
||||
onOpenFile,
|
||||
}: FileBrowserPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const entriesQuery = useProjectEntriesQuery(environmentId, cwd);
|
||||
const entries = entriesQuery.data?.entries ?? [];
|
||||
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 previousTreePathsRef = useRef<readonly string[]>([]);
|
||||
|
||||
const { model } = useFileTree({
|
||||
density: "compact",
|
||||
fileTreeSearchMode: "hide-non-matches",
|
||||
flattenEmptyDirectories: true,
|
||||
initialExpansion: 1,
|
||||
icons: T3_PIERRE_ICONS,
|
||||
onSelectionChange: (selectedPaths) => {
|
||||
const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");
|
||||
if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {
|
||||
onOpenFile(selectedPath);
|
||||
}
|
||||
},
|
||||
paths: [],
|
||||
search: true,
|
||||
unsafeCSS: TREE_UNSAFE_CSS,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (previousTreePathsRef.current === treePaths) return;
|
||||
entryKindsRef.current = entryKinds;
|
||||
previousTreePathsRef.current = treePaths;
|
||||
model.resetPaths(treePaths);
|
||||
}, [entryKinds, model, treePaths]);
|
||||
|
||||
const fileCount = useMemo(
|
||||
() => entries.reduce((count, entry) => count + (entry.kind === "file" ? 1 : 0), 0),
|
||||
[entries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex min-h-0 flex-1 flex-col bg-background"
|
||||
data-file-browser-panel={`${environmentId}:${cwd}`}
|
||||
>
|
||||
<div className="flex h-9 shrink-0 items-center gap-2 border-b border-border/60 px-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-xs font-medium text-foreground">{projectName}</div>
|
||||
<div className="truncate text-[10px] leading-none text-muted-foreground">
|
||||
{entriesQuery.isPending && entriesQuery.data === null
|
||||
? "Indexing…"
|
||||
: `${fileCount.toLocaleString()} files`}
|
||||
{entriesQuery.data?.truncated ? " · partial" : ""}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label="Search workspace files"
|
||||
onClick={() => model.openSearch()}
|
||||
>
|
||||
<Search className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label="Refresh workspace files"
|
||||
onClick={entriesQuery.refresh}
|
||||
>
|
||||
<RefreshCw className={cn("size-3.5", entriesQuery.isPending && "animate-spin")} />
|
||||
</button>
|
||||
</div>
|
||||
{entriesQuery.error && entriesQuery.data === null ? (
|
||||
<div className="p-4 text-xs leading-relaxed text-destructive">{entriesQuery.error}</div>
|
||||
) : (
|
||||
<FileTree
|
||||
model={model}
|
||||
aria-label={`${projectName} files`}
|
||||
className="min-h-0 flex-1 overflow-hidden"
|
||||
style={{
|
||||
colorScheme: resolvedTheme,
|
||||
["--trees-fg-override" as string]: "var(--foreground)",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { Editor } from "@pierre/diffs/editor";
|
||||
import { EditorProvider, File, Virtualizer } from "@pierre/diffs/react";
|
||||
import { ChevronRight, FolderTree, LoaderCircle } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { ensureEnvironmentApi } from "~/environmentApi";
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { resolveDiffThemeName } from "~/lib/diffRendering";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { Toggle } from "~/components/ui/toggle";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
|
||||
import FileBrowserPanel from "./FileBrowserPanel";
|
||||
import { projectFileCacheKey } from "./fileContentRevision";
|
||||
import { fileBreadcrumbs } from "./filePath";
|
||||
import { FileSaveCoordinator } from "./fileSaveCoordinator";
|
||||
import {
|
||||
confirmProjectFileQueryData,
|
||||
setProjectFileQueryData,
|
||||
useProjectFileQuery,
|
||||
} from "./projectFilesQueryState";
|
||||
|
||||
interface FilePreviewPanelProps {
|
||||
environmentId: EnvironmentId;
|
||||
cwd: string;
|
||||
projectName: string;
|
||||
relativePath: string | null;
|
||||
onOpenFile: (relativePath: string) => void;
|
||||
onPendingChange: (relativePath: string, pending: boolean) => void;
|
||||
}
|
||||
|
||||
const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
|
||||
const FILE_SAVE_DEBOUNCE_MS = 500;
|
||||
|
||||
interface EditableFileSurfaceProps {
|
||||
environmentId: EnvironmentId;
|
||||
cwd: string;
|
||||
relativePath: string;
|
||||
contents: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onPendingChange: (relativePath: string, pending: boolean) => void;
|
||||
}
|
||||
|
||||
function EditableFileSurface({
|
||||
environmentId,
|
||||
cwd,
|
||||
relativePath,
|
||||
contents,
|
||||
resolvedTheme,
|
||||
onPendingChange,
|
||||
}: EditableFileSurfaceProps) {
|
||||
const saveCoordinator = useMemo(
|
||||
() =>
|
||||
new FileSaveCoordinator({
|
||||
debounceMs: FILE_SAVE_DEBOUNCE_MS,
|
||||
onPendingChange: (pending) => onPendingChange(relativePath, pending),
|
||||
persist: async (nextContents) => {
|
||||
await ensureEnvironmentApi(environmentId).projects.writeFile({
|
||||
cwd,
|
||||
relativePath,
|
||||
contents: nextContents,
|
||||
});
|
||||
},
|
||||
onConfirmed: (confirmedContents) => {
|
||||
confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents);
|
||||
},
|
||||
}),
|
||||
[cwd, environmentId, onPendingChange, relativePath],
|
||||
);
|
||||
const editor = useMemo(
|
||||
() =>
|
||||
new Editor({
|
||||
onChange: (file) => {
|
||||
setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
|
||||
saveCoordinator.change(file.contents);
|
||||
},
|
||||
}),
|
||||
[cwd, environmentId, relativePath, saveCoordinator],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
editor.cleanUp();
|
||||
saveCoordinator.dispose();
|
||||
},
|
||||
[editor, saveCoordinator],
|
||||
);
|
||||
|
||||
return (
|
||||
<EditorProvider editor={editor}>
|
||||
<Virtualizer
|
||||
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
}}
|
||||
>
|
||||
<File
|
||||
file={{
|
||||
name: relativePath,
|
||||
contents,
|
||||
cacheKey: projectFileCacheKey(cwd, relativePath, contents),
|
||||
}}
|
||||
options={{
|
||||
disableFileHeader: true,
|
||||
overflow: "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme,
|
||||
}}
|
||||
className="min-h-full"
|
||||
contentEditable
|
||||
/>
|
||||
</Virtualizer>
|
||||
</EditorProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function initialExplorerOpen(): boolean {
|
||||
try {
|
||||
return window.localStorage.getItem(FILE_EXPLORER_STORAGE_KEY) !== "false";
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export default function FilePreviewPanel({
|
||||
environmentId,
|
||||
cwd,
|
||||
projectName,
|
||||
relativePath,
|
||||
onOpenFile,
|
||||
onPendingChange,
|
||||
}: FilePreviewPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const file = useProjectFileQuery(environmentId, cwd, relativePath);
|
||||
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
|
||||
const breadcrumbRef = useRef<HTMLDivElement>(null);
|
||||
const breadcrumbs = useMemo(
|
||||
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
|
||||
[projectName, relativePath],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
|
||||
"[data-current-file-crumb='true']",
|
||||
);
|
||||
currentCrumb?.scrollIntoView({ block: "nearest", inline: "end" });
|
||||
}, [relativePath]);
|
||||
|
||||
const toggleExplorer = () => {
|
||||
setExplorerOpen((current) => {
|
||||
const next = !current;
|
||||
try {
|
||||
window.localStorage.setItem(FILE_EXPLORER_STORAGE_KEY, String(next));
|
||||
} catch {}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
|
||||
{relativePath ? (
|
||||
<div className="flex h-11 shrink-0 items-center gap-2 border-y border-border/60 px-3">
|
||||
<ScrollArea
|
||||
ref={breadcrumbRef}
|
||||
hideScrollbars
|
||||
scrollFade
|
||||
className="min-w-0 flex-1 rounded-none"
|
||||
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}
|
||||
<span
|
||||
className={cn(
|
||||
"max-w-40 truncate",
|
||||
crumb.kind === "file"
|
||||
? "font-medium text-foreground"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
title={crumb.path || projectName}
|
||||
>
|
||||
{crumb.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={explorerOpen}
|
||||
onPressedChange={toggleExplorer}
|
||||
aria-label={explorerOpen ? "Hide file explorer" : "Show file explorer"}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
>
|
||||
<FolderTree className="size-3.5" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>
|
||||
{explorerOpen ? "Hide file explorer" : "Show file explorer"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
{relativePath && file.data?.truncated ? (
|
||||
<div className="shrink-0 border-b border-amber-500/20 bg-amber-500/8 px-3 py-1.5 text-[11px] text-amber-700 dark:text-amber-300">
|
||||
Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
className={cn(
|
||||
"min-w-0 flex-1 flex-col overflow-hidden",
|
||||
relativePath ? "flex" : "hidden",
|
||||
)}
|
||||
>
|
||||
{relativePath && file.error && file.data === null ? (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-xs leading-relaxed text-destructive">
|
||||
{file.error}
|
||||
</div>
|
||||
) : relativePath && file.data === null ? (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">
|
||||
<LoaderCircle className="size-5 animate-spin" />
|
||||
</div>
|
||||
) : relativePath && file.data ? (
|
||||
file.data.truncated ? (
|
||||
<Virtualizer
|
||||
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
|
||||
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
}}
|
||||
>
|
||||
<File
|
||||
file={{
|
||||
name: relativePath,
|
||||
contents: file.data.contents,
|
||||
cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
|
||||
}}
|
||||
options={{
|
||||
disableFileHeader: true,
|
||||
overflow: "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme,
|
||||
}}
|
||||
className="min-h-full"
|
||||
/>
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<EditableFileSurface
|
||||
key={`${relativePath}:${resolvedTheme}`}
|
||||
environmentId={environmentId}
|
||||
cwd={cwd}
|
||||
relativePath={relativePath}
|
||||
contents={file.data.contents}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onPendingChange={onPendingChange}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
{explorerOpen || relativePath === null ? (
|
||||
<aside
|
||||
className={cn(
|
||||
"flex min-h-0 shrink-0 bg-background",
|
||||
relativePath
|
||||
? "w-[min(22rem,46%)] min-w-64 border-l border-border/60"
|
||||
: "min-w-0 flex-1",
|
||||
)}
|
||||
>
|
||||
<FileBrowserPanel
|
||||
key={`${environmentId}:${cwd}`}
|
||||
environmentId={environmentId}
|
||||
cwd={cwd}
|
||||
projectName={projectName}
|
||||
onOpenFile={onOpenFile}
|
||||
/>
|
||||
</aside>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { fileContentRevision, projectFileCacheKey } from "./fileContentRevision";
|
||||
|
||||
describe("fileContentRevision", () => {
|
||||
it("changes for same-length edits", () => {
|
||||
expect(fileContentRevision("nodeVersion")).not.toBe(fileContentRevision("nodeVeasdrs"));
|
||||
});
|
||||
|
||||
it("keeps identical contents stable", () => {
|
||||
expect(projectFileCacheKey("/repo", "file.json", "contents")).toBe(
|
||||
projectFileCacheKey("/repo", "file.json", "contents"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
export function fileContentRevision(contents: string): string {
|
||||
let hash = 2_166_136_261;
|
||||
for (let index = 0; index < contents.length; index += 1) {
|
||||
hash ^= contents.charCodeAt(index);
|
||||
hash = Math.imul(hash, 16_777_619);
|
||||
}
|
||||
return `${contents.length}:${(hash >>> 0).toString(36)}`;
|
||||
}
|
||||
|
||||
export function projectFileCacheKey(cwd: string, relativePath: string, contents: string): string {
|
||||
return `${cwd}:${relativePath}:${fileContentRevision(contents)}`;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { fileBreadcrumbs } from "./filePath";
|
||||
|
||||
describe("fileBreadcrumbs", () => {
|
||||
it("builds project, directory, and file crumbs", () => {
|
||||
expect(fileBreadcrumbs("t3code", "apps/web/src/main.tsx")).toEqual([
|
||||
{ label: "t3code", path: "", kind: "project" },
|
||||
{ label: "apps", path: "apps", kind: "directory" },
|
||||
{ label: "web", path: "apps/web", kind: "directory" },
|
||||
{ label: "src", path: "apps/web/src", kind: "directory" },
|
||||
{ label: "main.tsx", path: "apps/web/src/main.tsx", kind: "file" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes repeated separators", () => {
|
||||
expect(fileBreadcrumbs("workspace", "/src//index.ts").map((crumb) => crumb.label)).toEqual([
|
||||
"workspace",
|
||||
"src",
|
||||
"index.ts",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
export interface FileBreadcrumb {
|
||||
label: string;
|
||||
path: string;
|
||||
kind: "project" | "directory" | "file";
|
||||
}
|
||||
|
||||
export function fileBreadcrumbs(projectName: string, relativePath: string): FileBreadcrumb[] {
|
||||
const parts = relativePath.split("/").filter(Boolean);
|
||||
return [
|
||||
{ label: projectName, path: "", kind: "project" },
|
||||
...parts.map((part, index) => ({
|
||||
label: part,
|
||||
path: parts.slice(0, index + 1).join("/"),
|
||||
kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),
|
||||
})),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { FileSaveCoordinator } from "./fileSaveCoordinator";
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe("FileSaveCoordinator", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("debounces edits and persists only the latest contents", async () => {
|
||||
vi.useFakeTimers();
|
||||
const persist = vi.fn<(contents: string) => Promise<void>>().mockResolvedValue(undefined);
|
||||
const onPendingChange = vi.fn();
|
||||
const onConfirmed = vi.fn();
|
||||
const coordinator = new FileSaveCoordinator({
|
||||
debounceMs: 500,
|
||||
persist,
|
||||
onPendingChange,
|
||||
onConfirmed,
|
||||
});
|
||||
|
||||
coordinator.change("first");
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
coordinator.change("latest");
|
||||
await vi.advanceTimersByTimeAsync(499);
|
||||
expect(persist).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(persist).toHaveBeenCalledOnce();
|
||||
expect(persist).toHaveBeenCalledWith("latest");
|
||||
expect(onConfirmed).toHaveBeenCalledWith("latest");
|
||||
expect(onPendingChange.mock.calls).toEqual([[true], [true], [false]]);
|
||||
});
|
||||
|
||||
it("keeps pending state until an edit made during a write is also saved", async () => {
|
||||
vi.useFakeTimers();
|
||||
const firstWrite = deferred();
|
||||
const persist = vi
|
||||
.fn<(contents: string) => Promise<void>>()
|
||||
.mockReturnValueOnce(firstWrite.promise)
|
||||
.mockResolvedValueOnce(undefined);
|
||||
const onPendingChange = vi.fn();
|
||||
const coordinator = new FileSaveCoordinator({
|
||||
debounceMs: 500,
|
||||
persist,
|
||||
onPendingChange,
|
||||
onConfirmed: vi.fn(),
|
||||
});
|
||||
|
||||
coordinator.change("first");
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
coordinator.change("latest");
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(persist).toHaveBeenCalledTimes(1);
|
||||
|
||||
firstWrite.resolve();
|
||||
await vi.runAllTimersAsync();
|
||||
expect(persist).toHaveBeenCalledTimes(2);
|
||||
expect(persist).toHaveBeenLastCalledWith("latest");
|
||||
expect(onPendingChange.mock.calls.at(-1)).toEqual([false]);
|
||||
});
|
||||
|
||||
it("leaves the file pending when the latest write fails", async () => {
|
||||
vi.useFakeTimers();
|
||||
const onPendingChange = vi.fn();
|
||||
const coordinator = new FileSaveCoordinator({
|
||||
debounceMs: 500,
|
||||
persist: vi.fn().mockRejectedValue(new Error("write failed")),
|
||||
onPendingChange,
|
||||
onConfirmed: vi.fn(),
|
||||
});
|
||||
|
||||
coordinator.change("latest");
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
await Promise.resolve();
|
||||
expect(onPendingChange).toHaveBeenCalledWith(true);
|
||||
expect(onPendingChange).not.toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
export interface FileSaveCoordinatorOptions {
|
||||
readonly debounceMs: number;
|
||||
readonly persist: (contents: string) => Promise<void>;
|
||||
readonly onPendingChange: (pending: boolean) => void;
|
||||
readonly onConfirmed: (contents: string) => void;
|
||||
}
|
||||
|
||||
export class FileSaveCoordinator {
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private latestContents = "";
|
||||
private latestRevision = 0;
|
||||
private lastChangeAt = 0;
|
||||
private saving = false;
|
||||
private disposed = false;
|
||||
|
||||
constructor(private readonly options: FileSaveCoordinatorOptions) {}
|
||||
|
||||
change(contents: string): void {
|
||||
this.latestContents = contents;
|
||||
this.latestRevision += 1;
|
||||
this.lastChangeAt = Date.now();
|
||||
this.options.onPendingChange(true);
|
||||
this.schedule(this.options.debounceMs);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.clearTimer();
|
||||
if (this.latestRevision > 0) void this.persistLatest();
|
||||
}
|
||||
|
||||
private schedule(delay: number): void {
|
||||
this.clearTimer();
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.persistLatest();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private clearTimer(): void {
|
||||
if (this.timer === null) return;
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
private async persistLatest(): Promise<void> {
|
||||
if (this.saving || this.latestRevision === 0) return;
|
||||
|
||||
this.saving = true;
|
||||
const contents = this.latestContents;
|
||||
const revision = this.latestRevision;
|
||||
let succeeded = false;
|
||||
try {
|
||||
await this.options.persist(contents);
|
||||
succeeded = true;
|
||||
this.options.onConfirmed(contents);
|
||||
} catch {}
|
||||
|
||||
this.saving = false;
|
||||
if (revision === this.latestRevision) {
|
||||
if (succeeded) this.options.onPendingChange(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const remainingDebounce = Math.max(
|
||||
0,
|
||||
this.options.debounceMs - (Date.now() - this.lastChangeAt),
|
||||
);
|
||||
if (this.disposed) {
|
||||
void this.persistLatest();
|
||||
} else {
|
||||
this.schedule(remainingDebounce);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import type {
|
||||
EnvironmentApi,
|
||||
ProjectListEntriesResult,
|
||||
ProjectReadFileResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
__resetEnvironmentApiOverridesForTests,
|
||||
__setEnvironmentApiOverrideForTests,
|
||||
} from "~/environmentApi";
|
||||
import { appAtomRegistry } from "~/rpc/atomRegistry";
|
||||
|
||||
import {
|
||||
__resetProjectFileQueryDataForTests,
|
||||
confirmProjectFileQueryData,
|
||||
getProjectEntriesQueryAtom,
|
||||
getProjectFileQueryAtom,
|
||||
resolveProjectFileQueryData,
|
||||
setProjectFileQueryData,
|
||||
} from "./projectFilesQueryState";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-project-files-query-test");
|
||||
|
||||
function deferred<A>() {
|
||||
let resolve!: (value: A) => void;
|
||||
const promise = new Promise<A>((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe("project files queries", () => {
|
||||
afterEach(() => {
|
||||
__resetProjectFileQueryDataForTests();
|
||||
__resetEnvironmentApiOverridesForTests();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("retains cached entries while explicitly revalidating", async () => {
|
||||
vi.stubGlobal("window", {});
|
||||
const first = {
|
||||
entries: [{ path: "README.md", kind: "file" }],
|
||||
truncated: false,
|
||||
} satisfies ProjectListEntriesResult;
|
||||
const second = {
|
||||
entries: [
|
||||
{ path: "README.md", kind: "file" },
|
||||
{ path: "src", kind: "directory" },
|
||||
],
|
||||
truncated: false,
|
||||
} satisfies ProjectListEntriesResult;
|
||||
const revalidation = deferred<ProjectListEntriesResult>();
|
||||
const listEntries = vi
|
||||
.fn<EnvironmentApi["projects"]["listEntries"]>()
|
||||
.mockResolvedValueOnce(first)
|
||||
.mockReturnValueOnce(revalidation.promise);
|
||||
__setEnvironmentApiOverrideForTests(environmentId, {
|
||||
projects: { listEntries },
|
||||
} as unknown as EnvironmentApi);
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = getProjectEntriesQueryAtom(environmentId, "/repo");
|
||||
|
||||
registry.get(atom);
|
||||
await vi.waitFor(() => {
|
||||
expect(Option.getOrNull(AsyncResult.value(registry.get(atom)))).toEqual(first);
|
||||
});
|
||||
|
||||
registry.refresh(atom);
|
||||
await vi.waitFor(() => expect(listEntries).toHaveBeenCalledTimes(2));
|
||||
const refreshing = registry.get(atom);
|
||||
expect(refreshing.waiting).toBe(true);
|
||||
expect(Option.getOrNull(AsyncResult.value(refreshing))).toEqual(first);
|
||||
|
||||
revalidation.resolve(second);
|
||||
await vi.waitFor(() => {
|
||||
expect(Option.getOrNull(AsyncResult.value(registry.get(atom)))).toEqual(second);
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps the latest optimistic draft when an older write finishes", async () => {
|
||||
vi.stubGlobal("window", {});
|
||||
const initial = {
|
||||
relativePath: "convex.json",
|
||||
contents: '{"nodeVersion":"20"}',
|
||||
byteLength: 20,
|
||||
truncated: false,
|
||||
} satisfies ProjectReadFileResult;
|
||||
const readFile = vi.fn<EnvironmentApi["projects"]["readFile"]>().mockResolvedValue(initial);
|
||||
__setEnvironmentApiOverrideForTests(environmentId, {
|
||||
projects: { readFile },
|
||||
} as unknown as EnvironmentApi);
|
||||
const atom = getProjectFileQueryAtom(environmentId, "/repo", "convex.json");
|
||||
|
||||
appAtomRegistry.get(atom);
|
||||
await vi.waitFor(() => {
|
||||
expect(Option.getOrNull(AsyncResult.value(appAtomRegistry.get(atom)))).toEqual(initial);
|
||||
});
|
||||
|
||||
setProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"220"}');
|
||||
setProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"22"}');
|
||||
|
||||
expect(
|
||||
confirmProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"220"}'),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
resolveProjectFileQueryData(
|
||||
environmentId,
|
||||
"/repo",
|
||||
"convex.json",
|
||||
Option.getOrNull(AsyncResult.value(appAtomRegistry.get(atom))),
|
||||
),
|
||||
).toEqual({
|
||||
relativePath: "convex.json",
|
||||
contents: '{"nodeVersion":"22"}',
|
||||
byteLength: 20,
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
confirmProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"22"}'),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ProjectListEntriesResult,
|
||||
ProjectReadFileResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect } from "react";
|
||||
|
||||
import { ensureEnvironmentApi } from "~/environmentApi";
|
||||
import { appAtomRegistry } from "~/rpc/atomRegistry";
|
||||
|
||||
const PROJECT_QUERY_STALE_TIME_MS = 30_000;
|
||||
const PROJECT_QUERY_IDLE_TTL_MS = 5 * 60_000;
|
||||
const EMPTY_PROJECT_FILE_PATH = "";
|
||||
interface OptimisticProjectFile {
|
||||
readonly data: ProjectReadFileResult;
|
||||
readonly confirmed: boolean;
|
||||
}
|
||||
|
||||
const optimisticProjectFiles = new Map<string, OptimisticProjectFile>();
|
||||
|
||||
class ProjectQueryError extends Data.TaggedError("ProjectQueryError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
function queryError(message: string, cause: unknown): ProjectQueryError {
|
||||
return new ProjectQueryError({ message, cause });
|
||||
}
|
||||
|
||||
function entriesKey(environmentId: EnvironmentId, cwd: string): string {
|
||||
return [environmentId, cwd].map(encodeURIComponent).join("|");
|
||||
}
|
||||
|
||||
function fileKey(environmentId: EnvironmentId, cwd: string, relativePath: string): string {
|
||||
return [environmentId, cwd, relativePath].map(encodeURIComponent).join("|");
|
||||
}
|
||||
|
||||
function keyParts(key: string): string[] {
|
||||
return key.split("|").map(decodeURIComponent);
|
||||
}
|
||||
|
||||
const projectEntriesQueryAtom = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => {
|
||||
const [environmentId, cwd] = keyParts(key) as [EnvironmentId, string];
|
||||
return ensureEnvironmentApi(environmentId).projects.listEntries({ cwd });
|
||||
},
|
||||
catch: (cause) => queryError("Could not load workspace files.", cause),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.swr({
|
||||
staleTime: PROJECT_QUERY_STALE_TIME_MS,
|
||||
revalidateOnMount: true,
|
||||
}),
|
||||
Atom.setIdleTTL(PROJECT_QUERY_IDLE_TTL_MS),
|
||||
Atom.withLabel(`projects:entries:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const projectFileQueryAtom = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => {
|
||||
const [environmentId, cwd, relativePath] = keyParts(key) as [EnvironmentId, string, string];
|
||||
if (relativePath === EMPTY_PROJECT_FILE_PATH) return Promise.resolve(null);
|
||||
return ensureEnvironmentApi(environmentId).projects.readFile({ cwd, relativePath });
|
||||
},
|
||||
catch: (cause) => queryError("Could not read workspace file.", cause),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.swr({
|
||||
staleTime: PROJECT_QUERY_STALE_TIME_MS,
|
||||
revalidateOnMount: true,
|
||||
}),
|
||||
Atom.setIdleTTL(PROJECT_QUERY_IDLE_TTL_MS),
|
||||
Atom.withLabel(`projects:file:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
interface ProjectQueryState<A> {
|
||||
readonly data: A | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
export function getProjectEntriesQueryAtom(environmentId: EnvironmentId, cwd: string) {
|
||||
return projectEntriesQueryAtom(entriesKey(environmentId, cwd));
|
||||
}
|
||||
|
||||
export function getProjectFileQueryAtom(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string | null,
|
||||
) {
|
||||
return projectFileQueryAtom(fileKey(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH));
|
||||
}
|
||||
|
||||
export function setProjectFileQueryData(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
): void {
|
||||
const key = fileKey(environmentId, cwd, relativePath);
|
||||
optimisticProjectFiles.set(key, {
|
||||
confirmed: false,
|
||||
data: {
|
||||
relativePath,
|
||||
contents,
|
||||
byteLength: new TextEncoder().encode(contents).byteLength,
|
||||
truncated: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function confirmProjectFileQueryData(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
): boolean {
|
||||
const key = fileKey(environmentId, cwd, relativePath);
|
||||
const optimisticFile = optimisticProjectFiles.get(key);
|
||||
if (optimisticFile?.data.contents !== contents) return false;
|
||||
|
||||
optimisticProjectFiles.set(key, { ...optimisticFile, confirmed: true });
|
||||
appAtomRegistry.refresh(getProjectFileQueryAtom(environmentId, cwd, relativePath));
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resolveProjectFileQueryData(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string | null,
|
||||
data: ProjectReadFileResult | null,
|
||||
): ProjectReadFileResult | null {
|
||||
if (relativePath === null) return data;
|
||||
return optimisticProjectFiles.get(fileKey(environmentId, cwd, relativePath))?.data ?? data;
|
||||
}
|
||||
|
||||
export function __resetProjectFileQueryDataForTests(): void {
|
||||
optimisticProjectFiles.clear();
|
||||
}
|
||||
|
||||
function errorMessage<A>(result: AsyncResult.AsyncResult<A, unknown>): string | null {
|
||||
if (result._tag !== "Failure") return null;
|
||||
const cause = Cause.squash(result.cause);
|
||||
return cause instanceof Error ? cause.message : "Workspace query failed.";
|
||||
}
|
||||
|
||||
export function useProjectEntriesQuery(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
): ProjectQueryState<ProjectListEntriesResult> {
|
||||
const atom = getProjectEntriesQueryAtom(environmentId, cwd);
|
||||
const result = useAtomValue(atom);
|
||||
const refresh = useCallback(() => appAtomRegistry.refresh(atom), [atom]);
|
||||
return {
|
||||
data: Option.getOrNull(AsyncResult.value(result)),
|
||||
error: errorMessage(result),
|
||||
isPending: result.waiting,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
|
||||
export function useProjectFileQuery(
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
relativePath: string | null,
|
||||
): ProjectQueryState<ProjectReadFileResult> {
|
||||
const atom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
|
||||
const result = useAtomValue(atom);
|
||||
const refresh = useCallback(() => appAtomRegistry.refresh(atom), [atom]);
|
||||
const data = Option.getOrNull(AsyncResult.value(result));
|
||||
const optimisticFile =
|
||||
relativePath === null
|
||||
? undefined
|
||||
: optimisticProjectFiles.get(fileKey(environmentId, cwd, relativePath));
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
relativePath === null ||
|
||||
optimisticFile === undefined ||
|
||||
!optimisticFile.confirmed ||
|
||||
data?.contents !== optimisticFile.data.contents
|
||||
) {
|
||||
return;
|
||||
}
|
||||
optimisticProjectFiles.delete(fileKey(environmentId, cwd, relativePath));
|
||||
}, [cwd, data?.contents, environmentId, optimisticFile, relativePath]);
|
||||
|
||||
return {
|
||||
data: optimisticFile?.data ?? data,
|
||||
error: errorMessage(result),
|
||||
isPending: result.waiting,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -21,7 +21,11 @@ const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
|
||||
* via a drag handle on the left edge; width persists per browser. In
|
||||
* sheet/sidebar modes the parent owns the size.
|
||||
*/
|
||||
export function PreviewPanelShell(props: { mode: PreviewPanelMode; children: ReactNode }) {
|
||||
export function PreviewPanelShell(props: {
|
||||
mode: PreviewPanelMode;
|
||||
maximized?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
|
||||
const isInline = props.mode === "inline";
|
||||
const maxWidth = useViewportClampedMaxWidth();
|
||||
@@ -37,12 +41,17 @@ export function PreviewPanelShell(props: { mode: PreviewPanelMode; children: Rea
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex h-full min-h-0 min-w-0 flex-col self-stretch bg-background",
|
||||
isInline ? "shrink-0 border-l border-border" : "w-full",
|
||||
isInline
|
||||
? props.maximized
|
||||
? "flex-1 border-l border-border"
|
||||
: "shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
)}
|
||||
style={isInline ? { width: `${width}px` } : undefined}
|
||||
style={isInline && !props.maximized ? { width: `${width}px` } : undefined}
|
||||
data-preview-panel-mode={props.mode}
|
||||
data-preview-panel-maximized={props.maximized ? "true" : "false"}
|
||||
>
|
||||
{isInline ? <RightPanelResizeHandle handlers={handlers} /> : null}
|
||||
{isInline && !props.maximized ? <RightPanelResizeHandle handlers={handlers} /> : null}
|
||||
{useDragRegion ? <div className="electron-drag-region h-0 w-full" aria-hidden /> : null}
|
||||
{props.children}
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,8 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
|
||||
onMetadata: (callback, options) => rpcClient.terminal.onMetadata(callback, options),
|
||||
},
|
||||
projects: {
|
||||
listEntries: rpcClient.projects.listEntries,
|
||||
readFile: rpcClient.projects.readFile,
|
||||
searchEntries: rpcClient.projects.searchEntries,
|
||||
writeFile: rpcClient.projects.writeFile,
|
||||
},
|
||||
|
||||
@@ -121,6 +121,8 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
subscribePorts: vi.fn(() => () => undefined),
|
||||
},
|
||||
projects: {
|
||||
listEntries: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
searchEntries: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
},
|
||||
|
||||
@@ -4,6 +4,30 @@
|
||||
/* Window Controls Overlay: active when Electron exposes native titlebar control geometry. */
|
||||
@custom-variant wco (&:is(.wco, .wco *));
|
||||
|
||||
:root {
|
||||
--workspace-topbar-height: 52px;
|
||||
--workspace-controls-top: 0px;
|
||||
--workspace-controls-right: calc(env(safe-area-inset-right) + 0.75rem);
|
||||
--workspace-native-controls-inset: 0px;
|
||||
}
|
||||
|
||||
@media (width >= 40rem) {
|
||||
:root {
|
||||
--workspace-controls-right: calc(env(safe-area-inset-right) + 1.25rem);
|
||||
}
|
||||
}
|
||||
|
||||
.wco {
|
||||
--workspace-topbar-height: env(titlebar-area-height, 52px);
|
||||
--workspace-controls-top: env(titlebar-area-y, 0px);
|
||||
--workspace-controls-right: calc(
|
||||
100vw - env(titlebar-area-width, 100vw) - env(titlebar-area-x, 0px) + 1em
|
||||
);
|
||||
--workspace-native-controls-inset: calc(
|
||||
100vw - env(titlebar-area-width, 100vw) - env(titlebar-area-x, 0px) + 1em
|
||||
);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--animate-skeleton: skeleton 2s -1s infinite linear;
|
||||
--font-sans:
|
||||
@@ -71,6 +95,25 @@
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.workspace-topbar {
|
||||
display: flex;
|
||||
height: var(--workspace-topbar-height);
|
||||
min-height: var(--workspace-topbar-height);
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.workspace-titlebar-controls {
|
||||
position: absolute;
|
||||
top: var(--workspace-controls-top);
|
||||
right: var(--workspace-controls-right);
|
||||
display: flex;
|
||||
height: var(--workspace-topbar-height);
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
/* Safe-area inset utilities for surfaces that opt into edge-to-edge rendering.
|
||||
Insets resolve to 0 when the browser already constrains the layout viewport
|
||||
to the safe area. */
|
||||
|
||||
@@ -55,6 +55,8 @@ const rpcClientMock = {
|
||||
),
|
||||
},
|
||||
projects: {
|
||||
listEntries: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
searchEntries: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
},
|
||||
|
||||
@@ -83,6 +83,7 @@ describe("resolveMarkdownFileLinkTarget", () => {
|
||||
),
|
||||
).toMatchObject({
|
||||
displayPath: "t3code/apps/web/src/session-logic.ts:501",
|
||||
workspaceRelativePath: "apps/web/src/session-logic.ts",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,6 +96,14 @@ describe("resolveMarkdownFileLinkTarget", () => {
|
||||
).toMatchObject({
|
||||
displayPath:
|
||||
"t3code/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",
|
||||
workspaceRelativePath:
|
||||
"apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not create a preview path for files outside the workspace", () => {
|
||||
expect(resolveMarkdownFileLinkMeta("/tmp/report.ts", "/repo/project")).toMatchObject({
|
||||
workspaceRelativePath: null,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface MarkdownFileLinkMeta {
|
||||
filePath: string;
|
||||
targetPath: string;
|
||||
displayPath: string;
|
||||
workspaceRelativePath: string | null;
|
||||
basename: string;
|
||||
line?: number;
|
||||
column?: number;
|
||||
@@ -174,6 +175,19 @@ function basenameOfPath(path: string): string {
|
||||
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
|
||||
}
|
||||
|
||||
function workspaceRelativePath(path: string, workspaceRoot: string | undefined): string | null {
|
||||
if (!workspaceRoot) return null;
|
||||
const normalizedPath = normalizeWindowsDrivePath(path.replaceAll("\\", "/"));
|
||||
const normalizedRoot = normalizeWindowsDrivePath(workspaceRoot.replaceAll("\\", "/")).replace(
|
||||
/\/+$/,
|
||||
"",
|
||||
);
|
||||
const pathForCompare = normalizedPath.toLowerCase();
|
||||
const rootForCompare = normalizedRoot.toLowerCase();
|
||||
if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
|
||||
return normalizedPath.slice(normalizedRoot.length + 1);
|
||||
}
|
||||
|
||||
export function resolveMarkdownFileLinkMeta(
|
||||
href: string | undefined,
|
||||
cwd?: string,
|
||||
@@ -191,6 +205,7 @@ export function resolveMarkdownFileLinkMeta(
|
||||
filePath: path,
|
||||
targetPath,
|
||||
displayPath: formatWorkspaceRelativePath(targetPath, cwd),
|
||||
workspaceRelativePath: workspaceRelativePath(path, cwd),
|
||||
basename: basenameOfPath(path),
|
||||
...(lineNumber !== undefined ? { line: lineNumber } : {}),
|
||||
...(columnNumber !== undefined ? { column: columnNumber } : {}),
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
hasSpecificPierreIconForFileName,
|
||||
resolvePierreIconForEntry,
|
||||
syntheticFileNameForLanguageId,
|
||||
T3_PIERRE_ICONS,
|
||||
} from "./pierre-icons";
|
||||
|
||||
describe("Pierre file icons", () => {
|
||||
it("uses Pierre exact filename and complete-set extension mappings", () => {
|
||||
assert.equal(resolvePierreIconForEntry("Dockerfile", "file")?.token, "docker");
|
||||
assert.equal(resolvePierreIconForEntry("src/Button.tsx", "file")?.token, "react");
|
||||
assert.equal(resolvePierreIconForEntry("vite.config.ts", "file")?.token, "vite");
|
||||
});
|
||||
|
||||
it("extends Pierre with T3-specific exact filename icons", () => {
|
||||
assert.equal(
|
||||
resolvePierreIconForEntry("package.json", "file")?.name,
|
||||
"t3-file-icon-package-json",
|
||||
);
|
||||
assert.equal(
|
||||
resolvePierreIconForEntry("config/tsconfig.json", "file")?.name,
|
||||
"t3-file-icon-tsconfig",
|
||||
);
|
||||
assert.equal(resolvePierreIconForEntry("AGENTS.md", "file")?.name, "t3-file-icon-agents");
|
||||
assert.equal(resolvePierreIconForEntry("CLAUDE.md", "file")?.name, "t3-file-icon-claude");
|
||||
assert.equal(resolvePierreIconForEntry("README.md", "file")?.name, "t3-file-icon-readme");
|
||||
assert.equal(resolvePierreIconForEntry("pnpm-lock.yaml", "file")?.name, "t3-file-icon-pnpm");
|
||||
assert.equal(
|
||||
resolvePierreIconForEntry("pnpm-workspace.yaml", "file")?.name,
|
||||
"t3-file-icon-pnpm",
|
||||
);
|
||||
});
|
||||
|
||||
it("ships every custom icon referenced by the extended resolver", () => {
|
||||
const customIconNames = new Set(Object.values(T3_PIERRE_ICONS.byFileName));
|
||||
for (const iconName of customIconNames) {
|
||||
assert.include(T3_PIERRE_ICONS.spriteSheet, `id="${iconName}"`);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the Pierre default icon for unknown file types", () => {
|
||||
assert.equal(resolvePierreIconForEntry("artifact.unknown-ext", "file")?.token, "default");
|
||||
assert.isFalse(hasSpecificPierreIconForFileName("artifact.unknown-ext"));
|
||||
});
|
||||
|
||||
it("leaves directory rendering to the shared folder fallback", () => {
|
||||
assert.isNull(resolvePierreIconForEntry("packages/client-runtime", "directory"));
|
||||
});
|
||||
|
||||
it("normalizes common markdown fence language aliases", () => {
|
||||
assert.equal(syntheticFileNameForLanguageId("typescript"), "file.ts");
|
||||
assert.equal(syntheticFileNameForLanguageId("shellscript"), "file.sh");
|
||||
assert.equal(syntheticFileNameForLanguageId("python"), "file.py");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import {
|
||||
createFileTreeIconResolver,
|
||||
getBuiltInSpriteSheet,
|
||||
type FileTreeIcons,
|
||||
} from "@pierre/trees";
|
||||
|
||||
export interface PierreIconResolution {
|
||||
name: string;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
const PIERRE_ICON_SPRITE_ID = "t3code-pierre-file-icon-sprite";
|
||||
|
||||
const T3_FILE_ICON_SPRITE = `
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" aria-hidden="true">
|
||||
<symbol id="t3-file-icon-package-json" viewBox="0 0 32 32">
|
||||
<path d="M2 2H30V30H2" fill="#c12127" />
|
||||
<path d="M7.25 7.25h17.5v17.5h-3.5v-14H16v14H7.25" fill="#fff" />
|
||||
</symbol>
|
||||
<symbol id="t3-file-icon-tsconfig" viewBox="0 0 32 32">
|
||||
<path d="M23.827 8.243a4.424 4.424 0 0 1 2.223 1.281 5.853 5.853 0 0 1 .852 1.143c.011.045-1.534 1.083-2.471 1.662-.034.023-.169-.124-.322-.35a2.014 2.014 0 0 0-1.67-1c-1.077-.074-1.771.49-1.766 1.433a1.3 1.3 0 0 0 .153.666c.237.49.677.784 2.059 1.383 2.544 1.1 3.636 1.817 4.31 2.843a5.158 5.158 0 0 1 .416 4.333 4.764 4.764 0 0 1-3.932 2.815 10.9 10.9 0 0 1-2.708-.028 6.531 6.531 0 0 1-3.616-1.884 6.278 6.278 0 0 1-.926-1.371 2.655 2.655 0 0 1 .327-.208c.158-.09.756-.434 1.32-.761l1.024-.6.214.312a4.771 4.771 0 0 0 1.35 1.292 3.3 3.3 0 0 0 3.458-.175 1.545 1.545 0 0 0 .2-1.974c-.276-.4-.84-.727-2.443-1.422a8.8 8.8 0 0 1-3.349-2.055 4.687 4.687 0 0 1-.976-1.777 7.116 7.116 0 0 1-.062-2.268 4.332 4.332 0 0 1 3.644-3.374 9 9 0 0 1 2.71.01ZM15.484 9.726l.011 1.454h-4.63v13.148H7.6V11.183H2.97V9.755a13.986 13.986 0 0 1 .04-1.466c.017-.023 2.832-.034 6.245-.028l6.211.017Z" fill="#007acc" />
|
||||
<path d="m27.075 25.107.363-.361c1.68.055 1.706 0 1.78-.177l.462-1.124.034-.107-.038-.093c-.02-.049-.081-.2-1.13-1.2v-.526c1.211-1.166 1.185-1.226 1.116-1.4l-.46-1.136c-.069-.17-.1-.237-1.763-.191l-.364-.367a8.138 8.138 0 0 0-.057-1.657l-.047-.106-1.2-.525c-.177-.081-.239-.11-1.372 1.124l-.509-.008c-1.167-1.245-1.222-1.223-1.4-1.152l-1.115.452c-.175.071-.236.1-.169 1.79l-.36.359c-1.68-.055-1.7 0-1.778.177L18.606 20l-.036.108.038.094c.02.048.078.194 1.13 1.2v.525c-1.211 1.166-1.184 1.226-1.115 1.4l.459 1.137c.07.174.1.236 1.763.192l.363.377a8.169 8.169 0 0 0 .055 1.654l.047.107 1.208.528c.176.073.236.1 1.366-1.13l.509.006c1.168 1.247 1.228 1.223 1.4 1.154l1.113-.45c.176-.075.237-.102.169-1.795Zm-4.788-2.632a2 2 0 1 1 2.618 1.14 2.023 2.023 0 0 1-2.618-1.14Z" fill="#99b8c4" />
|
||||
</symbol>
|
||||
<symbol id="t3-file-icon-agents" viewBox="0 0 32 32">
|
||||
<path fill="currentColor" d="M27.2 16c0-6.19-5.01-11.2-11.2-11.2C9.81 4.8 4.8 9.81 4.8 16S9.81 27.2 16 27.2c6.19 0 11.2-5.01 11.2-11.2Zm-5.6 2.1a1.4 1.4 0 1 1 0 2.8h-4.2a1.4 1.4 0 1 1 0-2.8Zm-11.2-6.8c.622-.373 1.42-.208 1.84.361l.079.119 2.1 3.5.088.171c.15.351.15.748 0 1.1l-.088.171-2.1 3.5a1.4 1.4 0 0 1-2.4-1.44L11.59 16l-1.67-2.78-.067-.127c-.302-.642-.075-1.42.547-1.79ZM30 16c0 7.73-6.27 14-14 14S2 23.73 2 16 8.27 2 16 2s14 6.27 14 14Z" />
|
||||
</symbol>
|
||||
<symbol id="t3-file-icon-claude" viewBox="0 0 32 32">
|
||||
<path fill="#d97757" d="m7.5 20.61 5.5-3.08.1-.27-.1-.15h-.27l-.92-.06a234.2 234.2 0 0 1-8.51-.34l-.67-.14-.62-.82.06-.41.56-.38.8.07c3.08.2 6.15.4 9.21.72h.46l.06-.19-.16-.1-.12-.12-2.74-1.86c-2.04-1.3-3.55-2.43-5.38-3.68l-.43-.54-.18-1.18.76-.84 1.03.07.26.07c2.03 1.6 4.1 3.14 6.17 4.66l.43.36.17-.12.02-.09-.2-.32c-1.43-2.6-2.55-4.62-4-6.96l-.2-.72c-.08-.3-.13-.55-.13-.85l.87-1.18.49-.16 1.16.16.49.42c1.4 3.31 2.76 5.93 4.23 8.83l.29.97.1.3h.19v-.17c.65-3.42 0-6.57 1.22-9.53l.87-.57.68.33.56.8-.08.51c-.37 2.62-.92 5.22-1.4 7.82h.24l.29-.29a68.66 68.66 0 0 1 4.91-5.94l.64-.5h1.2l.89 1.32-.4 1.36a53.45 53.45 0 0 0-4.66 6.47l.09.13.22-.02c2.4-.57 4.84-.99 7.27-1.4l.97.45.1.46-.37.94c-3 .72-6 1.34-9 2.05l-.05.04.06.07c2.7.26 5.62.3 7.99.47l.92.61.55.75-.1.56-1.4.73c-2.93-.7-5.19-1.22-7.91-1.9h-.22v.13c2.18 2.12 4.6 4.27 6.54 6.07l.15.68-.38.53-.4-.06c-2.04-1.43-3.9-3.09-5.8-4.7h-.15v.2l.52.76c1.14 1.79 2.64 3.25 2.87 5.37l-.2.41-.7.25-.78-.14a73.16 73.16 0 0 1-4.58-7.04l-.17.09-.78 8.46-.37.43-.85.33-.71-.54-.38-.87a114 114 0 0 0 1.53-7.97l.2-.73-.01-.05-.16.02a76.67 76.67 0 0 1-6.23 7.88l-.48.2-.84-.44.08-.77.47-.69c2.07-2.57 3.54-4.66 5.54-7v-.19h-.07l-7.4 4.8-1.31.17-.57-.53.07-.87.27-.28 2.23-1.53Z" />
|
||||
</symbol>
|
||||
<symbol id="t3-file-icon-readme" viewBox="0 0 32 32">
|
||||
<rect x="2.5" y="7.955" width="27" height="16.091" fill="none" stroke="#b48a5a" />
|
||||
<path fill="#b48a5a" d="M5.909 20.636v-9.272h2.727l2.728 3.409 2.727-3.409h2.727v9.272h-2.727v-5.318l-2.727 3.409-2.728-3.409v5.318H5.91Zm17.046 0-4.091-4.5h2.727v-4.772h2.727v4.772h2.727l-4.09 4.5Z" />
|
||||
</symbol>
|
||||
<symbol id="t3-file-icon-pnpm" viewBox="0 0 32 32">
|
||||
<path fill="#f9ad00" d="M30 10.75h-8.749V2H30Zm-9.626 0h-8.75V2h8.75Zm-9.625 0H2V2h8.749ZM30 20.375h-8.749v-8.75H30Z" />
|
||||
<path fill="currentColor" d="M20.374 20.375h-8.75v-8.75h8.75Zm0 9.625h-8.75v-8.75h8.75ZM30 30h-8.749v-8.75H30Zm-19.251 0H2v-8.75h8.749Z" />
|
||||
</symbol>
|
||||
</svg>`;
|
||||
|
||||
export const T3_PIERRE_ICONS = {
|
||||
set: "complete",
|
||||
colored: true,
|
||||
spriteSheet: T3_FILE_ICON_SPRITE,
|
||||
byFileName: {
|
||||
"package.json": "t3-file-icon-package-json",
|
||||
"tsconfig.json": "t3-file-icon-tsconfig",
|
||||
"agents.md": "t3-file-icon-agents",
|
||||
"claude.md": "t3-file-icon-claude",
|
||||
"readme.md": "t3-file-icon-readme",
|
||||
"pnpm-lock.yaml": "t3-file-icon-pnpm",
|
||||
"pnpm-workspace.yaml": "t3-file-icon-pnpm",
|
||||
},
|
||||
} satisfies FileTreeIcons;
|
||||
|
||||
const completeIconResolver = createFileTreeIconResolver(T3_PIERRE_ICONS);
|
||||
|
||||
const LANGUAGE_EXTENSION_ALIASES: Record<string, string> = {
|
||||
bash: "sh",
|
||||
csharp: "cs",
|
||||
dockerfile: "dockerfile",
|
||||
javascript: "js",
|
||||
jsx: "jsx",
|
||||
markdown: "md",
|
||||
mdx: "mdx",
|
||||
plaintext: "txt",
|
||||
python: "py",
|
||||
ruby: "rb",
|
||||
rust: "rs",
|
||||
shell: "sh",
|
||||
shellscript: "sh",
|
||||
swift: "swift",
|
||||
typescript: "ts",
|
||||
tsx: "tsx",
|
||||
yaml: "yml",
|
||||
};
|
||||
|
||||
export function basenameOfPath(pathValue: string): string {
|
||||
const slashIndex = pathValue.lastIndexOf("/");
|
||||
return slashIndex === -1 ? pathValue : pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
export function inferEntryKindFromPath(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) return "directory";
|
||||
return base.includes(".") ? "file" : "directory";
|
||||
}
|
||||
|
||||
export function syntheticFileNameForLanguageId(languageId: string): string {
|
||||
const normalized = languageId.toLowerCase();
|
||||
return `file.${LANGUAGE_EXTENSION_ALIASES[normalized] ?? normalized}`;
|
||||
}
|
||||
|
||||
export function resolvePierreIconForEntry(
|
||||
pathValue: string,
|
||||
kind: "file" | "directory",
|
||||
): PierreIconResolution | null {
|
||||
if (kind === "directory") return null;
|
||||
return completeIconResolver.resolveIcon("file-tree-icon-file", pathValue);
|
||||
}
|
||||
|
||||
export function hasSpecificPierreIconForFileName(fileName: string): boolean {
|
||||
return resolvePierreIconForEntry(fileName, "file")?.token !== "default";
|
||||
}
|
||||
|
||||
export function ensurePierreIconSprite(): void {
|
||||
if (typeof document === "undefined" || document.getElementById(PIERRE_ICON_SPRITE_ID)) return;
|
||||
const container = document.createElement("div");
|
||||
container.id = PIERRE_ICON_SPRITE_ID;
|
||||
container.setAttribute("aria-hidden", "true");
|
||||
container.style.position = "absolute";
|
||||
container.style.width = "0";
|
||||
container.style.height = "0";
|
||||
container.style.overflow = "hidden";
|
||||
container.style.pointerEvents = "none";
|
||||
container.innerHTML = `${getBuiltInSpriteSheet("complete")}${T3_FILE_ICON_SPRITE}`;
|
||||
document.body.prepend(container);
|
||||
}
|
||||
@@ -88,6 +88,54 @@ describe("rightPanelStore", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps files as a singleton surface", () => {
|
||||
useRightPanelStore.getState().open(refA, "files");
|
||||
useRightPanelStore.getState().open(refA, "files");
|
||||
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
|
||||
isOpen: true,
|
||||
activeSurfaceId: "files",
|
||||
surfaces: [{ id: "files", kind: "files" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces the standalone explorer with peer file surfaces", () => {
|
||||
useRightPanelStore.getState().open(refA, "files");
|
||||
useRightPanelStore.getState().openFile(refA, "src/index.ts");
|
||||
useRightPanelStore.getState().openFile(refA, "src/index.ts");
|
||||
useRightPanelStore.getState().openFile(refA, "README.md");
|
||||
|
||||
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
|
||||
isOpen: true,
|
||||
activeSurfaceId: "file:README.md",
|
||||
surfaces: [
|
||||
{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" },
|
||||
{ id: "file:README.md", kind: "file", relativePath: "README.md" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("removes persisted file surfaces when their workspace no longer exists", () => {
|
||||
useRightPanelStore.getState().openFile(refA, "src/index.ts");
|
||||
useRightPanelStore.getState().open(refA, "plan");
|
||||
useRightPanelStore.getState().openFile(refA, "README.md");
|
||||
|
||||
useRightPanelStore.getState().reconcileFileSurfaces(refA, false);
|
||||
|
||||
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
|
||||
isOpen: true,
|
||||
activeSurfaceId: "plan",
|
||||
surfaces: [{ id: "plan", kind: "plan" }],
|
||||
});
|
||||
|
||||
useRightPanelStore.getState().openFile(refB, "conductor.json");
|
||||
useRightPanelStore.getState().reconcileFileSurfaces(refB, false);
|
||||
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB)).toEqual({
|
||||
isOpen: false,
|
||||
activeSurfaceId: null,
|
||||
surfaces: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("close hides the panel without clearing its selected surface", () => {
|
||||
useRightPanelStore.getState().open(refA, "plan");
|
||||
useRightPanelStore.getState().close(refA);
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
* This is intentionally a shallow workspace model: it owns an ordered set of
|
||||
* surface descriptors and the active surface, while each feature continues to
|
||||
* own its durable resource state. Browser surfaces point at preview tab ids,
|
||||
* terminal surfaces point at terminal session ids, and diff/plan remain
|
||||
* singleton surfaces.
|
||||
* terminal surfaces point at terminal session ids, file surfaces point at
|
||||
* workspace paths, and diff/plan/files remain singleton surfaces.
|
||||
*/
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
@@ -14,7 +14,7 @@ import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
import { resolveStorage } from "./lib/storage";
|
||||
|
||||
export const RIGHT_PANEL_KINDS = ["plan", "diff", "preview", "terminal"] as const;
|
||||
export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
|
||||
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
|
||||
|
||||
export type RightPanelSurface =
|
||||
@@ -29,10 +29,12 @@ export type RightPanelSurface =
|
||||
splitDirection?: "horizontal" | "vertical";
|
||||
}
|
||||
| { id: "diff"; kind: "diff" }
|
||||
| { id: "files"; kind: "files" }
|
||||
| { id: `file:${string}`; kind: "file"; relativePath: string }
|
||||
| { id: "plan"; kind: "plan" };
|
||||
|
||||
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
|
||||
const RIGHT_PANEL_STORAGE_VERSION = 5;
|
||||
const RIGHT_PANEL_STORAGE_VERSION = 6;
|
||||
|
||||
export interface ThreadRightPanelState {
|
||||
isOpen: boolean;
|
||||
@@ -42,8 +44,9 @@ export interface ThreadRightPanelState {
|
||||
|
||||
interface RightPanelStoreState {
|
||||
byThreadKey: Record<string, ThreadRightPanelState>;
|
||||
open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "terminal">) => void;
|
||||
open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
|
||||
openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
|
||||
openFile: (ref: ScopedThreadRef, relativePath: string) => void;
|
||||
openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
|
||||
splitTerminal: (
|
||||
ref: ScopedThreadRef,
|
||||
@@ -56,10 +59,11 @@ interface RightPanelStoreState {
|
||||
activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
|
||||
closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
|
||||
reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
|
||||
reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
|
||||
show: (ref: ScopedThreadRef) => void;
|
||||
close: (ref: ScopedThreadRef) => void;
|
||||
toggleVisibility: (ref: ScopedThreadRef) => void;
|
||||
toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "terminal">) => void;
|
||||
toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
|
||||
removeThread: (ref: ScopedThreadRef) => void;
|
||||
}
|
||||
|
||||
@@ -70,11 +74,13 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = {
|
||||
};
|
||||
|
||||
const singletonSurface = (
|
||||
kind: Exclude<RightPanelKind, "preview" | "terminal">,
|
||||
kind: Exclude<RightPanelKind, "file" | "preview" | "terminal">,
|
||||
): RightPanelSurface => {
|
||||
switch (kind) {
|
||||
case "diff":
|
||||
return { id: "diff", kind };
|
||||
case "files":
|
||||
return { id: "files", kind };
|
||||
case "plan":
|
||||
return { id: "plan", kind };
|
||||
}
|
||||
@@ -85,6 +91,12 @@ const browserSurface = (tabId: string | null): RightPanelSurface =>
|
||||
? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
|
||||
: { id: "browser:new", kind: "preview", resourceId: null };
|
||||
|
||||
const fileSurface = (relativePath: string): RightPanelSurface => ({
|
||||
id: `file:${relativePath}`,
|
||||
kind: "file",
|
||||
relativePath,
|
||||
});
|
||||
|
||||
const terminalSurface = (terminalId: string): RightPanelSurface => ({
|
||||
id: `terminal:${terminalId}`,
|
||||
kind: "terminal",
|
||||
@@ -213,6 +225,18 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
|
||||
return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
|
||||
}),
|
||||
})),
|
||||
openFile: (ref, relativePath) =>
|
||||
set((state) => ({
|
||||
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
|
||||
const withoutStandaloneExplorer = current.surfaces.filter(
|
||||
(surface) => surface.kind !== "files",
|
||||
);
|
||||
return upsertSurface(
|
||||
{ ...current, surfaces: withoutStandaloneExplorer },
|
||||
fileSurface(relativePath),
|
||||
);
|
||||
}),
|
||||
})),
|
||||
openTerminal: (ref, terminalId) =>
|
||||
set((state) => ({
|
||||
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
|
||||
@@ -339,6 +363,27 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
|
||||
};
|
||||
}),
|
||||
})),
|
||||
reconcileFileSurfaces: (ref, workspaceAvailable) =>
|
||||
set((state) => ({
|
||||
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
|
||||
if (workspaceAvailable) return current;
|
||||
const surfaces = current.surfaces.filter(
|
||||
(surface) => surface.kind !== "files" && surface.kind !== "file",
|
||||
);
|
||||
if (surfaces.length === current.surfaces.length) return current;
|
||||
const activeStillExists = surfaces.some(
|
||||
(surface) => surface.id === current.activeSurfaceId,
|
||||
);
|
||||
return {
|
||||
...current,
|
||||
isOpen: surfaces.length > 0 ? current.isOpen : false,
|
||||
surfaces,
|
||||
activeSurfaceId: activeStillExists
|
||||
? current.activeSurfaceId
|
||||
: (surfaces.at(-1)?.id ?? null),
|
||||
};
|
||||
}),
|
||||
})),
|
||||
show: (ref) =>
|
||||
set((state) => ({
|
||||
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
|
||||
|
||||
@@ -1,481 +0,0 @@
|
||||
{
|
||||
"version": "12.17.0",
|
||||
"source": "https://raw.githubusercontent.com/vscode-icons/vscode-icons/v12.17.0/src/iconsManifest/languages.ts",
|
||||
"generatedAt": "2026-02-17T20:03:11.362Z",
|
||||
"extensionToLanguageId": {
|
||||
"as": "actionscript",
|
||||
"ada": "ada",
|
||||
"prw": "advpl",
|
||||
"affect": "affectscript",
|
||||
"agda": "agda",
|
||||
"al": "al",
|
||||
"alloy": "alloy",
|
||||
"ansible": "ansible",
|
||||
"g4": "antlr",
|
||||
"any": "anyscript",
|
||||
"htaccess": "apacheconf",
|
||||
"cls": "apex",
|
||||
"apib": "apiblueprint",
|
||||
"apl": "apl",
|
||||
"applescript": "applescript",
|
||||
"adoc": "asciidoc",
|
||||
"asp": "asp",
|
||||
"asm": "arm",
|
||||
"astro": "astro",
|
||||
"ats": "ats",
|
||||
"ahk": "ahk",
|
||||
"au3": "autoit",
|
||||
"am": "automake",
|
||||
"avcs": "avro",
|
||||
"azcli": "azcli",
|
||||
"azure-pipelines.yml": "azure-pipelines",
|
||||
"bal": "ballerina",
|
||||
"bat": "bat",
|
||||
"bats": "bats",
|
||||
"bzl": "bazel",
|
||||
"bf": "befunge",
|
||||
"bicep": "bicep",
|
||||
"bib": "bibtex",
|
||||
"biml": "biml",
|
||||
"bin": "code-text-binary",
|
||||
"rast": "biome_syntax_tree",
|
||||
"blade.php": "blade",
|
||||
"blitzbasic": "blitzbasic",
|
||||
"bolt": "bolt",
|
||||
"bsq": "bosque",
|
||||
"bru": "bruno",
|
||||
"buf.yaml": "buf",
|
||||
"lockb": "bun.lockb",
|
||||
"c": "c",
|
||||
"c3": "c3",
|
||||
"cal": "c-al",
|
||||
"cabal": "cabal",
|
||||
"capnp": "capnp",
|
||||
"casc": "casc",
|
||||
"cddl": "cddl",
|
||||
"ceylon": "ceylon",
|
||||
"cfc": "cfc",
|
||||
"cfm": "cfmhtml",
|
||||
"circom": "circom",
|
||||
"clojure": "clojure",
|
||||
"clojurescript": "clojurescript",
|
||||
"yml": "manifest-yaml",
|
||||
"cmake": "cmake",
|
||||
"cbl": "cobol",
|
||||
"ql": "ql",
|
||||
"coffee": "coffeescript",
|
||||
"cfml": "cfml",
|
||||
"confluence": "confluence",
|
||||
"ckbk": "cookbook",
|
||||
"instructions.md": "instructions",
|
||||
"cpp": "cpp",
|
||||
"cr": "crystal",
|
||||
"cs": "csharp",
|
||||
"css": "css",
|
||||
"wxss": "css",
|
||||
"acss": "css",
|
||||
"mcss": "css",
|
||||
"pcss": "css",
|
||||
"postcss": "css",
|
||||
"nss": "css",
|
||||
"ccss": "css",
|
||||
"less": "css",
|
||||
"scss": "css",
|
||||
"sass": "css",
|
||||
"csv": "csv",
|
||||
"feature": "cucumber",
|
||||
"cu": "cuda",
|
||||
"cypher": "cypher",
|
||||
"pyx": "cython",
|
||||
"dal": "dal",
|
||||
"dart": "dart",
|
||||
"dhall": "dhall",
|
||||
"html": "django-html",
|
||||
"diff": "diff",
|
||||
"d": "d",
|
||||
"hcl": "dockerbake",
|
||||
"dtx": "doctex",
|
||||
"env": "dotenv",
|
||||
"dot": "dotjs",
|
||||
"dox": "doxygen",
|
||||
"drawio": "drawio",
|
||||
"drl": "drools",
|
||||
"dtd": "dtd",
|
||||
"dust": "dustjs",
|
||||
"dylan": "dylan",
|
||||
"earthfile": "earthfile",
|
||||
"edge": "edge",
|
||||
"eex": "eex",
|
||||
"es": "es",
|
||||
"ex": "elixir",
|
||||
"elm": "elm",
|
||||
"erb": "erb",
|
||||
"erl": "erlang",
|
||||
"yaml": "esphome",
|
||||
"xlsx": "excel",
|
||||
"falcon": "falcon",
|
||||
"fql": "fql",
|
||||
"f": "fortran",
|
||||
"ftl": "ftl",
|
||||
"fs": "fsharp",
|
||||
"fthtml": "fthtml",
|
||||
"gspec": "galen",
|
||||
"gml": "gml-gms",
|
||||
"gcode": "gcode",
|
||||
"gen": "genstat",
|
||||
"git": "git-commit",
|
||||
"gleam": "gleam",
|
||||
"gjs": "glimmer-js",
|
||||
"glsl": "glsl",
|
||||
"glyphs": "glyphs",
|
||||
"gp": "gnuplot",
|
||||
"go": "go",
|
||||
"mod": "go.mod",
|
||||
"work": "go.work",
|
||||
"api": "goctl",
|
||||
"gd": "gdscript",
|
||||
"gradle.kts": "gradle-kotlin-dsl",
|
||||
"gr": "grain",
|
||||
"gql": "graphql",
|
||||
"gv": "dot",
|
||||
"grit": "grit",
|
||||
"groovy": "groovy",
|
||||
"haml": "haml",
|
||||
"hbs": "handlebars",
|
||||
"prg": "harbour",
|
||||
"hs": "haskell",
|
||||
"haxe": "haxe",
|
||||
"helm.tpl": "helm",
|
||||
"hjson": "hjson",
|
||||
"hlsl": "hlsl",
|
||||
"hosts": "hosts",
|
||||
"http": "http",
|
||||
"aff": "hunspell.aff",
|
||||
"hy": "hy",
|
||||
"hypr": "hypr",
|
||||
"icl": "icl",
|
||||
"imba": "imba",
|
||||
"4gl": "4GL",
|
||||
"ini": "ini",
|
||||
"ink": "ink",
|
||||
"iss": "innosetup",
|
||||
"io": "io",
|
||||
"janet": "janet",
|
||||
"java": "java",
|
||||
"js": "javascript",
|
||||
"mjs": "javascript",
|
||||
"cjs": "javascript",
|
||||
"es6": "javascript",
|
||||
"jake": "javascript",
|
||||
"jsm": "javascript",
|
||||
"jsx": "javascript",
|
||||
"njs": "javascript",
|
||||
"pac": "javascript",
|
||||
"sjs": "javascript",
|
||||
"ssjs": "javascript",
|
||||
"xsjs": "javascript",
|
||||
"xsjslib": "javascript",
|
||||
"jekyll": "jekyll",
|
||||
"jenkins": "jenkins",
|
||||
"jest-snap": "jest-snapshot",
|
||||
"jinja": "jinja",
|
||||
"json": "json",
|
||||
"jsonc": "jsonc",
|
||||
"jsonl": "jsonl",
|
||||
"jsonnet": "jsonnet",
|
||||
"json5": "json5",
|
||||
"jl": "julia",
|
||||
"id": "iodine",
|
||||
"k": "k",
|
||||
"kv": "kivy",
|
||||
"ks": "kos",
|
||||
"kt": "kotlin",
|
||||
"kusto": "kusto",
|
||||
"tex": "latex",
|
||||
"lark": "lark",
|
||||
"lat": "latino",
|
||||
"lean": "lean4",
|
||||
"flex": "lex",
|
||||
"ly": "lilypond",
|
||||
"lisp": "lisp",
|
||||
"lhs": "literate haskell",
|
||||
"log": "log",
|
||||
"lol": "lolcode",
|
||||
"lsl": "lsl",
|
||||
"lua": "lua",
|
||||
"m4": "m4",
|
||||
"mk": "makefile",
|
||||
"md": "markdown",
|
||||
"markdown": "markdown",
|
||||
"mdown": "markdown",
|
||||
"mkd": "markdown",
|
||||
"marko": "marko",
|
||||
"mat": "matlab",
|
||||
"ms": "maxscript",
|
||||
"mdx": "mdx",
|
||||
"mediawiki": "mediawiki",
|
||||
"mel": "mel",
|
||||
"mmd": "mermaid",
|
||||
"metal": "metal",
|
||||
"mcfunction": "bc-mcfunction",
|
||||
"mjml": "mjml",
|
||||
"pq": "powerquery",
|
||||
"mojo": "mojo",
|
||||
"ep": "mojolicious",
|
||||
"mongo": "mongo",
|
||||
"mson": "mson",
|
||||
"mv": "mv",
|
||||
"mvt": "mvt",
|
||||
"ne": "nearley",
|
||||
"nginx": "nginx",
|
||||
"nim": "nim",
|
||||
"nimble": "nimble",
|
||||
"nix": "nix",
|
||||
"nsi": "nsis",
|
||||
"nunjucks": "nunjucks",
|
||||
"nu": "nushell",
|
||||
"m": "objective-c",
|
||||
"mm": "objective-cpp",
|
||||
"ml": "ocaml",
|
||||
"o3": "ogone",
|
||||
"w": "abl",
|
||||
"things": "openhab",
|
||||
"org": "org",
|
||||
"pas": "pascal",
|
||||
"pddl": "pddl",
|
||||
"plan": "plan",
|
||||
"happenings": "happenings",
|
||||
"pl": "perl",
|
||||
"pl6": "perl6",
|
||||
"pgsql": "pgsql",
|
||||
"php": "php",
|
||||
"php4": "php",
|
||||
"php5": "php",
|
||||
"php7": "php",
|
||||
"phtml": "php",
|
||||
"phps": "php",
|
||||
"phpt": "php",
|
||||
"phar": "php",
|
||||
"aw": "php",
|
||||
"ctp": "php",
|
||||
"inc": "php",
|
||||
"php3": "php",
|
||||
"php8": "php",
|
||||
"module": "php",
|
||||
"theme": "php",
|
||||
"tpl": "php",
|
||||
"pine": "pine",
|
||||
"txt": "plaintext",
|
||||
"dbgasm": "platformio-debug.disassembly",
|
||||
"ddl": "plsql",
|
||||
"po": "po",
|
||||
"dib": "polyglot-notebook",
|
||||
"polymer": "polymer",
|
||||
"pony": "pony",
|
||||
"ps": "postscript",
|
||||
"ps1": "powershell",
|
||||
"prisma": "prisma",
|
||||
"pde": "pde",
|
||||
"pro": "prolog",
|
||||
"rules": "prometheus",
|
||||
"properties": "java-properties",
|
||||
"proto": "proto3",
|
||||
"pug": "jade",
|
||||
"pp": "puppet",
|
||||
"purs": "purescript",
|
||||
"arr": "pyret",
|
||||
"pyscript": "pyscript",
|
||||
"py": "python",
|
||||
"pyi": "python",
|
||||
"pyw": "python",
|
||||
"pyc": "python",
|
||||
"pyd": "python",
|
||||
"pyo": "python",
|
||||
"pxd": "python",
|
||||
"pxi": "python",
|
||||
"rpy": "python",
|
||||
"cpy": "python",
|
||||
"ipy": "python",
|
||||
"pyowo": "pythowo",
|
||||
"qvs": "qlik",
|
||||
"qml": "qml",
|
||||
"qs": "qsharp",
|
||||
"r": "r",
|
||||
"rkt": "racket",
|
||||
"raku": "raku",
|
||||
"cshtml": "razor",
|
||||
"raml": "raml",
|
||||
"re": "reason",
|
||||
"red": "red",
|
||||
"res": "rescript",
|
||||
"rst": "restructuredtext",
|
||||
"rex": "rexx",
|
||||
"tag": "riot",
|
||||
"ripple": "ripple",
|
||||
"rmd": "rmd",
|
||||
"rnc": "rnc",
|
||||
"robot": "robot",
|
||||
"rb": "ruby",
|
||||
"rbw": "ruby",
|
||||
"rake": "ruby",
|
||||
"gemspec": "ruby",
|
||||
"ru": "ruby",
|
||||
"rjs": "ruby",
|
||||
"rxml": "ruby",
|
||||
"rsel": "ruby",
|
||||
"builder": "ruby",
|
||||
"jbuilder": "ruby",
|
||||
"rabl": "ruby",
|
||||
"prawn": "ruby",
|
||||
"thor": "ruby",
|
||||
"rs": "rust",
|
||||
"sl": "s-lang",
|
||||
"san": "san",
|
||||
"sas": "SAS",
|
||||
"sbt": "sbt",
|
||||
"scad": "scad",
|
||||
"scala": "scala",
|
||||
"sce": "scilab",
|
||||
"sdl": "sdl",
|
||||
"code-search": "search-result",
|
||||
"shader": "shaderlab",
|
||||
"sh": "shellscript",
|
||||
"bash": "shellscript",
|
||||
"zsh": "shellscript",
|
||||
"ksh": "shellscript",
|
||||
"fish": "shellscript",
|
||||
"slang": "slang",
|
||||
"ice": "slice",
|
||||
"slim": "slim",
|
||||
"slint": "slint",
|
||||
"sln": "sln",
|
||||
"ss": "silverstripe",
|
||||
"sn": "sino",
|
||||
"eskip": "eskip",
|
||||
"smk": "snakemake",
|
||||
"code-snippets": "snippets",
|
||||
"snort": "snort",
|
||||
"sol": "solidity",
|
||||
"rq": "sparql",
|
||||
"sqf": "sqf",
|
||||
"sql": "sql",
|
||||
"nut": "squirrel",
|
||||
"stan": "stan",
|
||||
"bazel": "starlark",
|
||||
"do": "stata",
|
||||
"stencil": "stencil",
|
||||
"html.stencil": "stencil-html",
|
||||
"st.css": "stylable",
|
||||
"styled": "source.css.styled",
|
||||
"styl": "stylus",
|
||||
"svelte": "svelte",
|
||||
"svg": "svg",
|
||||
"swagger": "Swagger",
|
||||
"swift": "swift",
|
||||
"swig": "swig",
|
||||
"link": "systemd-conf",
|
||||
"sv": "systemverilog",
|
||||
"tt": "t4",
|
||||
"teal": "teal",
|
||||
"templ": "templ",
|
||||
"tt3": "tt",
|
||||
"tera": "tera",
|
||||
"tf": "terraform",
|
||||
"sty": "tex",
|
||||
"textile": "textile",
|
||||
"json-tmlanguage": "json-tmlanguage",
|
||||
"yaml-tmlanguage": "yaml-tmlanguage",
|
||||
"toit": "toit",
|
||||
"toml": "toml",
|
||||
"toon": "toon",
|
||||
"ttcn3": "ttcn",
|
||||
"tuc": "tuc",
|
||||
"twig": "twig",
|
||||
"ts": "typescript",
|
||||
"mts": "typescript",
|
||||
"cts": "typescript",
|
||||
"tsx": "typescriptreact",
|
||||
"typoscript": "typoscript",
|
||||
"ua": "uiua",
|
||||
"u": "unison",
|
||||
"vb": "vb",
|
||||
"wsf": "vbscript",
|
||||
"vm": "velocity",
|
||||
"vto": "vento",
|
||||
"v": "verilog",
|
||||
"vhdl": "vhdl",
|
||||
"vim": "viml",
|
||||
"vitest-snap": "vitest-snapshot",
|
||||
"volt": "volt",
|
||||
"vroom": "vroom",
|
||||
"vue": "vue",
|
||||
"vue2": "vue",
|
||||
"vue3": "vue",
|
||||
"vues": "vue",
|
||||
"vuex": "vue",
|
||||
"vuerc": "vue",
|
||||
"vy": "vyper",
|
||||
"wai": "wai",
|
||||
"wasm": "wasm",
|
||||
"wat": "wasm",
|
||||
"wast": "wasm",
|
||||
"wsm": "wasm",
|
||||
"wast.js": "wasm",
|
||||
"wit": "wasm",
|
||||
"witx": "wasm",
|
||||
"wy": "wenyan",
|
||||
"wgsl": "wgsl",
|
||||
"wt": "wikitext",
|
||||
"wl": "wolfram",
|
||||
"wurst": "wurstlang",
|
||||
"xcompose": "xcompose",
|
||||
"xmake.lua": "xmake",
|
||||
"xml": "xml",
|
||||
"xquery": "xquery",
|
||||
"xsl": "xsl",
|
||||
"bison": "yacc",
|
||||
"yang": "yang",
|
||||
"zig": "zig",
|
||||
"zip": "zip"
|
||||
},
|
||||
"fileNameToLanguageId": {
|
||||
"browserslist": "browserslist",
|
||||
".browserslistrc": "browserslist",
|
||||
"caddyfile": "caddyfile",
|
||||
"cmakelists.txt": "cmake",
|
||||
"cmakecache.txt": "cmake-cache",
|
||||
"docker-compose.yml": "dockercompose",
|
||||
"docker-compose.yaml": "dockercompose",
|
||||
"compose.yaml": "dockercompose",
|
||||
"compose.yml": "dockercompose",
|
||||
"dockerfile": "dockerfile",
|
||||
"dockerfile.dev": "dockerfile",
|
||||
"dockerfile.prod": "dockerfile",
|
||||
"dockerfile.test": "dockerfile",
|
||||
".editorconfig": "editorconfig",
|
||||
"justfile": "just",
|
||||
"meson.build": "meson",
|
||||
".php-version": "php",
|
||||
"artisan": "php",
|
||||
"requirements.txt": "pip-requirements",
|
||||
"requirements-dev.txt": "pip-requirements",
|
||||
"requirements-test.txt": "pip-requirements",
|
||||
"requirements-prod.txt": "pip-requirements",
|
||||
"setup.py": "python",
|
||||
"setup.cfg": "python",
|
||||
".python-version": "python",
|
||||
"pipfile": "python",
|
||||
"pipfile.lock": "python",
|
||||
"robots.txt": "robots-txt",
|
||||
"config.ru": "ruby",
|
||||
".bashrc": "shellscript",
|
||||
".zshrc": "shellscript",
|
||||
".profile": "shellscript",
|
||||
".bash_profile": "shellscript",
|
||||
".bash_aliases": "shellscript",
|
||||
".zprofile": "shellscript",
|
||||
"tiltfile": "tiltfile",
|
||||
".vue-cli-rc": "vue",
|
||||
"yarn.lock": "yarnlock"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,52 +0,0 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { getVscodeIconUrlForEntry } from "./vscode-icons";
|
||||
|
||||
describe("getVscodeIconUrlForEntry", () => {
|
||||
it("uses exact filename matches from the vscode-icons manifest", () => {
|
||||
const darkUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "dark");
|
||||
const lightUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "light");
|
||||
|
||||
assert.isTrue(darkUrl.endsWith("/file_type_pnpm.svg"));
|
||||
assert.isTrue(lightUrl.endsWith("/file_type_light_pnpm.svg"));
|
||||
});
|
||||
|
||||
it("uses longest extension match for compound extensions", () => {
|
||||
const iconUrl = getVscodeIconUrlForEntry("tsconfig.tsbuildinfo", "file", "dark");
|
||||
const manifestStyleUrl = getVscodeIconUrlForEntry("buf.yaml", "file", "dark");
|
||||
assert.isTrue(iconUrl.endsWith("/file_type_tsbuildinfo.svg"));
|
||||
assert.isTrue(manifestStyleUrl.endsWith("/file_type_buf.svg"));
|
||||
});
|
||||
|
||||
it("uses folder mappings and light-aware filename mappings", () => {
|
||||
const folderUrl = getVscodeIconUrlForEntry("packages/src", "directory", "light");
|
||||
const fileUrl = getVscodeIconUrlForEntry("AGENTS.md", "file", "light");
|
||||
|
||||
assert.isTrue(folderUrl.endsWith("/folder_type_src.svg"));
|
||||
assert.isTrue(fileUrl.endsWith("/file_type_light_agents.svg"));
|
||||
});
|
||||
|
||||
it("falls back to language-based mappings for path-only cases", () => {
|
||||
const tsxUrl = getVscodeIconUrlForEntry("checkbox.tsx", "file", "light");
|
||||
const dockerfileUrl = getVscodeIconUrlForEntry("Dockerfile", "file", "dark");
|
||||
const shellUrl = getVscodeIconUrlForEntry("entrypoint.sh", "file", "dark");
|
||||
const htmlUrl = getVscodeIconUrlForEntry("index.html", "file", "dark");
|
||||
const cursorRulesUrl = getVscodeIconUrlForEntry("general.mdc", "file", "dark");
|
||||
const githubWorkflowUrl = getVscodeIconUrlForEntry(".github/workflows/ci.yml", "file", "light");
|
||||
|
||||
assert.isTrue(tsxUrl.endsWith("/file_type_reactts.svg"));
|
||||
assert.isTrue(dockerfileUrl.endsWith("/file_type_docker.svg"));
|
||||
assert.isTrue(shellUrl.endsWith("/file_type_shell.svg"));
|
||||
assert.isTrue(htmlUrl.endsWith("/file_type_html.svg"));
|
||||
assert.isTrue(cursorRulesUrl.endsWith("/file_type_markdown.svg"));
|
||||
assert.isTrue(githubWorkflowUrl.endsWith("/file_type_light_yaml.svg"));
|
||||
});
|
||||
|
||||
it("falls back to defaults when there is no match", () => {
|
||||
const fileUrl = getVscodeIconUrlForEntry("foo.unknown-ext", "file", "dark");
|
||||
const folderUrl = getVscodeIconUrlForEntry("totally-unknown-folder", "directory", "dark");
|
||||
|
||||
assert.isTrue(fileUrl.endsWith("/default_file.svg"));
|
||||
assert.isTrue(folderUrl.endsWith("/default_folder.svg"));
|
||||
});
|
||||
});
|
||||
@@ -1,211 +0,0 @@
|
||||
import vscodeIconsManifest from "./vscode-icons-manifest.json";
|
||||
import languageAssociationsData from "./vscode-icons-language-associations.json";
|
||||
|
||||
const VSCODE_ICONS_VERSION = "v12.17.0";
|
||||
const VSCODE_ICONS_BASE_URL = `https://cdn.jsdelivr.net/gh/vscode-icons/vscode-icons@${VSCODE_ICONS_VERSION}/icons`;
|
||||
|
||||
interface IconDefinition {
|
||||
iconPath: string;
|
||||
}
|
||||
|
||||
interface IconLookupSection {
|
||||
file?: string;
|
||||
folder?: string;
|
||||
fileNames: Record<string, string>;
|
||||
fileExtensions: Record<string, string>;
|
||||
folderNames: Record<string, string>;
|
||||
languageIds?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface VscodeIconsManifest extends IconLookupSection {
|
||||
iconDefinitions: Record<string, IconDefinition>;
|
||||
light: IconLookupSection;
|
||||
}
|
||||
|
||||
interface LanguageAssociations {
|
||||
version: string;
|
||||
extensionToLanguageId: Record<string, string>;
|
||||
fileNameToLanguageId: Record<string, string>;
|
||||
}
|
||||
|
||||
const manifest = vscodeIconsManifest as VscodeIconsManifest;
|
||||
const languageAssociations = languageAssociationsData as LanguageAssociations;
|
||||
const iconDefinitions = manifest.iconDefinitions;
|
||||
|
||||
const darkFileNames = toLowercaseLookup(manifest.fileNames);
|
||||
const lightFileNames = toLowercaseLookup(manifest.light.fileNames);
|
||||
const darkFileExtensions = toLowercaseLookup(manifest.fileExtensions);
|
||||
const lightFileExtensions = toLowercaseLookup(manifest.light.fileExtensions);
|
||||
const darkFolderNames = toLowercaseLookup(manifest.folderNames);
|
||||
const lightFolderNames = toLowercaseLookup(manifest.light.folderNames);
|
||||
const darkLanguageIds = toLowercaseLookup(manifest.languageIds ?? {});
|
||||
const lightLanguageIds = toLowercaseLookup(manifest.light.languageIds ?? {});
|
||||
const languageIdByExtension = toLowercaseLookup(languageAssociations.extensionToLanguageId);
|
||||
const languageIdByFileName = toLowercaseLookup(languageAssociations.fileNameToLanguageId);
|
||||
const localLanguageIdByExtensionOverrides = {
|
||||
// Cursor rules files (*.mdc) are commonly treated as markdown in VSCode/Cursor.
|
||||
mdc: "markdown",
|
||||
// Upstream languages.ts currently maps .html to django-html before html.
|
||||
// Prefer the base HTML icon for standalone HTML files.
|
||||
html: "html",
|
||||
// Upstream languages.ts maps yml/yaml to specialized language ids that can produce
|
||||
// non-generic YAML icons (for example cloudfoundry/esphome). Prefer the base YAML icon
|
||||
// unless a more specific basename/extension match (e.g. azure-pipelines.yml) is found.
|
||||
yml: "yaml",
|
||||
yaml: "yaml",
|
||||
} as const;
|
||||
|
||||
const defaultDarkFileIconDefinition = manifest.file ?? "_file";
|
||||
const defaultLightFileIconDefinition = manifest.light.file ?? defaultDarkFileIconDefinition;
|
||||
const defaultDarkFolderIconDefinition = manifest.folder ?? "_folder";
|
||||
const defaultLightFolderIconDefinition = manifest.light.folder ?? defaultDarkFolderIconDefinition;
|
||||
|
||||
function toLowercaseLookup(source: Record<string, string>): Record<string, string> {
|
||||
const entries = Object.entries(source);
|
||||
const lookup: Record<string, string> = {};
|
||||
for (const [key, value] of entries) {
|
||||
lookup[key.toLowerCase()] = value;
|
||||
}
|
||||
return lookup;
|
||||
}
|
||||
|
||||
const extensionByLanguageId: Record<string, string> = {};
|
||||
for (const [extension, languageId] of Object.entries(languageAssociations.extensionToLanguageId)) {
|
||||
const key = languageId.toLowerCase();
|
||||
if (!(key in extensionByLanguageId)) {
|
||||
extensionByLanguageId[key] = extension.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesizes a file name whose icon resolution best represents a markdown
|
||||
* fence language id — handles both extension-style ids ("ts", "py") and
|
||||
* language ids ("typescript", "python", "shellscript").
|
||||
*/
|
||||
export function syntheticFileNameForLanguageId(languageId: string): string {
|
||||
const normalized = languageId.toLowerCase();
|
||||
return `file.${extensionByLanguageId[normalized] ?? normalized}`;
|
||||
}
|
||||
|
||||
export function basenameOfPath(pathValue: string): string {
|
||||
const slashIndex = pathValue.lastIndexOf("/");
|
||||
if (slashIndex === -1) return pathValue;
|
||||
return pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
export function inferEntryKindFromPath(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
}
|
||||
return "directory";
|
||||
}
|
||||
|
||||
function extensionCandidates(fileName: string): string[] {
|
||||
const candidates = new Set<string>();
|
||||
if (fileName.includes(".")) {
|
||||
candidates.add(fileName);
|
||||
}
|
||||
let dotIndex = fileName.indexOf(".");
|
||||
while (dotIndex !== -1 && dotIndex < fileName.length - 1) {
|
||||
const candidate = fileName.slice(dotIndex + 1);
|
||||
if (candidate.length > 0) {
|
||||
candidates.add(candidate);
|
||||
}
|
||||
dotIndex = fileName.indexOf(".", dotIndex + 1);
|
||||
}
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function resolveLanguageFallbackDefinition(
|
||||
pathValue: string,
|
||||
theme: "light" | "dark",
|
||||
): string | null {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const languageIds = theme === "light" ? lightLanguageIds : darkLanguageIds;
|
||||
|
||||
const fromBasenameLanguage = languageIdByFileName[basename];
|
||||
if (fromBasenameLanguage) {
|
||||
return languageIds[fromBasenameLanguage] ?? darkLanguageIds[fromBasenameLanguage] ?? null;
|
||||
}
|
||||
|
||||
for (const candidate of extensionCandidates(basename)) {
|
||||
const languageId =
|
||||
localLanguageIdByExtensionOverrides[
|
||||
candidate as keyof typeof localLanguageIdByExtensionOverrides
|
||||
] ?? languageIdByExtension[candidate];
|
||||
if (!languageId) continue;
|
||||
return languageIds[languageId] ?? darkLanguageIds[languageId] ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function iconFilenameForDefinitionKey(definitionKey: string | undefined): string | null {
|
||||
if (!definitionKey) return null;
|
||||
const iconPath = iconDefinitions[definitionKey]?.iconPath;
|
||||
if (!iconPath) return null;
|
||||
const slashIndex = iconPath.lastIndexOf("/");
|
||||
if (slashIndex === -1) {
|
||||
return iconPath;
|
||||
}
|
||||
return iconPath.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
function resolveFileDefinition(pathValue: string, theme: "light" | "dark"): string {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const fileNames = theme === "light" ? lightFileNames : darkFileNames;
|
||||
const fileExtensions = theme === "light" ? lightFileExtensions : darkFileExtensions;
|
||||
|
||||
const fromFileName = fileNames[basename] ?? darkFileNames[basename];
|
||||
if (fromFileName) return fromFileName;
|
||||
|
||||
for (const candidate of extensionCandidates(basename)) {
|
||||
const fromExtension = fileExtensions[candidate] ?? darkFileExtensions[candidate];
|
||||
if (fromExtension) return fromExtension;
|
||||
}
|
||||
|
||||
const fromLanguage = resolveLanguageFallbackDefinition(pathValue, theme);
|
||||
if (fromLanguage) return fromLanguage;
|
||||
|
||||
return theme === "light" ? defaultLightFileIconDefinition : defaultDarkFileIconDefinition;
|
||||
}
|
||||
|
||||
function resolveFolderDefinition(pathValue: string, theme: "light" | "dark"): string {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const folderNames = theme === "light" ? lightFolderNames : darkFolderNames;
|
||||
return (
|
||||
folderNames[basename] ??
|
||||
darkFolderNames[basename] ??
|
||||
(theme === "light" ? defaultLightFolderIconDefinition : defaultDarkFolderIconDefinition)
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the file name resolves to a real icon rather than the generic default. */
|
||||
export function hasSpecificVscodeIconForFileName(
|
||||
fileName: string,
|
||||
theme: "light" | "dark",
|
||||
): boolean {
|
||||
const definition = resolveFileDefinition(fileName, theme);
|
||||
return (
|
||||
definition !== defaultDarkFileIconDefinition && definition !== defaultLightFileIconDefinition
|
||||
);
|
||||
}
|
||||
|
||||
export function getVscodeIconUrlForEntry(
|
||||
pathValue: string,
|
||||
kind: "file" | "directory",
|
||||
theme: "light" | "dark",
|
||||
): string {
|
||||
const definitionKey =
|
||||
kind === "directory"
|
||||
? resolveFolderDefinition(pathValue, theme)
|
||||
: resolveFileDefinition(pathValue, theme);
|
||||
const iconFilename =
|
||||
iconFilenameForDefinitionKey(definitionKey) ??
|
||||
(kind === "directory" ? "default_folder.svg" : "default_file.svg");
|
||||
return `${VSCODE_ICONS_BASE_URL}/${iconFilename}`;
|
||||
}
|
||||
@@ -121,6 +121,7 @@ export default defineConfig(() => {
|
||||
optimizeDeps: {
|
||||
include: [
|
||||
"@pierre/diffs",
|
||||
"@pierre/diffs/editor",
|
||||
"@pierre/diffs/react",
|
||||
"@pierre/diffs/worker/worker.js",
|
||||
"effect/Array",
|
||||
|
||||
@@ -35,7 +35,6 @@
|
||||
"dist:desktop:win:x64": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64",
|
||||
"release:smoke": "node scripts/release-smoke.ts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .vite-plus apps/*/.vite-plus packages/*/.vite-plus",
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs",
|
||||
"sync:repos": "node scripts/sync-reference-repos.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -96,6 +96,8 @@ export interface WsRpcClient {
|
||||
readonly subscribePorts: RpcStreamMethod<typeof WS_METHODS.subscribeDiscoveredLocalServers>;
|
||||
};
|
||||
readonly projects: {
|
||||
readonly listEntries: RpcUnaryMethod<typeof WS_METHODS.projectsListEntries>;
|
||||
readonly readFile: RpcUnaryMethod<typeof WS_METHODS.projectsReadFile>;
|
||||
readonly searchEntries: RpcUnaryMethod<typeof WS_METHODS.projectsSearchEntries>;
|
||||
readonly writeFile: RpcUnaryMethod<typeof WS_METHODS.projectsWriteFile>;
|
||||
};
|
||||
@@ -267,6 +269,10 @@ export function createWsRpcClient(
|
||||
),
|
||||
},
|
||||
projects: {
|
||||
listEntries: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.projectsListEntries](input)),
|
||||
readFile: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.projectsReadFile](input)),
|
||||
searchEntries: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.projectsSearchEntries](input)),
|
||||
writeFile: (input) =>
|
||||
|
||||
@@ -22,6 +22,10 @@ import type { ReviewDiffPreviewInput, ReviewDiffPreviewResult } from "./review.t
|
||||
import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts";
|
||||
import type { AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts";
|
||||
import type {
|
||||
ProjectListEntriesInput,
|
||||
ProjectListEntriesResult,
|
||||
ProjectReadFileInput,
|
||||
ProjectReadFileResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
ProjectWriteFileInput,
|
||||
@@ -1110,6 +1114,8 @@ export interface EnvironmentApi {
|
||||
) => () => void;
|
||||
};
|
||||
projects: {
|
||||
listEntries: (input: ProjectListEntriesInput) => Promise<ProjectListEntriesResult>;
|
||||
readFile: (input: ProjectReadFileInput) => Promise<ProjectReadFileResult>;
|
||||
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
|
||||
writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;
|
||||
};
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
|
||||
const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
|
||||
const PROJECT_WRITE_FILE_PATH_MAX_LENGTH = 512;
|
||||
const PROJECT_READ_FILE_PATH_MAX_LENGTH = 512;
|
||||
|
||||
export const ProjectSearchEntriesInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
@@ -26,6 +27,17 @@ export const ProjectSearchEntriesResult = Schema.Struct({
|
||||
});
|
||||
export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;
|
||||
|
||||
export const ProjectListEntriesInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProjectListEntriesInput = typeof ProjectListEntriesInput.Type;
|
||||
|
||||
export const ProjectListEntriesResult = Schema.Struct({
|
||||
entries: Schema.Array(ProjectEntry),
|
||||
truncated: Schema.Boolean,
|
||||
});
|
||||
export type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;
|
||||
|
||||
export class ProjectSearchEntriesError extends Schema.TaggedErrorClass<ProjectSearchEntriesError>()(
|
||||
"ProjectSearchEntriesError",
|
||||
{
|
||||
@@ -34,6 +46,36 @@ export class ProjectSearchEntriesError extends Schema.TaggedErrorClass<ProjectSe
|
||||
},
|
||||
) {}
|
||||
|
||||
export class ProjectListEntriesError extends Schema.TaggedErrorClass<ProjectListEntriesError>()(
|
||||
"ProjectListEntriesError",
|
||||
{
|
||||
message: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export const ProjectReadFileInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_READ_FILE_PATH_MAX_LENGTH)),
|
||||
});
|
||||
export type ProjectReadFileInput = typeof ProjectReadFileInput.Type;
|
||||
|
||||
export const ProjectReadFileResult = Schema.Struct({
|
||||
relativePath: TrimmedNonEmptyString,
|
||||
contents: Schema.String,
|
||||
byteLength: NonNegativeInt,
|
||||
truncated: Schema.Boolean,
|
||||
});
|
||||
export type ProjectReadFileResult = typeof ProjectReadFileResult.Type;
|
||||
|
||||
export class ProjectReadFileError extends Schema.TaggedErrorClass<ProjectReadFileError>()(
|
||||
"ProjectReadFileError",
|
||||
{
|
||||
message: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export const ProjectWriteFileInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)),
|
||||
|
||||
@@ -65,6 +65,12 @@ import {
|
||||
RelayClientStatusSchema,
|
||||
} from "./relayClient.ts";
|
||||
import {
|
||||
ProjectListEntriesError,
|
||||
ProjectListEntriesInput,
|
||||
ProjectListEntriesResult,
|
||||
ProjectReadFileError,
|
||||
ProjectReadFileInput,
|
||||
ProjectReadFileResult,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
@@ -141,6 +147,8 @@ export const WS_METHODS = {
|
||||
projectsList: "projects.list",
|
||||
projectsAdd: "projects.add",
|
||||
projectsRemove: "projects.remove",
|
||||
projectsListEntries: "projects.listEntries",
|
||||
projectsReadFile: "projects.readFile",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
projectsWriteFile: "projects.writeFile",
|
||||
|
||||
@@ -350,6 +358,18 @@ export const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntr
|
||||
error: Schema.Union([ProjectSearchEntriesError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsProjectsListEntriesRpc = Rpc.make(WS_METHODS.projectsListEntries, {
|
||||
payload: ProjectListEntriesInput,
|
||||
success: ProjectListEntriesResult,
|
||||
error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsProjectsReadFileRpc = Rpc.make(WS_METHODS.projectsReadFile, {
|
||||
payload: ProjectReadFileInput,
|
||||
success: ProjectReadFileResult,
|
||||
error: Schema.Union([ProjectReadFileError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {
|
||||
payload: ProjectWriteFileInput,
|
||||
success: ProjectWriteFileResult,
|
||||
@@ -676,6 +696,8 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
WsSourceControlCloneRepositoryRpc,
|
||||
WsSourceControlPublishRepositoryRpc,
|
||||
WsProjectsListEntriesRpc,
|
||||
WsProjectsReadFileRpc,
|
||||
WsProjectsSearchEntriesRpc,
|
||||
WsProjectsWriteFileRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
diff --git a/package.json b/package.json
|
||||
index c0e762b13b56247b256520754e439cbc16bb797d..d298b87c175ec891d1b50f681c9031f4b1929e67 100644
|
||||
index b18c94f3f7b40bdb15084ab7cabcb19dd29c61f7..ab96ac589d368e806ef45480283d6e0fa199117f 100644
|
||||
--- a/package.json
|
||||
+++ b/package.json
|
||||
@@ -51,6 +51,18 @@
|
||||
@@ -20,4 +20,4 @@ index c0e762b13b56247b256520754e439cbc16bb797d..d298b87c175ec891d1b50f681c9031f4
|
||||
+ "import": "./dist/utils/parsePatchFiles.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"publishConfig": {
|
||||
Generated
+89
-17
@@ -19,8 +19,8 @@ catalogs:
|
||||
specifier: 1.8.0
|
||||
version: 1.8.0
|
||||
'@pierre/diffs':
|
||||
specifier: 1.1.20
|
||||
version: 1.1.20
|
||||
specifier: 1.3.0-beta.4
|
||||
version: 1.3.0-beta.4
|
||||
'@typescript/native-preview':
|
||||
specifier: 7.0.0-dev.20260604.1
|
||||
version: 7.0.0-dev.20260604.1
|
||||
@@ -66,9 +66,9 @@ patchedDependencies:
|
||||
'@expo/[email protected]':
|
||||
hash: 8cb08b5bb7051ed9d2dbe46a2c293c5a1e17f1bd6ddf30de27909e18c921ff46
|
||||
path: patches/@expo%[email protected]
|
||||
'@pierre/diffs@1.1.20':
|
||||
hash: e4e35ba95100de3708f900e0d9ea62bca732b1e4486024b5055f48cd128dd9e0
|
||||
path: patches/@pierre%2Fdiffs@1.1.20.patch
|
||||
'@pierre/diffs@1.3.0-beta.4':
|
||||
hash: f5d41705ce94bbafc731d92e9cb1671db710df046dd135cb894e3e3e9164a75b
|
||||
path: patches/@pierre%2Fdiffs@1.3.0-beta.4.patch
|
||||
[email protected]:
|
||||
hash: 883249d8efbb462e928e21fefef96027b66aec50751178cafdce45f08eee3754
|
||||
path: patches/[email protected]
|
||||
@@ -198,7 +198,7 @@ importers:
|
||||
version: 1.8.0
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.1.20(patch_hash=e4e35ba95100de3708f900e0d9ea62bca732b1e4486024b5055f48cd128dd9e0)([email protected]([email protected]))([email protected])
|
||||
version: 1.3.0-beta.4(patch_hash=f5d41705ce94bbafc731d92e9cb1671db710df046dd135cb894e3e3e9164a75b)(@shikijs/[email protected].0)([email protected]([email protected]))([email protected])
|
||||
'@react-native-menu/menu':
|
||||
specifier: ^2.0.0
|
||||
version: 2.0.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
|
||||
@@ -400,7 +400,7 @@ importers:
|
||||
version: 1.15.13
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.1.20(patch_hash=e4e35ba95100de3708f900e0d9ea62bca732b1e4486024b5055f48cd128dd9e0)([email protected]([email protected]))([email protected])
|
||||
version: 1.3.0-beta.4(patch_hash=f5d41705ce94bbafc731d92e9cb1671db710df046dd135cb894e3e3e9164a75b)(@shikijs/[email protected].0)([email protected]([email protected]))([email protected])
|
||||
effect:
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78(patch_hash=883249d8efbb462e928e21fefef96027b66aec50751178cafdce45f08eee3754)
|
||||
@@ -482,7 +482,10 @@ importers:
|
||||
version: 0.41.0([email protected]([email protected]))([email protected])([email protected])
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.1.20(patch_hash=e4e35ba95100de3708f900e0d9ea62bca732b1e4486024b5055f48cd128dd9e0)([email protected]([email protected]))([email protected])
|
||||
version: 1.3.0-beta.4(patch_hash=f5d41705ce94bbafc731d92e9cb1671db710df046dd135cb894e3e3e9164a75b)(@shikijs/[email protected].0)([email protected]([email protected]))([email protected])
|
||||
'@pierre/trees':
|
||||
specifier: 1.0.0-beta.4
|
||||
version: 1.0.0-beta.4([email protected]([email protected]))([email protected])
|
||||
'@t3tools/client-runtime':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/client-runtime
|
||||
@@ -3203,16 +3206,42 @@ packages:
|
||||
resolution: {integrity: sha512-titLmukUt/h8ho7Svlf0xSBjoy2ccZKrXjpXpZCj+v6V4CJccC2KyP45BLSCMx8YIpifMyiDyUptM4+5sruKbQ==}
|
||||
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
|
||||
|
||||
'@pierre/diffs@1.1.20':
|
||||
resolution: {integrity: sha512-lLi+3sLCm3QDd5/aLO9pw+WbF6UzhrkWm2oTZ5WZJTGemOyUNRJ4DDhcEKmVusu4C4bXx9Nssh6fF+wQcapb5w==}
|
||||
'@pierre/diffs@1.3.0-beta.4':
|
||||
resolution: {integrity: sha512-poFcsvhcQt9lH/InzAPaGs47WYHMidnFCjuYGNU41HiVLJP4mkIQDSdvcnPIkBuh/cYbPOQg/YE3T1kSpr01GA==}
|
||||
peerDependencies:
|
||||
react: ^18.3.1 || ^19.0.0
|
||||
react-dom: ^18.3.1 || ^19.0.0
|
||||
|
||||
'@pierre/theme@0.0.28':
|
||||
resolution: {integrity: sha512-1j/H/fECBuc9dEvntdWI+l435HZapw+RCJTlqCA6BboQ5TjlnE005j/ROWutXIs8aq5OAc82JI2Kwk4A1WWBgw==}
|
||||
'@pierre/theme@1.0.3':
|
||||
resolution: {integrity: sha512-sWHv11TMoqKxKDgTIk5VbhQjdPhs8DCcBxbjh3mRlS3YOM/OcrWoGX6MM8eBGn9cUu3M46Py0JnxsG2nJaFTuA==}
|
||||
engines: {vscode: ^1.0.0}
|
||||
|
||||
'@pierre/[email protected]':
|
||||
resolution: {integrity: sha512-1thlEtJbqdyLzc1ZS2KQa1q7FzDGHT4dTEdKHoyQjOMeWWOmbVG5/ndEfOKfAb5Fzkz8cNJrOjFLiZoDH/A03A==}
|
||||
peerDependencies:
|
||||
'@pierre/theme': ^1.0.0
|
||||
'@shikijs/themes': ^3.0.0 || ^4.0.0
|
||||
react: ^18.3.1 || ^19.0.0
|
||||
react-dom: ^18.3.1 || ^19.0.0
|
||||
shiki: ^3.0.0 || ^4.0.0
|
||||
peerDependenciesMeta:
|
||||
'@pierre/theme':
|
||||
optional: true
|
||||
'@shikijs/themes':
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
react-dom:
|
||||
optional: true
|
||||
shiki:
|
||||
optional: true
|
||||
|
||||
'@pierre/[email protected]':
|
||||
resolution: {integrity: sha512-OfT1yk9ne8Te5+GB5zUY8yqE6B8BqjBHQJleH4lu8ltwNpoocZl4vXt1AzlEExpxI/pp+AFX5QG+lR3JjtTEag==}
|
||||
peerDependencies:
|
||||
react: ^18.3.1 || ^19.0.0
|
||||
react-dom: ^18.3.1 || ^19.0.0
|
||||
|
||||
'@polka/[email protected]':
|
||||
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
|
||||
|
||||
@@ -8078,6 +8107,14 @@ packages:
|
||||
engines: {node: '>=14.0.0'}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-O6MHzYNIKYaiSX3bOw0gGZfEbOmlIDtDfWwN1JJdc/T3ihzRT6tGGSEWE088dWrEDGa1u7101q+6fzQnO9XCPA==}
|
||||
peerDependencies:
|
||||
preact: '>=10 || >= 11.0.0-0'
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==}
|
||||
engines: {node: '>=14'}
|
||||
@@ -12439,9 +12476,10 @@ snapshots:
|
||||
|
||||
'@oxlint/[email protected]': {}
|
||||
|
||||
'@pierre/diffs@1.1.20(patch_hash=e4e35ba95100de3708f900e0d9ea62bca732b1e4486024b5055f48cd128dd9e0)([email protected]([email protected]))([email protected])':
|
||||
'@pierre/diffs@1.3.0-beta.4(patch_hash=f5d41705ce94bbafc731d92e9cb1671db710df046dd135cb894e3e3e9164a75b)(@shikijs/[email protected].0)([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@pierre/theme': 0.0.28
|
||||
'@pierre/theme': 1.0.3
|
||||
'@pierre/theming': 0.0.1(@pierre/[email protected])(@shikijs/[email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
'@shikijs/transformers': 3.23.0
|
||||
diff: 8.0.3
|
||||
hast-util-to-html: 9.0.5
|
||||
@@ -12449,10 +12487,13 @@ snapshots:
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3([email protected])
|
||||
shiki: 3.23.0
|
||||
transitivePeerDependencies:
|
||||
- '@shikijs/themes'
|
||||
|
||||
'@pierre/diffs@1.1.20(patch_hash=e4e35ba95100de3708f900e0d9ea62bca732b1e4486024b5055f48cd128dd9e0)([email protected]([email protected]))([email protected])':
|
||||
'@pierre/diffs@1.3.0-beta.4(patch_hash=f5d41705ce94bbafc731d92e9cb1671db710df046dd135cb894e3e3e9164a75b)(@shikijs/[email protected].0)([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@pierre/theme': 0.0.28
|
||||
'@pierre/theme': 1.0.3
|
||||
'@pierre/theming': 0.0.1(@pierre/[email protected])(@shikijs/[email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
'@shikijs/transformers': 3.23.0
|
||||
diff: 8.0.3
|
||||
hast-util-to-html: 9.0.5
|
||||
@@ -12460,8 +12501,33 @@ snapshots:
|
||||
react: 19.2.6
|
||||
react-dom: 19.2.6([email protected])
|
||||
shiki: 3.23.0
|
||||
transitivePeerDependencies:
|
||||
- '@shikijs/themes'
|
||||
|
||||
'@pierre/theme@0.0.28': {}
|
||||
'@pierre/theme@1.0.3': {}
|
||||
|
||||
'@pierre/[email protected](@pierre/[email protected])(@shikijs/[email protected])([email protected]([email protected]))([email protected])([email protected])':
|
||||
optionalDependencies:
|
||||
'@pierre/theme': 1.0.3
|
||||
'@shikijs/themes': 3.23.0
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3([email protected])
|
||||
shiki: 3.23.0
|
||||
|
||||
'@pierre/[email protected](@pierre/[email protected])(@shikijs/[email protected])([email protected]([email protected]))([email protected])([email protected])':
|
||||
optionalDependencies:
|
||||
'@pierre/theme': 1.0.3
|
||||
'@shikijs/themes': 4.1.0
|
||||
react: 19.2.6
|
||||
react-dom: 19.2.6([email protected])
|
||||
shiki: 3.23.0
|
||||
|
||||
'@pierre/[email protected]([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
preact: 11.0.0-beta.0
|
||||
preact-render-to-string: 6.6.5([email protected])
|
||||
react: 19.2.6
|
||||
react-dom: 19.2.6([email protected])
|
||||
|
||||
'@polka/[email protected]': {}
|
||||
|
||||
@@ -17748,6 +17814,12 @@ snapshots:
|
||||
commander: 9.5.0
|
||||
optional: true
|
||||
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
preact: 11.0.0-beta.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
|
||||
+4
-2
@@ -28,7 +28,7 @@ catalog:
|
||||
"@effect/tsgo": 0.13.2
|
||||
"@noble/curves": 1.9.1
|
||||
"@noble/hashes": 1.8.0
|
||||
"@pierre/diffs": 1.1.20
|
||||
"@pierre/diffs": 1.3.0-beta.4
|
||||
"@vitest/runner": 4.1.8
|
||||
"@types/node": 24.12.4
|
||||
"@typescript/native-preview": 7.0.0-dev.20260604.1
|
||||
@@ -83,8 +83,10 @@ packageExtensions:
|
||||
dependencies:
|
||||
vite: "catalog:"
|
||||
patchedDependencies:
|
||||
# Keep non-browser consumers off the root entrypoint, which eagerly imports
|
||||
# DOM-dependent renderers. These utility/type subpaths are safe for mobile.
|
||||
"@pierre/[email protected]": patches/@pierre%[email protected]
|
||||
"@effect/[email protected]": patches/@[email protected]
|
||||
"@expo/[email protected]": patches/@expo%[email protected]
|
||||
"@pierre/[email protected]": patches/@pierre%[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
@@ -1,153 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const VERSION = process.argv[2] ?? "12.17.0";
|
||||
const VERSION_TAG = `v${VERSION}`;
|
||||
const VSIX_URL = `https://open-vsx.org/api/vscode-icons-team/vscode-icons/${VERSION}/file/vscode-icons-team.vscode-icons-${VERSION}.vsix`;
|
||||
const LANGUAGES_URL = `https://raw.githubusercontent.com/vscode-icons/vscode-icons/${VERSION_TAG}/src/iconsManifest/languages.ts`;
|
||||
|
||||
const REPO_ROOT = process.cwd();
|
||||
const MANIFEST_PATH = path.join(REPO_ROOT, "apps/web/src/vscode-icons-manifest.json");
|
||||
const ASSOCIATIONS_PATH = path.join(
|
||||
REPO_ROOT,
|
||||
"apps/web/src/vscode-icons-language-associations.json",
|
||||
);
|
||||
|
||||
function normalizeExtension(value) {
|
||||
return value.trim().toLowerCase().replace(/^\./, "");
|
||||
}
|
||||
|
||||
function normalizeFileName(value) {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function putIfAbsent(target, key, value) {
|
||||
if (!(key in target)) {
|
||||
target[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadVsix(tmpDir) {
|
||||
const vsixPath = path.join(tmpDir, `vscode-icons-${VERSION}.vsix`);
|
||||
const response = await fetch(VSIX_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download VSIX: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
await fs.writeFile(vsixPath, bytes);
|
||||
return vsixPath;
|
||||
}
|
||||
|
||||
async function extractManifestFromVsix(vsixPath) {
|
||||
const { stdout } = await execFileAsync("unzip", [
|
||||
"-p",
|
||||
vsixPath,
|
||||
"extension/dist/src/vsicons-icon-theme.json",
|
||||
]);
|
||||
if (!stdout || stdout.trim().length === 0) {
|
||||
throw new Error("Could not extract vsicons-icon-theme.json from VSIX");
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
|
||||
async function loadLanguagesCollection() {
|
||||
const response = await fetch(LANGUAGES_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch languages.ts: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const rawSource = await response.text();
|
||||
const source = rawSource
|
||||
.replace(/^import[^;]+;\s*/gm, "")
|
||||
.replace(/export const languages(?:\s*:\s*[^=]+)?\s*=/, "const languages =")
|
||||
.replace(/\}\s*satisfies\s*Record<[^;]+>;/, "};");
|
||||
|
||||
const context = {};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(`${source}\n;globalThis.__languages = languages;`, context);
|
||||
const languages = context.__languages;
|
||||
if (!languages || typeof languages !== "object") {
|
||||
throw new Error("Failed to parse languages.ts into a collection");
|
||||
}
|
||||
return languages;
|
||||
}
|
||||
|
||||
function buildLanguageAssociations(manifest, languages) {
|
||||
const availableLanguageIds = new Set(Object.keys(manifest.languageIds ?? {}));
|
||||
const extensionToLanguageId = {};
|
||||
const fileNameToLanguageId = {};
|
||||
|
||||
for (const entry of Object.values(languages)) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const idsRaw = entry.ids;
|
||||
const ids = Array.isArray(idsRaw) ? idsRaw : [idsRaw];
|
||||
const knownExtensions = Array.isArray(entry.knownExtensions) ? entry.knownExtensions : [];
|
||||
const knownFilenames = Array.isArray(entry.knownFilenames) ? entry.knownFilenames : [];
|
||||
|
||||
for (const idValue of ids) {
|
||||
if (typeof idValue !== "string") continue;
|
||||
const languageId = idValue.trim();
|
||||
if (languageId.length === 0) continue;
|
||||
if (!availableLanguageIds.has(languageId)) continue;
|
||||
|
||||
for (const extensionValue of knownExtensions) {
|
||||
if (typeof extensionValue !== "string") continue;
|
||||
const extension = normalizeExtension(extensionValue);
|
||||
if (extension.length === 0) continue;
|
||||
putIfAbsent(extensionToLanguageId, extension, languageId);
|
||||
}
|
||||
|
||||
for (const fileNameValue of knownFilenames) {
|
||||
if (typeof fileNameValue !== "string") continue;
|
||||
const fileName = normalizeFileName(fileNameValue);
|
||||
if (fileName.length === 0) continue;
|
||||
putIfAbsent(fileNameToLanguageId, fileName, languageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: VERSION,
|
||||
source: LANGUAGES_URL,
|
||||
generatedAt: new Date().toISOString(),
|
||||
extensionToLanguageId,
|
||||
fileNameToLanguageId,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "t3-vscode-icons-sync-"));
|
||||
try {
|
||||
const vsixPath = await downloadVsix(tmpDir);
|
||||
const manifest = await extractManifestFromVsix(vsixPath);
|
||||
const languages = await loadLanguagesCollection();
|
||||
const associations = buildLanguageAssociations(manifest, languages);
|
||||
|
||||
await fs.writeFile(MANIFEST_PATH, `${JSON.stringify(manifest)}\n`, "utf8");
|
||||
await fs.writeFile(ASSOCIATIONS_PATH, `${JSON.stringify(associations)}\n`, "utf8");
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
`Synced vscode-icons ${VERSION}`,
|
||||
`manifest: ${MANIFEST_PATH}`,
|
||||
`language associations: ${ASSOCIATIONS_PATH}`,
|
||||
`extension mappings: ${Object.keys(associations.extensionToLanguageId).length}`,
|
||||
`filename mappings: ${Object.keys(associations.fileNameToLanguageId).length}`,
|
||||
].join("\n") + "\n",
|
||||
);
|
||||
} finally {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user