fix(new-project): flag a taken folder and remember the location (#5024)

New Project accepted the name of a folder that already exists and has files, and only reported "already exists and is not empty" in the progress view after Create. It now checks as the name or location changes: the name field and its hint turn red and Create is disabled. Until the user types a name, it follows the first free `untitled`, `untitled1`, … in the location.

The location always started at the home folder (unless Default Project Directory was set). It now starts where the last project was created; the Default Project Directory setting still comes first.

The check is the one `scaffold_create` already did, moved into `ide_scaffold::target_taken` and exposed with `free_name` as `scaffold_target_taken` / `scaffold_free_name`.
This commit is contained in:
l0ng-ai
2026-11-22 00:51:52 +08:00
committed by GitHub
parent 0798582173
commit 8eb332aba7
11 changed files with 229 additions and 10 deletions
+7
View File
@@ -1501,6 +1501,8 @@ export const commands = {
* trusted. Cancellable with `cancel_request(request)`; a failed or cancelled run leaves nothing.
*/
scaffoldCreate: (req: CreateRequest, request: RequestId, onEvent: Channel<ScaffoldEvent>) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("scaffold_create", { req, request, onEvent })),
/** The first of `base`, `base1`, `base2`, … that names nothing in `location` yet. */
scaffoldFreeName: (location: string, base: string) => typedError<string, IdeError>(__TAURI_INVOKE("scaffold_free_name", { location, base })),
/**
* The fields a generator's project service adds for `values`; cancellable with
* `cancel_request(request)`.
@@ -1508,6 +1510,11 @@ export const commands = {
scaffoldOptions: (generator: string, values: { [key in string]: string }, request: RequestId) => typedError<Field[], IdeError>(__TAURI_INVOKE("scaffold_options", { generator, values, request })),
/** The programs a generator needs for `values`, and whether they are installed. */
scaffoldRequirements: (generator: string, values: { [key in string]: string }) => typedError<Requirement[], IdeError>(__TAURI_INVOKE("scaffold_requirements", { generator, values })),
/**
* Whether a project named `name` cannot be created in `location`: something other than an
* empty folder is already there.
*/
scaffoldTargetTaken: (location: string, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("scaffold_target_taken", { location, name })),
scopeFiles: (pattern: string, limit: number) => typedError<ScopeFiles, IdeError>(__TAURI_INVOKE("scope_files", { pattern, limit })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
sdkContainerPython: () => typedError<{
+68 -7
View File
@@ -65,9 +65,28 @@ function errorText(e: unknown) {
return e instanceof Error ? e.message : String(e);
}
/** Default Project Directory, else the parent of the open project. */
const LOCATION_KEY = "openidea.newProject.location";
const DEFAULT_NAME = "untitled";
function lastLocation(): string {
try {
return localStorage.getItem(LOCATION_KEY) ?? "";
} catch {
return "";
}
}
function saveLocation(dir: string) {
try {
localStorage.setItem(LOCATION_KEY, dir);
} catch {
// Not kept: the next project starts from the default location.
}
}
/** Default Project Directory, else where the last project was created, else the parent of the open project. */
function initialLocation(): string {
const preset = defaultProjectDirectory();
const preset = defaultProjectDirectory() || lastLocation();
if (preset) return preset;
const root = useProject.getState().project?.root;
return root ? root.slice(0, Math.max(root.lastIndexOf("/"), 1)) : "";
@@ -119,7 +138,11 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
const [catalogError, setCatalogError] = useState<string | null>(null);
const [selected, setSelected] = useState("empty");
const [query, setQuery] = useState("");
const [name, setName] = useState("untitled");
const [name, setName] = useState(DEFAULT_NAME);
/** Until the user types a name, it follows the first free `untitled…` in the location. */
const [nameEdited, setNameEdited] = useState(false);
/** The project path last found taken (something other than an empty folder is there). */
const [takenPath, setTakenPath] = useState<string | null>(null);
const [location, setLocation] = useState(initialLocation);
const [git, setGit] = useState(true);
/** Values the user set, per generator; the rest are rendered defaults. */
@@ -212,8 +235,42 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
const setValue = (id: string, value: string) =>
setEdited((all) => ({ ...all, [selected]: { ...(all[selected] ?? {}), [id]: value } }));
const nameError = projectNameError(name);
const path = location.trim() && !nameError ? joinPath(location.trim(), name) : "";
const syntaxError = projectNameError(name);
const path = location.trim() && !syntaxError ? joinPath(location.trim(), name) : "";
const nameError =
syntaxError ?? (path && takenPath === path ? "A folder with this name already exists and is not empty" : null);
useEffect(() => {
const dir = location.trim();
if (nameEdited || !dir) return;
let live = true;
const timer = setTimeout(() => {
call(commands.scaffoldFreeName(dir, DEFAULT_NAME))
.then((free) => live && setName(free))
.catch(() => {});
}, 200);
return () => {
live = false;
clearTimeout(timer);
};
}, [location, nameEdited]);
useEffect(() => {
if (!path) return;
let live = true;
const dir = location.trim();
const timer = setTimeout(() => {
call(commands.scaffoldTargetTaken(dir, name.trim()))
.then((taken) => live && setTakenPath(taken ? path : null))
.catch(() => {});
}, 150);
return () => {
live = false;
clearTimeout(timer);
};
// `path` already reflects `location` and `name`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [path]);
const visibleFields = fields.filter((f) => isVisible(f, values));
const invalidField = visibleFields.find((f) => fieldError(f, values[f.id] ?? ""));
const missing = requirements.filter((r) => !r.satisfied);
@@ -265,6 +322,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
channel,
),
);
saveLocation(location.trim());
onClose();
await openProjectInWindow(dir, useProject.getState().project !== null);
} catch (e) {
@@ -354,7 +412,10 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => setName(e.target.value)}
onChange={(e) => {
setNameEdited(true);
setName(e.target.value);
}}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
@@ -376,7 +437,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
/>
</div>
<span />
<div className={styles.hint}>
<div className={nameError ? `${styles.hint} ${styles.hintError}` : styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
@@ -0,0 +1,98 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { GeneratorInfo } from "@/bindings";
import { NewProjectOverlay, showNewProject } from "../NewProject";
const mocks = vi.hoisted(() => ({
freeName: vi.fn(),
taken: vi.fn(),
create: vi.fn(),
open: vi.fn(),
}));
const empty: GeneratorInfo = {
id: "empty",
name: "Empty Project",
group: "New Project",
icon: "folder",
order: 0,
description: "An empty folder to add files to.",
git: true,
fields: [],
dynamic: false,
};
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: {
...actual.commands,
scaffoldCatalog: () => Promise.resolve([empty]),
scaffoldRequirements: () => Promise.resolve({ status: "ok", data: [] }),
scaffoldFreeName: mocks.freeName,
scaffoldTargetTaken: mocks.taken,
scaffoldCreate: mocks.create,
},
};
});
vi.mock("../windows", async (original) => ({
...(await original<typeof import("../windows")>()),
openProjectInWindow: mocks.open,
}));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
const nameInput = () => screen.getByLabelText("Name:");
const createButton = () => screen.getByRole("button", { name: "Create" });
describe("File › New Project… name and location", () => {
beforeEach(() => {
localStorage.clear();
localStorage.setItem("openidea.newProject.location", "/work/projects");
mocks.freeName.mockImplementation(() => ok("untitled2"));
mocks.taken.mockImplementation((_dir: string, name: string) => ok(name === "existing"));
mocks.create.mockImplementation(() => ok("/work/projects/untitled2"));
mocks.open.mockResolvedValue(undefined);
});
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
it("starts where the last project was created, named after the first free untitled folder", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
expect(screen.getByLabelText("Location:")).toHaveValue("/work/projects");
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
expect(mocks.freeName).toHaveBeenCalledWith("/work/projects", "untitled");
});
it("marks a name whose folder already exists with files and disables Create", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
fireEvent.change(nameInput(), { target: { value: "existing" } });
expect(await screen.findByText("A folder with this name already exists and is not empty")).toBeInTheDocument();
expect(nameInput()).toHaveAttribute("aria-invalid", "true");
expect(createButton()).toBeDisabled();
fireEvent.change(nameInput(), { target: { value: "fresh" } });
await waitFor(() => expect(createButton()).toBeEnabled());
expect(screen.queryByText("A folder with this name already exists and is not empty")).toBeNull();
});
it("remembers the location of the project it created", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
fireEvent.change(screen.getByLabelText("Location:"), { target: { value: "/elsewhere" } });
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(mocks.open).toHaveBeenCalled());
expect(localStorage.getItem("openidea.newProject.location")).toBe("/elsewhere");
});
});
+3
View File
@@ -117,6 +117,9 @@
.hint {
min-height: 1.5em;
}
.hint.hintError {
color: var(--danger);
}
.fieldHint {
margin-top: 4px;
}
+2 -1
View File
@@ -3016,5 +3016,6 @@
"Location:": "Location:",
"ID:": "ID:",
"Homepage:": "Homepage:",
"Mail:": "Mail:"
"Mail:": "Mail:",
"A folder with this name already exists and is not empty": "A folder with this name already exists and is not empty"
}
+1
View File
@@ -3719,6 +3719,7 @@
"Choose a scope": "选择范围",
"Enter a project name": "请输入项目名称",
"The name contains characters a folder name cannot have": "名称包含文件夹名称中不能使用的字符",
"A folder with this name already exists and is not empty": "已存在同名文件夹且不为空",
"Project Location": "项目位置",
"New Project": "新建项目",
"New Project…": "新建项目…",