Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(workspace): Finder 支持新建文件夹,侧栏下拉不再截断文案

lmliheng301b80a60198
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 04f59d29..f678bf91 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1668,6 +1668,10 @@ export interface DirListResponse {
/** Windows only, on the home request (no `path`): the drive roots that exist. */
roots?: string[];
}
+/** The answer to making one folder: its absolute path, for the picker to reveal and select. */
+export interface DirCreateResponse {
+ path: string;
+}
/** One Skill found in a picked directory: metadata plus which of the two layouts it came from. */
export interface DirectorySkillItem extends SkillMetadataItem {
diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.ts
index 4e5efbc9..4233ebe1 100644
--- a/packages/server/src/http/routes/dirs.ts
+++ b/packages/server/src/http/routes/dirs.ts
@@ -15,6 +15,9 @@
* (Desktop, Documents, Downloads) looks exactly like that, and an empty list sent people
* looking for files that were there all along.
*
+ * POST /api/projects/:p/dirs makes one folder inside the folder being browsed, which is the
+ * picker's "New folder": see the route for what it refuses.
+ *
* POST /api/projects/:p/dirs/access is the picker's way out of that refusal in the desktop
* app: see the route.
*
@@ -24,7 +27,12 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { Hono } from "hono";
-import type { DirAccessResponse, DirEntryInfo, DirListResponse } from "../../api/types.js";
+import type {
+ DirAccessResponse,
+ DirCreateResponse,
+ DirEntryInfo,
+ DirListResponse,
+} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { HttpError } from "../errors.js";
import { requireValidId } from "../validate.js";
@@ -75,6 +83,41 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {
} satisfies DirListResponse);
});
+ /**
+ * The picker's "New folder": `parent` is the folder on screen, `name` the single segment to
+ * make inside it. The name is joined here rather than taken as a path, so a caller cannot
+ * walk out of the folder it is looking at with a separator or a `..` — the whole point of
+ * putting the box in the picker is that what it makes lands where the user can see it.
+ *
+ * It makes exactly one folder: `recursive` is off, so a typo in `parent` is a 404 rather than
+ * a silent tree of new folders, and a name already taken is a 409 the picker can point at
+ * rather than a silent success. 201 with the path made, which is what the picker selects.
+ */
+ app.post("/", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
+
+ const body = (await c.req.json().catch(() => null)) as {
+ parent?: unknown;
+ name?: unknown;
+ } | null;
+ const parent = typeof body?.parent === "string" ? body.parent.trim() : "";
+ const name = typeof body?.name === "string" ? body.name.trim() : "";
+ if (!path.isAbsolute(parent)) {
+ throw new HttpError(400, "dir_not_absolute", "Directory must be an absolute path.");
+ }
+ const bad = dirNameError(name);
+ if (bad !== null) throw bad;
+
+ const target = path.join(parent, name);
+ try {
+ await fs.mkdir(target);
+ } catch (err) {
+ throw dirCreateError(err, target);
+ }
+ return c.json({ path: target } satisfies DirCreateResponse, 201);
+ });
+
/**
* The picker's "Allow access" for a folder macOS refused: the desktop shell's main process
* reads it once in the app's own name, which is what makes macOS ask the user — a read from
@@ -139,6 +182,54 @@ export function dirReadError(err: unknown, dir: string): HttpError {
return new HttpError(500, "dir_read_failed", `Could not read this directory: ${dir}.`);
}
+/**
+ * Why a folder name cannot be made, or null when it can. A name is ONE segment: a separator
+ * (either spelling — a name travels between machines), `.`/`..`, or the empty string would
+ * either escape the folder on screen or name nothing, and a NUL is not a path at all. What is
+ * left is checked by the filesystem, not here: a name the platform dislikes (`*` on Windows)
+ * comes back as a create error, not as this route's own opinion.
+ */
+export function dirNameError(name: string): HttpError | null {
+ if (name === "") {
+ return new HttpError(400, "dir_name_empty", "Enter a folder name.");
+ }
+ if (name === "." || name === ".." || /[\\/]/.test(name) || name.includes("\0")) {
+ return new HttpError(400, "dir_name_invalid", "A folder name cannot be a path, `.` or `..`.");
+ }
+ return null;
+}
+
+/**
+ * The HTTP answer for a `mkdir` that failed. "Already there" is its own code so the picker can
+ * say the name is taken and keep the box open with what was typed; a name the platform refuses
+ * (a reserved one, a character its filesystem will not hold) is a 400 rather than a 500, since
+ * it is the input and not the server that is wrong.
+ */
+export function dirCreateError(err: unknown, target: string): HttpError {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code === "EEXIST") {
+ return new HttpError(409, "dir_exists", `Something is already there: ${target}.`);
+ }
+ if (code === "EACCES" || code === "EPERM") {
+ return new HttpError(
+ 403,
+ "dir_permission_denied",
+ `The server is not allowed to write here: ${path.dirname(target)}.`,
+ );
+ }
+ if (code === "ENOENT" || code === "ENOTDIR") {
+ return new HttpError(
+ 404,
+ "dir_not_found",
+ `Directory does not exist: ${path.dirname(target)}.`,
+ );
+ }
+ if (code === "EINVAL" || code === "ENAMETOOLONG") {
+ return new HttpError(400, "dir_name_invalid", `That folder name cannot be used: ${target}.`);
+ }
+ return new HttpError(500, "dir_create_failed", `Could not create this folder: ${target}.`);
+}
+
/**
* `requireProjectDir` with the refusal told apart from absence. That helper folds every
* failure into "does not exist or is inaccessible", which is the right answer where a path is
diff --git a/packages/server/test/dirs.test.ts b/packages/server/test/dirs.test.ts
index cc96717a..91a40630 100644
--- a/packages/server/test/dirs.test.ts
+++ b/packages/server/test/dirs.test.ts
@@ -8,7 +8,11 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import type { DirListResponse, ProjectCreateResponse } from "../src/api/types.js";
+import type {
+ DirCreateResponse,
+ DirListResponse,
+ ProjectCreateResponse,
+} from "../src/api/types.js";
import { dirReadError } from "../src/http/routes/dirs.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -88,3 +92,79 @@ describe("dirs api", () => {
},
);
});
+
+describe("dir create api", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let dir: string;
+
+ const createUrl = () => `/api/projects/${projectId}/dirs`;
+ const listUrl = (p: string) => `${createUrl()}?path=${encodeURIComponent(p)}`;
+ const create = (parent: unknown, name: unknown) => owner.post(createUrl(), { parent, name });
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_mkdir");
+ owner = apiClient(t.app, a.cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner_mkdir-dirs", name: "mkdir project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "penguin-mkdir-")));
+ });
+
+ afterEach(async () => {
+ await t.cleanup();
+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ });
+
+ it("makes one folder and answers with its path", async () => {
+ const res = await create(dir, "notes");
+ expect(res.status).toBe(201);
+ expect(((await res.json()) as DirCreateResponse).path).toBe(path.join(dir, "notes"));
+ expect((await fs.stat(path.join(dir, "notes"))).isDirectory()).toBe(true);
+ // Visible to the picker straight away, since that is what the answer is for.
+ const listing = (await (await owner.get(listUrl(dir))).json()) as DirListResponse;
+ expect(listing.entries.map((e) => e.name)).toContain("notes");
+ });
+
+ it("refuses a name that is a path, `.`, `..` or empty, without touching the disk", async () => {
+ for (const [name, code] of [
+ ["a/b", "dir_name_invalid"],
+ ["a\\b", "dir_name_invalid"],
+ ["..", "dir_name_invalid"],
+ [".", "dir_name_invalid"],
+ ["", "dir_name_empty"],
+ ] as const) {
+ const res = await create(dir, name);
+ expect([res.status, ((await res.json()) as { error: { code: string } }).error.code]).toEqual([
+ 400,
+ code,
+ ]);
+ }
+ // Nothing was made: a rejected name never reaches the filesystem as a path.
+ expect(await fs.readdir(dir)).toEqual([]);
+ });
+
+ it("keeps a name already taken a 409, and a parent that is not there a 404", async () => {
+ await fs.mkdir(path.join(dir, "taken"));
+ expect((await create(dir, "taken")).status).toBe(409);
+ expect((await create(path.join(dir, "gone"), "child")).status).toBe(404);
+ });
+
+ it("needs an absolute parent", async () => {
+ expect((await create("relative", "child")).status).toBe(400);
+ });
+
+ it("is refused to a caller who may not see the Project", async () => {
+ const stranger = await provisionUser(t.app, "stranger_mkdir");
+ const res = await apiClient(t.app, stranger.cookie).post(createUrl(), {
+ parent: dir,
+ name: "nope",
+ });
+ // The Project does not exist for this caller, so the route is not theirs to reach.
+ expect([403, 404]).toContain(res.status);
+ expect(await fs.readdir(dir)).toEqual([]);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 7740dd19..59504133 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -39,6 +39,7 @@ import type {
DesktopPrivacyPane,
DesktopUpdateStatusResponse,
DirAccessResponse,
+ DirCreateResponse,
DirectorySkillsResponse,
DirListResponse,
EndpointModelListRequest,
@@ -733,6 +734,17 @@ export const listDirs = (projectId: string, path = "", machineId?: string | null
`/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/dirs?path=${encodeURIComponent(path)}`,
);
+/**
+ * Makes one folder inside `parent` (the picker's "New folder"). `name` is a single segment, not
+ * a path, and only this server can be asked: a machine browsed over ssh lists folders, and the
+ * picker offers no "New folder" while it is browsing one.
+ */
+export const createDir = (projectId: string, parent: string, name: string) =>
+ apiFetch<DirCreateResponse>(`/api/projects/${encodeURIComponent(projectId)}/dirs`, {
+ method: "POST",
+ body: { parent, name },
+ });
+
/**
* Asks the desktop shell to read a folder macOS refused, in the app's own name — what makes
* macOS ask the user. Always this server: only the shell that started it can be asked. The
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index bce7121e..ce4e7ea5 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -2367,7 +2367,10 @@ export function Sidebar({
open={listSettingsOpen}
setOpen={setListSettingsOpen}
portal={{ direction: "down", align: "right" }}
- menuClass="w-40"
+ // Sized to the rows, never to a guess: a fixed narrow width clipped "Group by
+ // workspace" to "Group by work…", and the rows are the only thing that knows how
+ // wide they have to be. Same idiom as the finder's own menu.
+ menuClass="w-max min-w-40 max-w-[calc(100vw-2rem)]"
button={
<SidebarControl
label={S.chat.listSettings}
diff --git a/packages/web/src/features/chat/workspace-finder-model.ts b/packages/web/src/features/chat/workspace-finder-model.ts
index 03d82c37..9ba279f8 100644
--- a/packages/web/src/features/chat/workspace-finder-model.ts
+++ b/packages/web/src/features/chat/workspace-finder-model.ts
@@ -351,13 +351,19 @@ export interface FinderMenuTarget {
}
export type FinderMenuItem =
- "open" | "choose" | "addToQuickAccess" | "removeFromQuickAccess" | "copyPath" | "refresh";
+ | "open"
+ | "choose"
+ | "newFolder"
+ | "addToQuickAccess"
+ | "removeFromQuickAccess"
+ | "copyPath"
+ | "refresh";
/**
* The context menu's rows, the way Explorer orders them: what opening the thing does first,
* then choosing it, then Quick access, then copying its path. A file row only copies (files
* are listed for context and cannot be picked); the empty space acts on the open folder, and
- * adds Refresh as Explorer's background menu does.
+ * adds New folder and Refresh as Explorer's background menu does.
*/
export function finderMenuItems(
target: FinderMenuTarget,
@@ -366,7 +372,7 @@ export function finderMenuItems(
if (target.kind === "file") return ["copyPath"];
const quick = inQuickAccess ? "removeFromQuickAccess" : "addToQuickAccess";
return target.kind === "here"
- ? ["choose", quick, "copyPath", "refresh"]
+ ? ["choose", "newFolder", quick, "copyPath", "refresh"]
: ["open", "choose", quick, "copyPath"];
}
diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsx
index ce600e00..bfc59fbe 100644
--- a/packages/web/src/features/chat/workspace-finder.tsx
+++ b/packages/web/src/features/chat/workspace-finder.tsx
@@ -119,6 +119,7 @@ const PLACE_ICON: Record<Place["key"], string> = {
const MENU_ICON: Record<FinderMenuItem, string> = {
open: ICONS.folderOpen,
choose: CHECK_ICON,
+ newFolder: ICONS.folderPlus,
addToQuickAccess: ICONS.pin,
removeFromQuickAccess: ICONS.pin,
copyPath: STAT_ICONS.copy,
@@ -212,6 +213,15 @@ export function WorkspaceFinder({
/** The selected row, by path — survives a reload and a filter that keeps it. */
const [selected, setSelected] = useState<string | null>(null);
const [filter, setFilter] = useState("");
+ /**
+ * The name box while a folder is being made. Only this server can be asked to make one — a
+ * machine browsed over ssh lists folders and nothing else — so the box is not offered while
+ * another machine is on screen. `creating` holds the request, so Enter twice makes one folder.
+ */
+ const [newFolderOpen, setNewFolderOpen] = useState(false);
+ const [newFolderName, setNewFolderName] = useState("");
+ const [creating, setCreating] = useState(false);
+ const newFolderRef = useRef<HTMLInputElement>(null);
/** The address bar is a path field (clicked, or ⌘⇧G) rather than breadcrumbs; the draft is what it holds. */
const [addressEditing, setAddressEditing] = useState(false);
const [addressDraft, setAddressDraft] = useState("");
@@ -268,6 +278,8 @@ export function WorkspaceFinder({
setView({ path: res.path, listing: res, error: null });
setSelected(opts.select ?? null);
setFilter("");
+ setNewFolderOpen(false);
+ setNewFolderName("");
if (opts.record !== false) setHistory((h) => historyVisit(h, res.path));
})
.catch((err: unknown) => {
@@ -278,6 +290,8 @@ export function WorkspaceFinder({
setView({ path: target, listing: null, error: err });
setSelected(null);
setFilter("");
+ setNewFolderOpen(false);
+ setNewFolderName("");
if (opts.record !== false && target !== "") setHistory((h) => historyVisit(h, target));
})
.finally(() => {
@@ -411,6 +425,17 @@ export function WorkspaceFinder({
const chooseTarget = selectedEntry?.path ?? view.listing?.path ?? null;
const platform = view.listing?.platform ?? homeListing?.platform;
const crumbs = splitBreadcrumbs(view.path);
+ /** "New folder" is offered only where it can be honoured: this server's own filesystem. */
+ const canCreateFolder = machine === null && view.error === null && view.listing !== null;
+
+ // Opening the box puts the caret in it, selected, so a name is typed straight over any
+ // suggestion the browser made. Keyed on the box alone: re-running per keystroke would fight
+ // the typing it is there to serve.
+ useEffect(() => {
+ if (!newFolderOpen) return;
+ newFolderRef.current?.focus();
+ newFolderRef.current?.select();
+ }, [newFolderOpen]);
// Keep the selected row in sight as the keyboard moves it.
useEffect(() => {
@@ -466,6 +491,40 @@ export function WorkspaceFinder({
if (path !== "") load(path, { record: false, select: selected });
};
+ /** Opens the name box, with the filter cleared so the folder about to be made is visible in the list. */
+ const startNewFolder = () => {
+ if (!canCreateFolder) return;
+ setFilter("");
+ setNewFolderName("");
+ setNewFolderOpen(true);
+ };
+
+ /**
+ * Makes the folder the box names, then reveals it: the folder on screen is re-read with the
+ * new one selected, so what was made is on screen rather than merely reported. A refusal —
+ * a name taken, one the system will not accept — leaves the box open with what was typed,
+ * since the name is the thing to change; the reason is shown as a toast, which can speak
+ * while the box keeps the caret.
+ */
+ const createFolder = () => {
+ const parent = view.listing?.path ?? null;
+ const name = newFolderName.trim();
+ if (parent === null || creating) return;
+ if (name === "") {
+ newFolderRef.current?.focus();
+ return;
+ }
+ setCreating(true);
+ api
+ .createDir(projectId, parent, name)
+ .then((res) => load(parent, { record: false, select: res.path }))
+ .catch((err: unknown) => {
+ toastError(apiErrorText(err));
+ newFolderRef.current?.focus();
+ })
+ .finally(() => setCreating(false));
+ };
+
/**
* "Allow access": the shell reads the refused folder in the app's own name, which is what
* makes macOS ask. Granted, the folder is read again — unless the finder has moved on while
@@ -566,6 +625,11 @@ export function WorkspaceFinder({
case "choose":
onChoose(target.path, target.machine);
return;
+ case "newFolder":
+ // The menu only carries this row for the folder on screen of this server (see the
+ // panel's item filter), so there is nothing to re-root: the box opens where we stand.
+ startNewFolder();
+ break;
case "addToQuickAccess":
case "removeFromQuickAccess":
editQuickAccess(target.path, target.machine, item === "addToQuickAccess");
@@ -589,6 +653,8 @@ export function WorkspaceFinder({
return f.open;
case "choose":
return target.kind === "here" ? f.chooseCurrent : f.chooseThis;
+ case "newFolder":
+ return f.newFolder;
case "addToQuickAccess":
return f.addToQuickAccess;
case "removeFromQuickAccess":
@@ -609,6 +675,9 @@ export function WorkspaceFinder({
const menuTargetAt = (
at: EventTarget | null,
): { target: FinderMenuTarget; el: HTMLElement } | null => {
+ // A text field keeps its own menu: the name box sits inside the list's box, so without
+ // this the folder behind it would answer a right-click the field was asked.
+ if (at instanceof Element && at.closest("input, textarea") !== null) return null;
const el =
at instanceof Element
? at.closest<HTMLElement>("[data-finder-path], [data-finder-here]")
@@ -1147,6 +1216,19 @@ export function WorkspaceFinder({
>
<GlyphIcon d={ICONS.refresh} size={ICON_SIZE.iconButton} />
</button>
+ {/* Like Refresh, the phone reaches this from the list's context menu — the toolbar
+ keeps only the navigation there, where the address bar needs the width. */}
+ {canCreateFolder && (
+ <button
+ type="button"
+ className={`${navButtonClass} hidden sm:block`}
+ data-tooltip={f.newFolder}
+ aria-label={f.newFolder}
+ onClick={startNewFolder}
+ >
+ <GlyphIcon d={ICONS.folderPlus} size={ICON_SIZE.iconButton} />
+ </button>
+ )}
</div>
{addressBar}
<label className="relative flex shrink-0 items-center">
@@ -1235,84 +1317,129 @@ export function WorkspaceFinder({
);
} else if (view.listing === null) {
body = <p className="px-4 py-3 text-xs text-gray-400">{S.common.loading}</p>;
- } else if (entries.length === 0) {
+ } else if (entries.length === 0 && !newFolderOpen) {
body = (
<p className="px-4 py-3 text-xs text-gray-400">
{filter.trim() !== "" ? f.noMatch(filter.trim()) : f.empty}
</p>
);
} else {
- body = entries.map((entry, i) => {
- const folder = isFolder(entry);
- const isSel = i === selIndex;
- const accent = isSel && listFocused;
- return (
- <div
- key={entry.path}
- id={`${listId}-${i}`}
- role="option"
- // Named by the folder alone: the date and the enter button are the row's furniture.
- aria-label={entry.name}
- aria-selected={isSel}
- aria-disabled={folder ? undefined : true}
- data-tooltip={folder ? entry.path : f.fileNotSelectable}
- data-finder-path={entry.path}
- data-finder-kind={folder ? "folder" : "file"}
- onClick={() => {
- if (!folder) return;
- if (isCoarsePointer()) openEntry(entry.path);
- else setSelected(entry.path);
+ // The name box rides at the head of the list, where the folder it will make will appear, and
+ // an otherwise-empty folder shows it instead of "this folder is empty".
+ const newFolderRow = newFolderOpen ? (
+ <div className="flex select-none items-center gap-1 py-1 pl-3 pr-2">
+ <GlyphIcon d={ICONS.folder} size={ICON_SIZE.rowLead} className="shrink-0 text-gray-400" />
+ <input
+ ref={newFolderRef}
+ value={newFolderName}
+ aria-label={f.newFolder}
+ placeholder={f.newFolderName}
+ data-tooltip={f.newFolderHint}
+ disabled={creating}
+ {...noAutofill}
+ onChange={(e) => setNewFolderName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ // The finder's own Enter opens the selected folder; this Enter makes the folder.
+ e.stopPropagation();
+ createFolder();
+ } else if (e.key === "Escape") {
+ // Escape closes the box, not the finder (see the wrapper's key map).
+ e.preventDefault();
+ e.stopPropagation();
+ setNewFolderOpen(false);
+ }
}}
- onDoubleClick={() => folder && openEntry(entry.path)}
- className={`flex select-none items-center ${ICON_GAP.menu} py-1 pl-3 pr-2 text-sm ${
- !folder
- ? "cursor-default text-gray-400 dark:text-gray-600"
- : isSel
- ? listFocused
- ? "bg-accent text-accent-fg"
- : "bg-gray-200 text-gray-900 dark:bg-gray-700 dark:text-gray-100"
- : "cursor-default text-gray-800 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-800/60"
- }`}
- >
- <GlyphIcon
- d={folder ? ICONS.folder : ICONS.file}
- size={ICON_SIZE.rowLead}
- className={`shrink-0 ${accent ? "" : "text-gray-400"}`}
- />
- <span className="min-w-0 flex-1 truncate">{entry.name}</span>
- <span
- className={`hidden w-36 shrink-0 text-xs tabular-nums sm:block ${accent ? "" : "text-gray-400 dark:text-gray-500"}`}
- >
- {entry.mtime !== undefined ? formatDateTime(new Date(entry.mtime).toISOString()) : "—"}
- </span>
- {/* A second way into a folder beside the double click — one a touch screen, a
+ // Focus moving away — to the list, to another control — abandons the new folder, the
+ // way Explorer's does; a request already in flight is left to finish.
+ onBlur={() => {
+ if (!creating) setNewFolderOpen(false);
+ }}
+ className="h-6 min-w-0 flex-1 rounded-sm border border-gray-300 bg-white px-1.5 text-sm text-gray-800 outline-none placeholder:text-gray-400 focus:border-gray-400 dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100"
+ />
+ </div>
+ ) : null;
+ body = (
+ <>
+ {newFolderRow}
+ {entries.length === 0
+ ? null
+ : entries.map((entry, i) => {
+ const folder = isFolder(entry);
+ const isSel = i === selIndex;
+ const accent = isSel && listFocused;
+ return (
+ <div
+ key={entry.path}
+ id={`${listId}-${i}`}
+ role="option"
+ // Named by the folder alone: the date and the enter button are the row's furniture.
+ aria-label={entry.name}
+ aria-selected={isSel}
+ aria-disabled={folder ? undefined : true}
+ data-tooltip={folder ? entry.path : f.fileNotSelectable}
+ data-finder-path={entry.path}
+ data-finder-kind={folder ? "folder" : "file"}
+ onClick={() => {
+ if (!folder) return;
+ if (isCoarsePointer()) openEntry(entry.path);
+ else setSelected(entry.path);
+ }}
+ onDoubleClick={() => folder && openEntry(entry.path)}
+ className={`flex select-none items-center ${ICON_GAP.menu} py-1 pl-3 pr-2 text-sm ${
+ !folder
+ ? "cursor-default text-gray-400 dark:text-gray-600"
+ : isSel
+ ? listFocused
+ ? "bg-accent text-accent-fg"
+ : "bg-gray-200 text-gray-900 dark:bg-gray-700 dark:text-gray-100"
+ : "cursor-default text-gray-800 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-800/60"
+ }`}
+ >
+ <GlyphIcon
+ d={folder ? ICONS.folder : ICONS.file}
+ size={ICON_SIZE.rowLead}
+ className={`shrink-0 ${accent ? "" : "text-gray-400"}`}
+ />
+ <span className="min-w-0 flex-1 truncate">{entry.name}</span>
+ <span
+ className={`hidden w-36 shrink-0 text-xs tabular-nums sm:block ${accent ? "" : "text-gray-400 dark:text-gray-500"}`}
+ >
+ {entry.mtime !== undefined
+ ? formatDateTime(new Date(entry.mtime).toISOString())
+ : "—"}
+ </span>
+ {/* A second way into a folder beside the double click — one a touch screen, a
trackpad and a first-time user all find. Out of the tab order: the list's own
Enter is the keyboard's way in. A file keeps the slot empty so dates line up. */}
- {folder ? (
- <button
- type="button"
- tabIndex={-1}
- aria-label={f.openFolder(entry.name)}
- data-tooltip={f.open}
- onClick={(e) => {
- e.stopPropagation();
- openEntry(entry.path);
- }}
- onDoubleClick={(e) => e.stopPropagation()}
- className={`flex w-6 shrink-0 justify-center rounded py-0.5 transition-colors duration-150 ${
- accent
- ? "text-current"
- : "text-gray-400 hover:text-gray-900 dark:text-gray-500 dark:hover:text-gray-100"
- }`}
- >
- <GlyphIcon d={ENTER_ICON} size={ICON_SIZE.inlineGlyph} />
- </button>
- ) : (
- <span className="w-6 shrink-0" aria-hidden />
- )}
- </div>
- );
- });
+ {folder ? (
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-label={f.openFolder(entry.name)}
+ data-tooltip={f.open}
+ onClick={(e) => {
+ e.stopPropagation();
+ openEntry(entry.path);
+ }}
+ onDoubleClick={(e) => e.stopPropagation()}
+ className={`flex w-6 shrink-0 justify-center rounded py-0.5 transition-colors duration-150 ${
+ accent
+ ? "text-current"
+ : "text-gray-400 hover:text-gray-900 dark:text-gray-500 dark:hover:text-gray-100"
+ }`}
+ >
+ <GlyphIcon d={ENTER_ICON} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ ) : (
+ <span className="w-6 shrink-0" aria-hidden />
+ )}
+ </div>
+ );
+ })}
+ </>
+ );
}
const clear = clearButton({
@@ -1382,8 +1509,9 @@ export function WorkspaceFinder({
data-finder-here=""
// A listbox only while it holds rows: a message (empty, loading, an error with
// its Retry) is not an option, and the pane stays focusable either way so the
- // keyboard chords keep working from it.
- role={hasRows ? "listbox" : "region"}
+ // keyboard chords keep working from it. The name box is not an option either, so
+ // the list steps out of the role while it is up.
+ role={hasRows && !newFolderOpen ? "listbox" : "region"}
tabIndex={0}
aria-label={crumbs[crumbs.length - 1]?.label ?? title}
aria-busy={loading}
@@ -1420,16 +1548,18 @@ export function WorkspaceFinder({
button={null}
>
<Menu density="sm">
- {finderMenuItems(menuTarget, inQuickAccess(menuTarget.path, menuTarget.machine)).map(
- (item) => (
+ {finderMenuItems(menuTarget, inQuickAccess(menuTarget.path, menuTarget.machine))
+ // Making a folder is this server's own filesystem work: a machine browsed over ssh
+ // lists folders and cannot be asked to make one, so the row is not offered there.
+ .filter((item) => item !== "newFolder" || menuTarget.machine === null)
+ .map((item) => (
<MenuItem
key={item}
glyph={MENU_ICON[item]}
label={menuLabel(item, menuTarget)}
onSelect={() => runMenuItem(item, menuTarget)}
/>
- ),
- )}
+ ))}
</Menu>
</Dropdown>
)}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 7820d12f..4c2f511e 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2475,6 +2475,9 @@ export const en: Strings = {
removeNamed: (name: string): string => `Remove ${name} from Quick access`,
open: "Open",
openFolder: (name: string): string => `Open ${name}`,
+ newFolder: "New folder",
+ newFolderName: "Folder name",
+ newFolderHint: "Type a name and press Enter to create it, Escape to cancel",
chooseThis: "Choose this folder",
chooseCurrent: "Choose the current folder",
copyPath: "Copy path",
@@ -4961,6 +4964,11 @@ Scenarios:
dir_not_absolute: "The directory must be an absolute path.",
dir_not_found: "That directory does not exist or is inaccessible.",
dir_permission_denied: "Reading that directory is not allowed.",
+ dir_name_empty: "Enter a folder name.",
+ dir_name_invalid:
+ "A folder name cannot be a path, `.` or `..`, nor contain characters the system refuses.",
+ dir_exists: "That name is already taken.",
+ dir_create_failed: "Could not create that folder.",
not_a_dir: "That path is not a directory.",
path_not_found: "That path does not exist.",
reveal_failed: "Could not open the folder.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index a0ba17e4..301a85ce 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2521,6 +2521,12 @@ export const zh = {
open: "打开",
/** Accessible name of the enter button at the end of a folder row. */
openFolder: (name: string): string => `打开「${name}」`,
+ /** The toolbar button and the context-menu row that make a folder in the folder on screen. */
+ newFolder: "新建文件夹",
+ /** The name box's placeholder while a new folder is being made. */
+ newFolderName: "文件夹名称",
+ /** The name box's accessible name and tooltip: Enter makes it, Escape cancels. */
+ newFolderHint: "输入名称后按 Enter 创建,按 Esc 取消",
chooseThis: "选择此文件夹",
chooseCurrent: "选择当前文件夹",
copyPath: "复制路径",
@@ -4978,6 +4984,10 @@ Benchmark:
dir_not_absolute: "目录必须是绝对路径。",
dir_not_found: "该目录不存在或不可访问。",
dir_permission_denied: "没有读取该目录的权限。",
+ dir_name_empty: "请输入文件夹名称。",
+ dir_name_invalid: "文件夹名称不能是路径、`.` 或 `..`,也不能含有系统不接受的字符。",
+ dir_exists: "这个名称已被占用。",
+ dir_create_failed: "无法创建该文件夹。",
not_a_dir: "该路径不是目录。",
path_not_found: "该路径不存在。",
reveal_failed: "无法打开文件夹。",
diff --git a/packages/web/test/workspace-finder.test.ts b/packages/web/test/workspace-finder.test.ts
index 708dc62e..23e86b29 100644
--- a/packages/web/test/workspace-finder.test.ts
+++ b/packages/web/test/workspace-finder.test.ts
@@ -286,14 +286,21 @@ describe("the context menu", () => {
expect(finderMenuItems({ ...folder, kind: "file" }, false)).toEqual(["copyPath"]);
});
- it("acts on the open folder from the list's empty space, with Refresh", () => {
+ it("acts on the open folder from the list's empty space, with New folder and Refresh", () => {
expect(finderMenuItems({ kind: "here", path: "/p", machine: null }, false)).toEqual([
"choose",
+ "newFolder",
"addToQuickAccess",
"copyPath",
"refresh",
]);
});
+
+ it("never offers a folder row New folder: a row acts on itself, not on the folder on screen", () => {
+ const folder = { kind: "folder" as const, path: "/p/a", machine: null };
+ expect(finderMenuItems(folder, false)).not.toContain("newFolder");
+ expect(finderMenuItems({ ...folder, kind: "file" }, false)).not.toContain("newFolder");
+ });
});
describe("recent and go to folder", () => {