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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions packages/api/src/namespaces.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,27 @@ export interface FileSystem {
/** Watch a file or directory for changes. Returns a {@link Disposable}
* that stops the watch. */
watch(uri: Uri, listener: Listener<FileChangeEvent>): Disposable;
/**
* Delete the file or (empty or non-empty) directory at `uri` (Task 3.3,
* Req 11.2 — the explorer's delete command). Rejects on failure (does
* not exist, permission denied) — same never-silently-swallows contract
* as {@link read}/{@link write}; the caller (the explorer built-in)
* surfaces the rejection via `window.showMessage(..., "error")`.
*/
delete(uri: Uri): Promise<void>;
/**
* Rename/move the file or directory at `oldUri` to `newUri` (Task 3.3,
* Req 11.2 — the explorer's rename command). Rejects on failure
* (`oldUri` missing, `newUri` already exists, permission denied) —
* same contract as {@link delete}.
*/
rename(oldUri: Uri, newUri: Uri): Promise<void>;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
/**
* Create a new, empty directory at `uri` (Task 3.3, Req 11.2 — the
* explorer's "New Folder" command). Rejects on failure (already exists,
* parent missing, permission denied) — same contract as {@link delete}.
*/
mkdir(uri: Uri): Promise<void>;
}

/**
Expand Down
25 changes: 20 additions & 5 deletions packages/builtin/command-palette/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,9 +48,14 @@
* `api.workspace.fs.readdir` (Task 3.2's plan: "verify what
* `api.workspace.fs` actually exposes" — `@tecode/api`'s `FileSystem.
* readdir(uri): Promise<DirEntry[]>`, `namespaces.ts`) rooted at
* `api.workspace.rootUri`, with `createDefaultIgnorer()`'s interim stub
* (`../shared/ignore.ts`, superseded by Task 3.3's real explorer ignore
* logic) and a `maxResults` cap (`QUICK_OPEN_MAX_RESULTS`) that stops the
* `api.workspace.rootUri`, with `../shared/ignore.ts`'s REAL, Task
* 3.3-built `IgnoreChecker` (`createIgnoreChecker({ readFile:
* api.workspace.fs.read, gitRunner: createBunGitRunner() })` — batched
* `git check-ignore` when `git` is available, the root `.gitignore`'s glob
* matcher otherwise; this is the exact "one ignore-aware walk `ctrl+p` and
* the explorer both use" Task 3.3's issue calls for, replacing Task 3.2's
* interim `createDefaultIgnorer()` stub) and a `maxResults` cap
* (`QUICK_OPEN_MAX_RESULTS`) that stops the
* traversal outright once hit rather than walking the whole tree first
* (code review finding, "bounded workspace scan" — see `../shared/
* walkFiles.ts`'s "Bounded scans"); a cap-truncated walk surfaces a
Expand DownExpand Up@@ -86,7 +91,7 @@
*/

import type { CommandDescriptor, ExtensionContext, QuickPickItem } from "@tecode/api";
import { createDefaultIgnorer, filterByWhen, fuzzyMatch, walkFiles } from "../shared";
import { createBunGitRunner, createIgnoreChecker, filterByWhen, fuzzyMatch, walkFiles } from "../shared";
import { QUICK_OPEN_COMMAND_ID, SHOW_COMMANDS_COMMAND_ID } from "./manifest";

/** Cap on how many files {@link registerQuickOpen}'s workspace walk collects
Expand DownExpand Up@@ -142,6 +147,16 @@ function registerShowCommands(ctx: ExtensionContext): void {
/** Registers `workbench.action.quickOpen` (this module's TSDoc). */
function registerQuickOpen(ctx: ExtensionContext): void {
const { api } = ctx;
// Built ONCE, when the extension activates, not per keystroke/invocation:
// `IgnoreChecker`'s own `git`-availability check and root-`.gitignore`
// parse are each cached internally per instance (`ignore.ts`'s TSDoc), so
// reusing this one instance across every `ctrl+p` in the session avoids
// re-spawning `git --version` and re-reading `.gitignore` on every open.
const ignore = createIgnoreChecker({
readFile: (uri) => api.workspace.fs.read(uri),
gitRunner: createBunGitRunner(),
});

ctx.subscriptions.push(
api.commands.register(QUICK_OPEN_COMMAND_ID, async () => {
const rootUri = api.workspace.rootUri;
Expand All@@ -152,7 +167,7 @@ function registerQuickOpen(ctx: ExtensionContext): void {

const { files, truncated } = await walkFiles(rootUri, {
readdir: (uri) => api.workspace.fs.readdir(uri),
ignore: createDefaultIgnorer(),
ignore,
maxResults: QUICK_OPEN_MAX_RESULTS,
});
if (files.length === 0) {
Expand Down
182 changes: 182 additions & 0 deletions packages/builtin/explorer/ExplorerView.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
/**
* Tests for {@link ExplorerView} (Task 3.3, Req 11.2) — a fake `Tree`
* component stands in for `@tecode/core`'s real one (this built-in has no
* compile-time or runtime dependency on it, `ExplorerView.tsx`'s TSDoc),
* proving the PROP WIRING (`nodes`/`selectedId`/`expandedIds`/
* `focusContextKey`/`onSelect`/`onToggle`/`onActivate`) rather than
* `tecode.ui.Tree`'s own rendering (already covered by `@tecode/core`'s
* `components.test.tsx`).
*/

import { describe, expect, test } from "bun:test";
import { act, type ReactNode } from "react";
import { testRender } from "@opentui/react/test-utils";
import type { Tecode, Uri } from "@tecode/api";
import { createIgnoreChecker } from "../shared";
import { createExplorerStore } from "./store";
import { EXPLORER_FOCUS_CONTEXT_KEY, ExplorerView } from "./ExplorerView";

/** A minimal fake `tecode.ui.Tree` — captures the last props it was
* rendered with (for assertion) and renders each node's label as text,
* enough to prove `ExplorerView` passes the right data through without
* reimplementing the real `Tree`'s rendering/keyboard logic. */
function createFakeTree(): { Tree: Tecode["ui"]["Tree"]; lastProps: () => Record<string, unknown> | undefined } {
let captured: Record<string, unknown> | undefined;
const Tree = ((rawProps: Record<string, unknown>) => {
captured = rawProps;
const nodes = (rawProps["nodes"] as Array<{ id: string; label: string }> | undefined) ?? [];
return <box>{nodes.map((n) => <text key={n.id}>{n.label}</text>)}</box> as unknown as ReactNode;
}) as unknown as Tecode["ui"]["Tree"];
return { Tree, lastProps: () => captured };
}

type FakeTree = { [name: string]: FakeTree | null };
const ROOT: Uri = "file:///workspace/";

function createStore(tree: FakeTree, rootUri: Uri | undefined) {
return createExplorerStore(rootUri, {
readdir: async (uri) => {
const relative = uri.replace(ROOT, "").replace(/\/$/, "");
const segments = relative.length > 0 ? relative.split("/") : [];
let node: FakeTree = tree;
for (const segment of segments) {
const next = node[decodeURIComponent(segment)];
if (next === null || next === undefined) throw new Error("ENOENT");
node = next;
}
return Object.entries(node).map(([name, value]) => ({
name,
type: (value === null ? "file" : "directory") as "file" | "directory",
}));
},
ignore: createIgnoreChecker(),
showMessage: () => {},
showHidden: false,
});
}

describe("ExplorerView (Task 3.3, Req 11.2)", () => {
test("shows 'No folder is open.' when the store has no rootUri", async () => {
const store = createStore({}, undefined);
const { Tree } = createFakeTree();
const { renderOnce, captureCharFrame } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={() => {}} />,
{ width: 30, height: 5 },
);
await renderOnce();
expect(captureCharFrame()).toContain("No folder is open.");
});

test("shows '(empty)' before the root has loaded", async () => {
const store = createStore({}, ROOT);
const { Tree } = createFakeTree();
const { renderOnce, captureCharFrame } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={() => {}} />,
{ width: 30, height: 5 },
);
await renderOnce();
expect(captureCharFrame()).toContain("(empty)");
});

test("renders the store's nodes once loaded, and re-renders on store changes", async () => {
const store = createStore({ "a.ts": null }, ROOT);
const { Tree } = createFakeTree();
const { renderOnce, captureCharFrame } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={() => {}} />,
{ width: 30, height: 5 },
);
await renderOnce();
expect(captureCharFrame()).toContain("(empty)");

await act(async () => {
await store.reload(ROOT);
});
await renderOnce();
expect(captureCharFrame()).toContain("a.ts");
});

test("passes selectedId, expandedIds, and focusContextKey through to Tree", async () => {
const store = createStore({ src: { "a.ts": null } }, ROOT);
await store.reload(ROOT);
store.setSelectedId("file:///workspace/src" as Uri);
store.toggle("file:///workspace/src" as Uri, true);
await new Promise((r) => setTimeout(r, 10)); // let the toggle's own reload settle

const { Tree, lastProps } = createFakeTree();
const { renderOnce } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={() => {}} />,
{ width: 30, height: 5 },
);
await renderOnce();

expect(lastProps()?.["selectedId"]).toBe("file:///workspace/src");
expect(lastProps()?.["expandedIds"]).toEqual(["file:///workspace/src"]);
expect(lastProps()?.["focusContextKey"]).toBe(EXPLORER_FOCUS_CONTEXT_KEY);
});

test("onSelect from Tree updates the store's selection", async () => {
const store = createStore({ "a.ts": null }, ROOT);
await store.reload(ROOT);
const { Tree, lastProps } = createFakeTree();
const { renderOnce } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={() => {}} />,
{ width: 30, height: 5 },
);
await renderOnce();

act(() => {
(lastProps()?.["onSelect"] as (id: string) => void)("file:///workspace/a.ts");
});
expect(store.getSelectedId()).toBe("file:///workspace/a.ts");
});

test("onToggle from Tree toggles the store's expansion", async () => {
const store = createStore({ src: { "a.ts": null } }, ROOT);
await store.reload(ROOT);
const { Tree, lastProps } = createFakeTree();
const { renderOnce } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={() => {}} />,
{ width: 30, height: 5 },
);
await renderOnce();

act(() => {
(lastProps()?.["onToggle"] as (id: string, expanding: boolean) => void)("file:///workspace/src", true);
});
expect(store.getExpandedIds()).toEqual(["file:///workspace/src"]);
});

test("onActivate on a FILE node calls onOpenFile with its uri", async () => {
const store = createStore({ "a.ts": null }, ROOT);
await store.reload(ROOT);
const opened: string[] = [];
const { Tree, lastProps } = createFakeTree();
const { renderOnce } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={(uri) => opened.push(uri)} />,
{ width: 30, height: 5 },
);
await renderOnce();

act(() => {
(lastProps()?.["onActivate"] as (id: string) => void)("file:///workspace/a.ts");
});
expect(opened).toEqual(["file:///workspace/a.ts"]);
});

test("onActivate on a DIRECTORY node does NOT call onOpenFile", async () => {
const store = createStore({ src: { "a.ts": null } }, ROOT);
await store.reload(ROOT);
const opened: string[] = [];
const { Tree, lastProps } = createFakeTree();
const { renderOnce } = await testRender(
<ExplorerView store={store} Tree={Tree} onOpenFile={(uri) => opened.push(uri)} />,
{ width: 30, height: 5 },
);
await renderOnce();

act(() => {
(lastProps()?.["onActivate"] as (id: string) => void)("file:///workspace/src");
});
expect(opened).toEqual([]);
});
});
Loading
Loading