Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
565106d333 | ||
|
|
9ee21b09ac | ||
|
|
30e6d8838c |
No files matched your search
@@ -80,6 +80,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.projectsScaffold]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as ProjectScaffoldService from "./ProjectScaffoldService.ts";
|
||||
|
||||
const RealGitLayer = ProjectScaffoldService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-project-scaffold-" })),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* driver.execute({
|
||||
operation: "ProjectScaffoldService.test.git",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("scaffolds a committed repo on main with README and favicon", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* ProjectScaffoldService.ProjectScaffoldService;
|
||||
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-scaffold-" });
|
||||
const destination = path.join(tempDir, "cool-idea");
|
||||
|
||||
const result = yield* service.scaffold({ name: "Cool Idea", destinationPath: destination });
|
||||
assert.equal(result.cwd, destination);
|
||||
|
||||
const readme = yield* fileSystem.readFileString(path.join(destination, "README.md"));
|
||||
assert.equal(readme, "# Cool Idea\n\nInitialized with T3 Code.\n");
|
||||
const favicon = yield* fileSystem.readFileString(path.join(destination, "favicon.svg"));
|
||||
assert.include(favicon, "<svg");
|
||||
|
||||
// The initial commit is the point of the scaffold: worktree creation
|
||||
// fails on an unborn HEAD, so HEAD must resolve and the tree be clean.
|
||||
const branch = yield* runGit(destination, ["symbolic-ref", "--short", "HEAD"]);
|
||||
assert.equal(branch.stdout.trim(), "main");
|
||||
yield* runGit(destination, ["rev-parse", "--verify", "HEAD"]);
|
||||
const status = yield* runGit(destination, ["status", "--porcelain"]);
|
||||
assert.equal(status.stdout.trim(), "");
|
||||
}),
|
||||
).pipe(Effect.provide(RealGitLayer)),
|
||||
);
|
||||
|
||||
it.effect("refuses an existing destination folder", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* ProjectScaffoldService.ProjectScaffoldService;
|
||||
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-scaffold-" });
|
||||
const destination = path.join(tempDir, "taken");
|
||||
yield* fileSystem.makeDirectory(destination);
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
service.scaffold({ name: "Taken", destinationPath: destination }),
|
||||
);
|
||||
assert.include(error.detail, "already exists");
|
||||
}),
|
||||
).pipe(Effect.provide(RealGitLayer)),
|
||||
);
|
||||
|
||||
it.effect("removes the created folder when a git step fails", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-scaffold-" });
|
||||
const destination = path.join(tempDir, "doomed");
|
||||
|
||||
const failingGitLayer = ProjectScaffoldService.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(GitVcsDriver.GitVcsDriver)({
|
||||
execute: (input) =>
|
||||
input.args.includes("commit")
|
||||
? Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: "git",
|
||||
cwd: input.cwd,
|
||||
detail: "boom",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const service = yield* ProjectScaffoldService.ProjectScaffoldService;
|
||||
return yield* Effect.flip(
|
||||
service.scaffold({ name: "Doomed", destinationPath: destination }),
|
||||
);
|
||||
}).pipe(Effect.provide(failingGitLayer));
|
||||
|
||||
assert.isNotNull(error);
|
||||
assert.isFalse(yield* fileSystem.exists(destination));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -0,0 +1,165 @@
|
||||
import * as NodeOS from "node:os";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ProjectScaffoldError,
|
||||
type ProjectScaffoldInput,
|
||||
type ProjectScaffoldResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { generateProjectFaviconSvg, generateProjectReadme } from "@t3tools/shared/projectScaffold";
|
||||
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
|
||||
const isProjectScaffoldError = Schema.is(ProjectScaffoldError);
|
||||
|
||||
// Fallback identity for the initial commit when the machine has no git
|
||||
// user.name/user.email configured. The commit genuinely comes from the tool,
|
||||
// and a first-run user should not hit a git config error here.
|
||||
const FALLBACK_COMMIT_IDENTITY = {
|
||||
name: "T3 Code",
|
||||
email: "[email protected]",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Creates a brand-new project folder: mkdir, `git init -b main`, README.md and
|
||||
* a generated favicon.svg, then one initial commit. The initial commit is
|
||||
* mandatory — thread start creates a worktree from the base branch, and
|
||||
* `git worktree add` fails on a repo with an unborn HEAD.
|
||||
*/
|
||||
export class ProjectScaffoldService extends Context.Service<
|
||||
ProjectScaffoldService,
|
||||
{
|
||||
readonly scaffold: (
|
||||
input: ProjectScaffoldInput,
|
||||
) => Effect.Effect<ProjectScaffoldResult, ProjectScaffoldError>;
|
||||
}
|
||||
>()("t3/project/ProjectScaffoldService") {}
|
||||
|
||||
function expandHomePath(input: string, path: Path.Path): string {
|
||||
if (input === "~") {
|
||||
return NodeOS.homedir();
|
||||
}
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return path.join(NodeOS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function mapScaffoldError(operation: string) {
|
||||
return Effect.mapError((cause: unknown) =>
|
||||
isProjectScaffoldError(cause)
|
||||
? cause
|
||||
: new ProjectScaffoldError({
|
||||
operation,
|
||||
detail: "The project could not be created.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const gitConfigValue = (cwd: string, key: string) =>
|
||||
git
|
||||
.execute({
|
||||
operation: "ProjectScaffoldService.readGitConfig",
|
||||
cwd,
|
||||
args: ["config", "--get", key],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : "")));
|
||||
|
||||
const populateRepository = Effect.fn("ProjectScaffoldService.populateRepository")(function* (
|
||||
destination: string,
|
||||
name: string,
|
||||
) {
|
||||
yield* git.execute({
|
||||
operation: "ProjectScaffoldService.gitInit",
|
||||
cwd: destination,
|
||||
args: ["init", "-b", "main"],
|
||||
});
|
||||
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(destination, "README.md"),
|
||||
generateProjectReadme(name),
|
||||
);
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(destination, "favicon.svg"),
|
||||
generateProjectFaviconSvg(name),
|
||||
);
|
||||
|
||||
yield* git.execute({
|
||||
operation: "ProjectScaffoldService.gitAdd",
|
||||
cwd: destination,
|
||||
args: ["add", "README.md", "favicon.svg"],
|
||||
});
|
||||
|
||||
const userName = yield* gitConfigValue(destination, "user.name");
|
||||
const userEmail = yield* gitConfigValue(destination, "user.email");
|
||||
const identityArgs =
|
||||
userName.length > 0 && userEmail.length > 0
|
||||
? []
|
||||
: [
|
||||
"-c",
|
||||
`user.name=${FALLBACK_COMMIT_IDENTITY.name}`,
|
||||
"-c",
|
||||
`user.email=${FALLBACK_COMMIT_IDENTITY.email}`,
|
||||
];
|
||||
|
||||
yield* git.execute({
|
||||
operation: "ProjectScaffoldService.gitCommit",
|
||||
cwd: destination,
|
||||
args: [...identityArgs, "commit", "-m", "Initial commit"],
|
||||
});
|
||||
});
|
||||
|
||||
const scaffold = Effect.fn("ProjectScaffoldService.scaffold")(function* (
|
||||
input: ProjectScaffoldInput,
|
||||
) {
|
||||
const destination = path.resolve(expandHomePath(input.destinationPath.trim(), path));
|
||||
const alreadyExists = new ProjectScaffoldError({
|
||||
operation: "prepareDestination",
|
||||
detail: `A folder already exists at ${destination}.`,
|
||||
});
|
||||
|
||||
if (yield* fileSystem.exists(destination).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return yield* alreadyExists;
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(destination), { recursive: true });
|
||||
// Non-recursive mkdir is the exclusive ownership claim: if a concurrent
|
||||
// scaffold created the folder between the check above and here, this fails
|
||||
// instead of silently adopting (and later deleting) the other call's repo.
|
||||
yield* fileSystem.makeDirectory(destination).pipe(
|
||||
Effect.catch((cause) =>
|
||||
fileSystem.exists(destination).pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
Effect.flatMap((nowExists) => Effect.fail(nowExists ? alreadyExists : cause)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Remove the folder this call created when any later step fails, so a
|
||||
// retry with the same name starts clean. Parents created by the recursive
|
||||
// mkdir are left in place; they are the stable projects root.
|
||||
yield* populateRepository(destination, input.name).pipe(
|
||||
Effect.onError(() => fileSystem.remove(destination, { recursive: true }).pipe(Effect.ignore)),
|
||||
);
|
||||
|
||||
return { cwd: destination };
|
||||
});
|
||||
|
||||
return ProjectScaffoldService.of({
|
||||
scaffold: (input) => scaffold(input).pipe(mapScaffoldError("scaffold")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProjectScaffoldService, make);
|
||||
@@ -137,6 +137,7 @@ import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as ProjectScaffoldService from "./project/ProjectScaffoldService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
@@ -394,6 +395,7 @@ const buildAppUnderTest = (options?: {
|
||||
sourceControlRepositoryService?: Partial<
|
||||
SourceControlRepositoryService.SourceControlRepositoryService["Service"]
|
||||
>;
|
||||
projectScaffoldService?: Partial<ProjectScaffoldService.ProjectScaffoldService["Service"]>;
|
||||
reviewService?: Partial<ReviewService.ReviewService["Service"]>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]>;
|
||||
projectSetupScriptRunner?: Partial<
|
||||
@@ -723,9 +725,14 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(reviewLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
|
||||
...options?.layers?.sourceControlRepositoryService,
|
||||
}),
|
||||
Layer.mergeAll(
|
||||
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
|
||||
...options?.layers?.sourceControlRepositoryService,
|
||||
}),
|
||||
Layer.mock(ProjectScaffoldService.ProjectScaffoldService)({
|
||||
...options?.layers?.projectScaffoldService,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provide(
|
||||
|
||||
@@ -63,6 +63,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "./serverSettings.ts";
|
||||
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
|
||||
import * as ProjectScaffoldService from "./project/ProjectScaffoldService.ts";
|
||||
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
@@ -297,6 +298,10 @@ const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.l
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
);
|
||||
|
||||
const ProjectScaffoldServiceLayerLive = ProjectScaffoldService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
);
|
||||
|
||||
const ReviewLayerLive = ReviewService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
@@ -309,6 +314,7 @@ const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(ReviewLayerLive),
|
||||
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
|
||||
Layer.provideMerge(ProjectScaffoldServiceLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
|
||||
@@ -109,6 +109,7 @@ import * as UsageService from "./usage/UsageService.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
|
||||
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
|
||||
import * as ProjectScaffoldService from "./project/ProjectScaffoldService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
|
||||
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
|
||||
@@ -409,6 +410,7 @@ const makeWsRpcLayer = (
|
||||
);
|
||||
const sourceControlRepositories =
|
||||
yield* SourceControlRepositoryService.SourceControlRepositoryService;
|
||||
const projectScaffold = yield* ProjectScaffoldService.ProjectScaffoldService;
|
||||
const pullRequests = yield* PullRequestService.PullRequestService;
|
||||
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
@@ -1820,6 +1822,10 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsScaffold]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.projectsScaffold, projectScaffold.scaffold(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
|
||||
import {
|
||||
buildCreateProjectDestination,
|
||||
canCreateProjectInEnvironment,
|
||||
} from "@t3tools/client-runtime/operations/projects";
|
||||
import { connectionStatusText } from "@t3tools/client-runtime/connection";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import {
|
||||
@@ -38,6 +41,7 @@ import {
|
||||
PaletteIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
SquarePlusIcon,
|
||||
TextSearchIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
@@ -578,6 +582,9 @@ function OpenCommandPaletteDialog(props: {
|
||||
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const scaffoldProject = useAtomCommand(projectEnvironment.scaffold, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const { environments } = useEnvironments();
|
||||
const desktopLocalBootstraps = useDesktopLocalBootstraps();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
@@ -636,8 +643,12 @@ function OpenCommandPaletteDialog(props: {
|
||||
);
|
||||
const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
|
||||
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
|
||||
const [addProjectCreateFlow, setAddProjectCreateFlow] = useState<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
} | null>(null);
|
||||
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
|
||||
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
|
||||
const [isCreatingProject, setIsCreatingProject] = useState(false);
|
||||
const projectGroupingSettings = useMemo(
|
||||
() => selectProjectGroupingSettings(clientSettings),
|
||||
[clientSettings],
|
||||
@@ -1109,6 +1120,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
function popView(): void {
|
||||
browseNavigation.invalidate();
|
||||
setAddProjectCloneFlow(null);
|
||||
setAddProjectCreateFlow(null);
|
||||
if (viewStack.length <= 1) {
|
||||
setAddProjectEnvironmentId(null);
|
||||
}
|
||||
@@ -1145,6 +1157,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
() => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
setAddProjectCreateFlow(null);
|
||||
pushPaletteView(view);
|
||||
},
|
||||
);
|
||||
@@ -1162,6 +1175,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
(environmentId: EnvironmentId, source: AddProjectRemoteSource): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow({ step: "repository", environmentId, source });
|
||||
setAddProjectCreateFlow(null);
|
||||
pushPaletteView({
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: [],
|
||||
@@ -1171,6 +1185,19 @@ function OpenCommandPaletteDialog(props: {
|
||||
[pushPaletteView],
|
||||
);
|
||||
|
||||
const startAddProjectCreate = useCallback(
|
||||
(environmentId: EnvironmentId): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
setAddProjectCreateFlow({ environmentId });
|
||||
pushPaletteView({
|
||||
addonIcon: <SquarePlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [],
|
||||
});
|
||||
},
|
||||
[pushPaletteView],
|
||||
);
|
||||
|
||||
const openSourceControlSettings = useCallback(() => {
|
||||
setOpen(false);
|
||||
void navigate({ to: "/settings/source-control" });
|
||||
@@ -1194,6 +1221,18 @@ function OpenCommandPaletteDialog(props: {
|
||||
await startAddProjectBrowse(environmentId);
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
value: `action:add-project:${environmentId}:create`,
|
||||
searchTerms: ["create", "new", "empty", "init", "scaffold", "start"],
|
||||
title: "Create new project",
|
||||
description: "Start an empty repo in t3-projects",
|
||||
icon: <SquarePlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectCreate(environmentId);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const orderedSources: ReadonlyArray<AddProjectRemoteSource> = [
|
||||
@@ -1267,7 +1306,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
return [{ value: `sources:${environmentId}`, label: "Sources", items: sourceItems }];
|
||||
},
|
||||
[openSourceControlSettings, startAddProjectBrowse, startAddProjectClone],
|
||||
[openSourceControlSettings, startAddProjectBrowse, startAddProjectClone, startAddProjectCreate],
|
||||
);
|
||||
|
||||
const startAddProjectSourceSelection = useCallback(
|
||||
@@ -1287,6 +1326,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
}
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
setAddProjectCreateFlow(null);
|
||||
pushPaletteView({
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: buildAddProjectSourceGroups(
|
||||
@@ -1382,6 +1422,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
clearOpenIntent();
|
||||
browseNavigation.invalidate();
|
||||
setAddProjectCloneFlow(null);
|
||||
setAddProjectCreateFlow(null);
|
||||
setViewStack([]);
|
||||
setQuery("");
|
||||
const currentPrefix =
|
||||
@@ -1607,6 +1648,8 @@ function OpenCommandPaletteDialog(props: {
|
||||
readonly rawCwd: string;
|
||||
readonly platform: string;
|
||||
readonly currentProjectCwd: string | null;
|
||||
/** Overrides the title inferred from the path (create-project keeps the typed name). */
|
||||
readonly title?: string;
|
||||
}) => {
|
||||
const environment = environments.find(
|
||||
(candidate) => candidate.environmentId === input.environmentId,
|
||||
@@ -1694,7 +1737,7 @@ function OpenCommandPaletteDialog(props: {
|
||||
environmentId: input.environmentId,
|
||||
input: {
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(cwd),
|
||||
title: input.title ?? inferProjectTitleFromPath(cwd),
|
||||
workspaceRoot: cwd,
|
||||
createWorkspaceRootIfMissing: true,
|
||||
defaultModelSelection: resolveDefaultProviderModelSelection(
|
||||
@@ -1903,6 +1946,54 @@ function OpenCommandPaletteDialog(props: {
|
||||
await handleAddProject(cloneResult.value.cwd);
|
||||
}
|
||||
|
||||
async function submitAddProjectCreateFlow(): Promise<void> {
|
||||
if (!addProjectCreateFlow || isCreatingProject) {
|
||||
return;
|
||||
}
|
||||
if (!canCreateProjectInEnvironment(browseEnvironment?.connection.phase)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Environment unavailable",
|
||||
description: `${browseEnvironment?.label ?? "The selected environment"} is not connected.`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (createProjectPlan === null || createProjectCollision) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreatingProject(true);
|
||||
const scaffoldResult = await scaffoldProject({
|
||||
environmentId: addProjectCreateFlow.environmentId,
|
||||
input: {
|
||||
name: trimmedCreateProjectName,
|
||||
destinationPath: createProjectPlan.destinationPath,
|
||||
},
|
||||
});
|
||||
setIsCreatingProject(false);
|
||||
if (scaffoldResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(scaffoldResult)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to create project",
|
||||
description: errorMessage(squashAtomCommandFailure(scaffoldResult)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await handleAddProjectForEnvironment({
|
||||
environmentId: addProjectCreateFlow.environmentId,
|
||||
rawCwd: scaffoldResult.value.cwd,
|
||||
platform: browseEnvironmentPlatform,
|
||||
currentProjectCwd: null,
|
||||
title: trimmedCreateProjectName,
|
||||
});
|
||||
}
|
||||
|
||||
const browseTo = useCallback(
|
||||
async (name: string): Promise<void> => {
|
||||
const nextQuery = appendBrowsePathSegment(query, name);
|
||||
@@ -1973,8 +2064,95 @@ function OpenCommandPaletteDialog(props: {
|
||||
};
|
||||
}, [addProjectCloneFlow]);
|
||||
|
||||
const trimmedCreateProjectName = addProjectCreateFlow ? query.trim() : "";
|
||||
const createProjectPlan = useMemo(
|
||||
() =>
|
||||
addProjectCreateFlow && trimmedCreateProjectName.length > 0
|
||||
? buildCreateProjectDestination({
|
||||
baseBrowsePath: getAddProjectInitialQueryForEnvironment(
|
||||
addProjectCreateFlow.environmentId,
|
||||
),
|
||||
name: trimmedCreateProjectName,
|
||||
})
|
||||
: null,
|
||||
[addProjectCreateFlow, getAddProjectInitialQueryForEnvironment, trimmedCreateProjectName],
|
||||
);
|
||||
// Live collision check against the create parent directory. A failed browse
|
||||
// (parent does not exist yet) means no collision is possible.
|
||||
const createProjectParentQuery = useEnvironmentQuery(
|
||||
addProjectCreateFlow && createProjectPlan
|
||||
? filesystemEnvironment.browse({
|
||||
environmentId: addProjectCreateFlow.environmentId,
|
||||
input: { partialPath: createProjectPlan.parentPath },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
// Exact-name compare: correct on case-sensitive filesystems, and the server's
|
||||
// own exists check backstops case-insensitive ones at submit time.
|
||||
const createProjectCollision =
|
||||
createProjectPlan !== null &&
|
||||
(createProjectParentQuery.data?.entries ?? EMPTY_BROWSE_ENTRIES).some(
|
||||
(entry) => entry.name === createProjectPlan.slug,
|
||||
);
|
||||
const canSubmitCreateProjectFlow =
|
||||
addProjectCreateFlow !== null &&
|
||||
createProjectPlan !== null &&
|
||||
!createProjectCollision &&
|
||||
canCreateProjectInEnvironment(browseEnvironment?.connection.phase) &&
|
||||
!isCreatingProject;
|
||||
// A typed name with no usable slug (e.g. all-symbol or non-Latin input)
|
||||
// must not leave the view silently dead; explain why Create is unavailable.
|
||||
const createProjectGroups: CommandPaletteView["groups"] =
|
||||
addProjectCreateFlow && trimmedCreateProjectName.length > 0 && createProjectPlan === null
|
||||
? [
|
||||
{
|
||||
value: "create-project",
|
||||
label: "Create project",
|
||||
items: [
|
||||
{
|
||||
kind: "action",
|
||||
value: "action:create-project:invalid-name",
|
||||
searchTerms: [],
|
||||
title: "Name needs a letter or number",
|
||||
description: "The folder name is built from a-z and 0-9 characters in the name",
|
||||
icon: <SquarePlusIcon className={ITEM_ICON_CLASS} />,
|
||||
disabled: true,
|
||||
keepOpen: true,
|
||||
run: async () => {},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
: addProjectCreateFlow && createProjectPlan
|
||||
? [
|
||||
{
|
||||
value: "create-project",
|
||||
label: "Create project",
|
||||
items: [
|
||||
{
|
||||
kind: "action",
|
||||
value: "action:create-project:confirm",
|
||||
searchTerms: [],
|
||||
title: `Create "${trimmedCreateProjectName}"`,
|
||||
description: createProjectCollision
|
||||
? `Folder already exists: ${createProjectPlan.destinationPath}`
|
||||
: createProjectPlan.destinationPath,
|
||||
icon: <SquarePlusIcon className={ITEM_ICON_CLASS} />,
|
||||
disabled: !canSubmitCreateProjectFlow,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
await submitAddProjectCreateFlow();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
let displayedGroups: CommandPaletteView["groups"] = filteredGroups;
|
||||
if (addProjectCloneFlow?.step === "repository") {
|
||||
if (addProjectCreateFlow) {
|
||||
displayedGroups = createProjectGroups;
|
||||
} else if (addProjectCloneFlow?.step === "repository") {
|
||||
displayedGroups = [];
|
||||
} else if (addProjectCloneFlow?.step === "confirm") {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups;
|
||||
@@ -1982,9 +2160,10 @@ function OpenCommandPaletteDialog(props: {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
|
||||
}
|
||||
|
||||
const inputPlaceholder =
|
||||
remoteProjectInputPlaceholder(addProjectCloneFlow) ??
|
||||
getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const inputPlaceholder = addProjectCreateFlow
|
||||
? "Enter project name"
|
||||
: (remoteProjectInputPlaceholder(addProjectCloneFlow) ??
|
||||
getCommandPaletteInputPlaceholder(paletteMode));
|
||||
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
|
||||
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
|
||||
const canSubmitBrowsePath =
|
||||
@@ -2083,6 +2262,12 @@ function OpenCommandPaletteDialog(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (addProjectCreateFlow && event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
void submitAddProjectCreateFlow();
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldSubmitBrowsePath =
|
||||
canSubmitBrowsePath &&
|
||||
event.key === "Enter" &&
|
||||
@@ -2240,83 +2425,110 @@ function OpenCommandPaletteDialog(props: {
|
||||
primaryEnvironmentId,
|
||||
]);
|
||||
|
||||
const inputAccessory =
|
||||
addProjectCloneFlow?.step === "repository" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
disabled={!canSubmitRemoteProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCloneFlow();
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{remoteProjectButtonLabel ?? "Continue"} (Enter)</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : isBrowsing ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={
|
||||
!canCreateProjectInEnvironment(browseEnvironment?.connection.phase) ||
|
||||
relativePathNeedsActiveProject ||
|
||||
(isCloneDestinationStep && isRemoteProjectPending)
|
||||
const inputAccessory = addProjectCreateFlow ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label="Create project (Enter)"
|
||||
disabled={!canSubmitCreateProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCreateFlow();
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{isCreatingProject ? "Creating" : "Create"}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Create project (Enter)</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : addProjectCloneFlow?.step === "repository" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
disabled={!canSubmitRemoteProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCloneFlow();
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{remoteProjectButtonLabel ?? "Continue"} (Enter)</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : isBrowsing ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={
|
||||
!canCreateProjectInEnvironment(browseEnvironment?.connection.phase) ||
|
||||
relativePathNeedsActiveProject ||
|
||||
(isCloneDestinationStep && isRemoteProjectPending)
|
||||
}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
}
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>
|
||||
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
|
||||
</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{submitActionLabel} ({addShortcutLabel})
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null;
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>
|
||||
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
|
||||
</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{submitActionLabel} ({addShortcutLabel})
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null;
|
||||
|
||||
const footerActionLabel =
|
||||
addProjectCloneFlow?.step === "repository"
|
||||
const footerActionLabel = addProjectCreateFlow
|
||||
? "Create"
|
||||
: addProjectCloneFlow?.step === "repository"
|
||||
? (remoteProjectButtonLabel ?? "Continue")
|
||||
: !canSubmitBrowsePath || hasHighlightedBrowseItem
|
||||
? "Select"
|
||||
@@ -2338,21 +2550,25 @@ function OpenCommandPaletteDialog(props: {
|
||||
|
||||
return (
|
||||
<CommandPaletteContent
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}-${addProjectCreateFlow ? "create" : "none"}`}
|
||||
aria-label="Command palette"
|
||||
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
|
||||
autoHighlight={
|
||||
isBrowsing || isRemoteProjectCloneFlow || addProjectCreateFlow !== null ? false : "always"
|
||||
}
|
||||
footerActionLabel={footerActionLabel}
|
||||
footerTrailing={footerTrailing}
|
||||
inputAccessory={inputAccessory}
|
||||
inputProps={{
|
||||
className:
|
||||
addProjectCloneFlow?.step === "repository"
|
||||
? "pe-32"
|
||||
: isBrowsing
|
||||
? willCreateProjectPath
|
||||
? "pe-36"
|
||||
: "pe-16"
|
||||
: undefined,
|
||||
addProjectCreateFlow !== null
|
||||
? "pe-28"
|
||||
: addProjectCloneFlow?.step === "repository"
|
||||
? "pe-32"
|
||||
: isBrowsing
|
||||
? willCreateProjectPath
|
||||
? "pe-36"
|
||||
: "pe-16"
|
||||
: undefined,
|
||||
placeholder: inputPlaceholder,
|
||||
wrapperClassName: isSubmenu
|
||||
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto"
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
buildAddProjectRemoteSourceReadiness,
|
||||
buildCreateProjectDestination,
|
||||
buildProjectCreateCommand,
|
||||
canCreateProjectInEnvironment,
|
||||
findExistingAddProject,
|
||||
@@ -151,3 +152,34 @@ describe("add project shared logic", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCreateProjectDestination", () => {
|
||||
it("nests the slug under t3-projects in the base browse path", () => {
|
||||
expect(buildCreateProjectDestination({ baseBrowsePath: "~/", name: "Cool Idea 3" })).toEqual({
|
||||
slug: "cool-idea-3",
|
||||
parentPath: "~/t3-projects/",
|
||||
destinationPath: "~/t3-projects/cool-idea-3",
|
||||
});
|
||||
});
|
||||
|
||||
it("respects a configured base directory", () => {
|
||||
expect(buildCreateProjectDestination({ baseBrowsePath: "/work/", name: "demo" })).toEqual({
|
||||
slug: "demo",
|
||||
parentPath: "/work/t3-projects/",
|
||||
destinationPath: "/work/t3-projects/demo",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses windows separators for windows base paths", () => {
|
||||
expect(buildCreateProjectDestination({ baseBrowsePath: "C:\\work\\", name: "demo" })).toEqual({
|
||||
slug: "demo",
|
||||
parentPath: "C:\\work\\t3-projects\\",
|
||||
destinationPath: "C:\\work\\t3-projects\\demo",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null while the name has no usable slug", () => {
|
||||
expect(buildCreateProjectDestination({ baseBrowsePath: "~/", name: "!!!" })).toBeNull();
|
||||
expect(buildCreateProjectDestination({ baseBrowsePath: "~/", name: " " })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -8,11 +8,16 @@ import type {
|
||||
SourceControlProviderKind,
|
||||
SourceControlRepositoryInfo,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
CREATED_PROJECTS_DIRECTORY_NAME,
|
||||
slugifyProjectName,
|
||||
} from "@t3tools/shared/projectScaffold";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
ensureBrowseDirectoryPath,
|
||||
findProjectByPath,
|
||||
inferProjectTitleFromPath,
|
||||
@@ -176,6 +181,32 @@ export function getAddProjectInitialQuery(baseDirectory: string | null | undefin
|
||||
return trimmed.length === 0 ? "~/" : ensureBrowseDirectoryPath(trimmed);
|
||||
}
|
||||
|
||||
export interface CreateProjectDestination {
|
||||
readonly slug: string;
|
||||
/** Browse-ready parent directory (trailing separator), e.g. "~/t3-projects/". */
|
||||
readonly parentPath: string;
|
||||
/** Full target folder for the new project, e.g. "~/t3-projects/cool-idea". */
|
||||
readonly destinationPath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a typed project name to its create-project target under
|
||||
* `[addProjectBaseDirectory or ~]/t3-projects/[slug]`. Returns null while the
|
||||
* name has no usable slug yet. `baseBrowsePath` comes from
|
||||
* getAddProjectInitialQuery.
|
||||
*/
|
||||
export function buildCreateProjectDestination(input: {
|
||||
readonly baseBrowsePath: string;
|
||||
readonly name: string;
|
||||
}): CreateProjectDestination | null {
|
||||
const slug = slugifyProjectName(input.name);
|
||||
if (slug.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const parentPath = appendBrowsePathSegment(input.baseBrowsePath, CREATED_PROJECTS_DIRECTORY_NAME);
|
||||
return { slug, parentPath, destinationPath: `${parentPath}${slug}` };
|
||||
}
|
||||
|
||||
export function resolveAddProjectPath(input: {
|
||||
readonly rawPath: string;
|
||||
readonly currentProjectCwd?: string | null;
|
||||
|
||||
@@ -92,6 +92,15 @@ export function createProjectEnvironmentAtoms<R, E>(
|
||||
scheduler: projectScheduler,
|
||||
concurrency: projectConcurrency,
|
||||
}),
|
||||
scaffold: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:projects:scaffold",
|
||||
tag: WS_METHODS.projectsScaffold,
|
||||
scheduler: projectScheduler,
|
||||
concurrency: {
|
||||
mode: "serial",
|
||||
key: ({ environmentId }) => environmentId,
|
||||
},
|
||||
}),
|
||||
writeFile: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:projects:write-file",
|
||||
tag: WS_METHODS.projectsWriteFile,
|
||||
|
||||
@@ -298,3 +298,29 @@ export class ProjectWriteFileError extends Schema.TaggedErrorClass<ProjectWriteF
|
||||
} as any);
|
||||
}
|
||||
}
|
||||
|
||||
export const ProjectScaffoldInput = Schema.Struct({
|
||||
// Human-readable project name; the server derives the README heading and
|
||||
// favicon letter from it. The folder name comes from destinationPath.
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(128)),
|
||||
destinationPath: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProjectScaffoldInput = typeof ProjectScaffoldInput.Type;
|
||||
|
||||
export const ProjectScaffoldResult = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProjectScaffoldResult = typeof ProjectScaffoldResult.Type;
|
||||
|
||||
export class ProjectScaffoldError extends Schema.TaggedErrorClass<ProjectScaffoldError>()(
|
||||
"ProjectScaffoldError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,9 @@ import {
|
||||
ProjectSearchContentsError,
|
||||
ProjectSearchContentsInput,
|
||||
ProjectSearchContentsResult,
|
||||
ProjectScaffoldError,
|
||||
ProjectScaffoldInput,
|
||||
ProjectScaffoldResult,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
@@ -201,6 +204,7 @@ export const WS_METHODS = {
|
||||
projectsSearchContents: "projects.searchContents",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
projectsWriteFile: "projects.writeFile",
|
||||
projectsScaffold: "projects.scaffold",
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
@@ -639,6 +643,12 @@ export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {
|
||||
error: Schema.Union([ProjectWriteFileError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsProjectsScaffoldRpc = Rpc.make(WS_METHODS.projectsScaffold, {
|
||||
payload: ProjectScaffoldInput,
|
||||
success: ProjectScaffoldResult,
|
||||
error: Schema.Union([ProjectScaffoldError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
|
||||
payload: LaunchEditorInput,
|
||||
error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
|
||||
@@ -1021,6 +1031,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsProjectsSearchContentsRpc,
|
||||
WsProjectsSearchEntriesRpc,
|
||||
WsProjectsWriteFileRpc,
|
||||
WsProjectsScaffoldRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
WsFilesystemBrowseRpc,
|
||||
WsAssetsCreateUrlRpc,
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
"types": "./src/projectFavicon.ts",
|
||||
"import": "./src/projectFavicon.ts"
|
||||
},
|
||||
"./projectScaffold": {
|
||||
"types": "./src/projectScaffold.ts",
|
||||
"import": "./src/projectScaffold.ts"
|
||||
},
|
||||
"./model": {
|
||||
"types": "./src/model.ts",
|
||||
"import": "./src/model.ts"
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
generateProjectFaviconSvg,
|
||||
generateProjectReadme,
|
||||
slugifyProjectName,
|
||||
} from "./projectScaffold.ts";
|
||||
|
||||
describe("slugifyProjectName", () => {
|
||||
it("lowercases and dashes word boundaries", () => {
|
||||
expect(slugifyProjectName("Cool Idea 3")).toBe("cool-idea-3");
|
||||
expect(slugifyProjectName(" spaced out ")).toBe("spaced-out");
|
||||
});
|
||||
|
||||
it("collapses symbol runs into single dashes", () => {
|
||||
expect(slugifyProjectName("t3.chat // clone!")).toBe("t3-chat-clone");
|
||||
});
|
||||
|
||||
it("strips leading and trailing separators", () => {
|
||||
expect(slugifyProjectName("--edgy--")).toBe("edgy");
|
||||
});
|
||||
|
||||
it("returns empty when nothing survives", () => {
|
||||
expect(slugifyProjectName("!!!")).toBe("");
|
||||
expect(slugifyProjectName(" ")).toBe("");
|
||||
});
|
||||
|
||||
it("caps length without a dangling dash", () => {
|
||||
const slug = slugifyProjectName(`${"a".repeat(63)} tail`);
|
||||
expect(slug.length).toBeLessThanOrEqual(64);
|
||||
expect(slug.endsWith("-")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateProjectFaviconSvg", () => {
|
||||
it("is deterministic for the same name", () => {
|
||||
expect(generateProjectFaviconSvg("Cool Idea")).toBe(generateProjectFaviconSvg("Cool Idea"));
|
||||
});
|
||||
|
||||
it("uses the first alphanumeric character uppercased", () => {
|
||||
expect(generateProjectFaviconSvg("cool idea")).toContain(">C</text>");
|
||||
expect(generateProjectFaviconSvg("~scratch")).toContain(">S</text>");
|
||||
});
|
||||
|
||||
it("escapes names with no alphanumeric characters", () => {
|
||||
expect(generateProjectFaviconSvg("<>")).toContain("><</text>");
|
||||
});
|
||||
|
||||
it("keeps hue inside the hsl wheel", () => {
|
||||
const hue = Number(/hsl\((\d+) /.exec(generateProjectFaviconSvg("anything"))?.[1]);
|
||||
expect(hue).toBeGreaterThanOrEqual(0);
|
||||
expect(hue).toBeLessThan(360);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateProjectReadme", () => {
|
||||
it("contains the name and the T3 Code line", () => {
|
||||
expect(generateProjectReadme("Cool Idea")).toBe("# Cool Idea\n\nInitialized with T3 Code.\n");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// Helpers for the "create project" flow: a project name maps deterministically
|
||||
// to a folder slug and a generated favicon, shared by the web client (path
|
||||
// preview, collision check) and the server (scaffold service).
|
||||
|
||||
/** Folder that groups created projects under the add-project base directory. */
|
||||
export const CREATED_PROJECTS_DIRECTORY_NAME = "t3-projects";
|
||||
|
||||
const MAX_PROJECT_SLUG_LENGTH = 64;
|
||||
|
||||
/**
|
||||
* Maps a human project name to a filesystem-safe folder name: lowercase,
|
||||
* alphanumeric runs joined by single dashes. Returns "" when nothing survives
|
||||
* (callers treat that as "no valid name yet").
|
||||
*/
|
||||
export function slugifyProjectName(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, MAX_PROJECT_SLUG_LENGTH)
|
||||
.replace(/-+$/g, "");
|
||||
}
|
||||
|
||||
/** FNV-1a, used to derive a stable hue from the project name. */
|
||||
function hashProjectName(name: string): number {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let index = 0; index < name.length; index += 1) {
|
||||
hash ^= name.charCodeAt(index);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
}
|
||||
|
||||
function projectFaviconLetter(name: string): string {
|
||||
const alphanumeric = /[\p{L}\p{N}]/u.exec(name);
|
||||
const letter = alphanumeric?.[0] ?? name.trim().at(0) ?? "?";
|
||||
return letter.toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic project favicon: the first letter of the name in white on a
|
||||
* rounded square whose hue hashes from the name. Saturation/lightness are
|
||||
* fixed so every icon reads on the true-black sidebar at 16px.
|
||||
*/
|
||||
export function generateProjectFaviconSvg(name: string): string {
|
||||
const hue = hashProjectName(name) % 360;
|
||||
const letter = escapeXml(projectFaviconLetter(name));
|
||||
return [
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">`,
|
||||
`<rect width="128" height="128" rx="24" fill="hsl(${hue} 65% 45%)"/>`,
|
||||
`<text x="64" y="64" font-family="system-ui, sans-serif" font-size="72" font-weight="700" fill="#ffffff" text-anchor="middle" dominant-baseline="central">${letter}</text>`,
|
||||
`</svg>`,
|
||||
``,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function generateProjectReadme(name: string): string {
|
||||
return `# ${name}\n\nInitialized with T3 Code.\n`;
|
||||
}
|
||||
Reference in new issue
Block a user