Skip to content

The VS Code of video editing, built for agents.

TypeScript

Enhance project management features and improve project handling

konstantin-paulus7273ed214104
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index eccd394e..cea7eb25 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -40,7 +40,11 @@ export const MAIN_CHANNELS = {
LOGS_GET: "logs:get",
PROJECTS_PICK_ROOT: "projects:pick-root",
PROJECTS_LIST: "projects:list",
+ PROJECTS_GET: "projects:get",
PROJECTS_CREATE: "projects:create",
+ PROJECTS_RENAME: "projects:rename",
+ PROJECTS_DUPLICATE: "projects:duplicate",
+ PROJECTS_DELETE: "projects:delete",
PROJECTS_COMPILE: "projects:compile",
PROJECTS_WATCH: "projects:watch",
PROJECTS_UNWATCH: "projects:unwatch",
@@ -53,13 +57,19 @@ export const MAIN_CHANNELS = {
PROJECTS_CHANGED: "projects:changed",
} as const;
-/** A project folder under the projects root: a real npm package with a JSX entry. */
+/**
+ * A project folder under the projects root: a real npm package with a JSX
+ * entry. Its package.json is the project record: `displayName` is the human
+ * name, `main` the entry file.
+ */
export type ProjectInfo = {
/** Folder name, doubles as the project id. */
name: string;
+ /** Human name from package.json `displayName` (falls back to the folder name). */
+ displayName: string;
/** Absolute path of the project folder. */
dir: string;
- /** Entry file relative to `dir` (index.tsx, index.ts, index.jsx or index.js). */
+ /** Entry file relative to `dir`: package.json `main`, else index.tsx/ts/jsx/js. */
entry: string;
/** mtime of the entry file, ISO string. */
modifiedAt: string;
@@ -109,10 +119,17 @@ export type MainRequestMap = {
[MAIN_CHANNELS.LOGS_GET]: { request: void; response: LogEntry[] };
[MAIN_CHANNELS.PROJECTS_PICK_ROOT]: { request: void; response: string | null };
[MAIN_CHANNELS.PROJECTS_LIST]: { request: { root: string }; response: ProjectInfo[] };
+ [MAIN_CHANNELS.PROJECTS_GET]: { request: { dir: string }; response: ProjectInfo | null };
[MAIN_CHANNELS.PROJECTS_CREATE]: {
- request: { root: string; name: string };
+ request: { root: string; name: string; displayName: string };
response: ProjectInfo;
};
+ [MAIN_CHANNELS.PROJECTS_RENAME]: {
+ request: { dir: string; displayName: string };
+ response: ProjectInfo;
+ };
+ [MAIN_CHANNELS.PROJECTS_DUPLICATE]: { request: { dir: string }; response: ProjectInfo };
+ [MAIN_CHANNELS.PROJECTS_DELETE]: { request: { dir: string }; response: void };
[MAIN_CHANNELS.PROJECTS_COMPILE]: { request: { dir: string }; response: CompileResult };
[MAIN_CHANNELS.PROJECTS_WATCH]: { request: { dir: string }; response: void };
[MAIN_CHANNELS.PROJECTS_UNWATCH]: { request: { dir: string }; response: void };
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index de176131..0f541b8d 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -16,8 +16,12 @@ import { MAIN_CHANNELS } from "./main-channels";
import {
compileProject,
createProject,
+ deleteProject,
+ duplicateProject,
+ getProject,
listProjects,
pickRoot,
+ renameProject,
unwatchAll,
unwatchProject,
watchProject,
@@ -257,7 +261,13 @@ if (app.requestSingleInstanceLock()) {
mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ root }) => listProjects(root));
- mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, name }) => createProject(root, name));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_GET, ({ dir }) => getProject(dir));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, name, displayName }) =>
+ createProject(root, name, displayName),
+ );
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_RENAME, ({ dir, displayName }) => renameProject(dir, displayName));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_DUPLICATE, ({ dir }) => duplicateProject(dir));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_COMPILE, ({ dir }) => compileProject(dir));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) =>
watchProject(BrowserWindow.fromWebContents(event.sender), dir),
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 85f20a7a..75d6c3ce 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -5,17 +5,19 @@
// Projects on disk. A project is a plain folder that is a real npm package
// with a JSX entry file whose default export renders a <stage>. The user picks
// a root folder; every direct child folder holding an entry file is a project.
+// The package.json is the project record (`displayName`, `main`); there is no
+// registry elsewhere.
//
// Compilation bundles the entry with esbuild (which resolves node_modules for
// us) and runs project sources through babel-preset-solid's universal JSX
// transform, so the renderer can evaluate the resulting CommonJS bundle
// against its own solid-js instance and the koota-backed JSX host.
-import { app, dialog, type BrowserWindow } from "electron";
+import { app, dialog, shell, type BrowserWindow } from "electron";
import { watch, type FSWatcher } from "node:fs";
-import { mkdir, readdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
+import { cp, mkdir, readdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
-import { join, relative, sep } from "node:path";
+import { basename, dirname, join, relative, sep } from "node:path";
import type { TransformOptions } from "@babel/core";
import type { BuildOptions, Plugin } from "esbuild";
@@ -67,21 +69,44 @@ async function exists(path: string): Promise<boolean> {
}
}
-async function findEntry(dir: string): Promise<string | undefined> {
+type PackageJson = { name?: string; displayName?: string; main?: string } & Record<string, unknown>;
+
+async function readPackage(dir: string): Promise<PackageJson | null> {
+ try {
+ return JSON.parse(await readFile(join(dir, "package.json"), "utf8")) as PackageJson;
+ } catch {
+ return null;
+ }
+}
+
+async function writePackage(dir: string, pkg: PackageJson): Promise<void> {
+ await writeFile(join(dir, "package.json"), JSON.stringify(pkg, null, 2) + "\n", "utf8");
+}
+
+/** package.json `main` when it names a JSX/TS/JS file that exists, else the default lookup. */
+async function findEntry(dir: string, pkg?: PackageJson | null): Promise<string | undefined> {
+ const main = (pkg ?? (await readPackage(dir)))?.main;
+ if (typeof main === "string" && /\.[jt]sx?$/.test(main) && (await exists(join(dir, main)))) {
+ return main.split(sep).join("/");
+ }
for (const name of ENTRY_FILES) {
if (await exists(join(dir, name))) return name;
}
return undefined;
}
-const noEntryError = (): string => `No ${ENTRY_FILES.join(" / ")} found in this folder.`;
+const noEntryError = (): string =>
+ `No entry found in this folder (package.json "main" or ${ENTRY_FILES.join(" / ")}).`;
-async function describe(dir: string, name: string): Promise<ProjectInfo | null> {
- const entry = await findEntry(dir);
+async function describe(dir: string): Promise<ProjectInfo | null> {
+ const pkg = await readPackage(dir);
+ const entry = await findEntry(dir, pkg);
if (!entry) return null;
+ const name = basename(dir);
const [folder, file] = await Promise.all([stat(dir), stat(join(dir, entry))]);
return {
name,
+ displayName: pkg?.displayName?.trim() || name,
dir,
entry,
modifiedAt: file.mtime.toISOString(),
@@ -89,6 +114,8 @@ async function describe(dir: string, name: string): Promise<ProjectInfo | null>
};
}
+export const getProject = (dir: string): Promise<ProjectInfo | null> => describe(dir);
+
export async function pickRoot(window: BrowserWindow | null): Promise<string | null> {
const options: Electron.OpenDialogOptions = {
title: "Choose projects folder",
@@ -107,7 +134,7 @@ export async function listProjects(root: string): Promise<ProjectInfo[]> {
const projects = await Promise.all(
entries
.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")
- .map((entry) => describe(join(root, entry.name), entry.name)),
+ .map((entry) => describe(join(root, entry.name))),
);
return projects.filter((project): project is ProjectInfo => project !== null);
}
@@ -125,15 +152,16 @@ function packageName(name: string): string {
return cleaned || "diffusion-project";
}
-const packageJson = (name: string): string => `{
- "name": "${packageName(name)}",
- "private": true,
- "type": "module",
- "devDependencies": {
- "solid-js": "^1.9.10"
- }
-}
-`;
+const packageJson = (name: string, displayName: string): PackageJson => ({
+ name: packageName(name),
+ displayName,
+ private: true,
+ type: "module",
+ main: "index.tsx",
+ devDependencies: {
+ "solid-js": "^1.9.10",
+ },
+});
const TSCONFIG = `{
"compilerOptions": {
@@ -190,6 +218,19 @@ async function writeIfMissing(dir: string, name: string, content: string): Promi
await writeFile(path, content, "utf8");
}
+/** Adds the record fields to a package.json that predates them; leaves everything else alone. */
+async function ensurePackage(dir: string, name: string, displayName: string, entry: string): Promise<void> {
+ const pkg = await readPackage(dir);
+ if (!pkg) {
+ await writePackage(dir, { ...packageJson(name, displayName), main: entry });
+ return;
+ }
+ const next = { ...pkg };
+ if (typeof next.displayName !== "string") next.displayName = displayName;
+ if (typeof next.main !== "string") next.main = entry;
+ if (next.displayName !== pkg.displayName || next.main !== pkg.main) await writePackage(dir, next);
+}
+
async function writeIfChanged(dir: string, name: string, content: string): Promise<void> {
const path = join(dir, name);
const current = await readFile(path, "utf8").catch(() => undefined);
@@ -202,28 +243,64 @@ async function writeIfChanged(dir: string, name: string, content: string): Promi
* written once, the generated types are kept in sync. Opening an up-to-date
* project writes nothing.
*/
-export async function scaffold(dir: string, name: string): Promise<void> {
- const entry = await findEntry(dir);
+export async function scaffold(dir: string, displayName = basename(dir)): Promise<void> {
+ const name = basename(dir);
+ let entry = await findEntry(dir);
// JavaScript projects are left alone.
if (entry && !/\.tsx?$/.test(entry)) return;
- if (!entry) await writeIfMissing(dir, "index.tsx", STARTER);
- await writeIfMissing(dir, "package.json", packageJson(name));
+ if (!entry) {
+ await writeIfMissing(dir, "index.tsx", STARTER);
+ entry = "index.tsx";
+ }
+ await ensurePackage(dir, name, displayName, entry);
await writeIfMissing(dir, "tsconfig.json", TSCONFIG);
await writeIfChanged(dir, "jsx.d.ts", TYPES);
}
/** Creates a fresh project folder under `root`. Fails if the folder exists. */
-export async function createProject(root: string, name: string): Promise<ProjectInfo> {
+export async function createProject(root: string, name: string, displayName: string): Promise<ProjectInfo> {
const dir = join(root, name);
if (await exists(dir)) throw new Error(`"${name}" already exists in the projects folder.`);
await mkdir(dir, { recursive: true });
- await scaffold(dir, name);
- const project = await describe(dir, name);
+ await scaffold(dir, displayName);
+ const project = await describe(dir);
if (!project) throw new Error("Failed to scaffold the project.");
return project;
}
+/** Sets the human name (package.json `displayName`). */
+export async function renameProject(dir: string, displayName: string): Promise<ProjectInfo> {
+ const pkg = (await readPackage(dir)) ?? packageJson(basename(dir), displayName);
+ await writePackage(dir, { ...pkg, displayName: displayName.trim() || basename(dir) });
+ const project = await describe(dir);
+ if (!project) throw new Error("Not a project folder.");
+ return project;
+}
+
+/** Copies the folder next to itself as `<name>-copy` (numbered when taken). */
+export async function duplicateProject(dir: string): Promise<ProjectInfo> {
+ const source = await describe(dir);
+ if (!source) throw new Error("Not a project folder.");
+
+ const root = dirname(dir);
+ let name = `${source.name}-copy`;
+ for (let i = 2; await exists(join(root, name)); i++) name = `${source.name}-copy-${i}`;
+ const target = join(root, name);
+
+ await cp(dir, target, { recursive: true, errorOnExist: true, force: false });
+ await renameProject(target, `${source.displayName} (Copy)`);
+ const project = await describe(target);
+ if (!project) throw new Error("Failed to duplicate the project.");
+ return project;
+}
+
+/** Moves the folder to the trash. */
+export async function deleteProject(dir: string): Promise<void> {
+ unwatchProject(dir);
+ await shell.trashItem(dir);
+}
+
// ---------------------------------------------------------------------------
// Compile
@@ -270,7 +347,7 @@ export async function compileProject(dir: string): Promise<CompileResult> {
if (!entry) return { ok: false, error: noEntryError() };
// Generated types may have drifted since the project was created.
- await scaffold(dir, dir.split(sep).pop() ?? "project");
+ await scaffold(dir);
// esbuild resolves symlinks, so the loader has to match on real paths.
const root = await realpath(dir);
diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsx
index 69835518..42a92702 100644
--- a/apps/web/src/components/dashboard/projects-view.tsx
+++ b/apps/web/src/components/dashboard/projects-view.tsx
@@ -37,35 +37,25 @@ import { Icon } from "../ui/icon";
import { track } from "@/lib/analytics";
import {
createProject,
+ deleteProject,
+ duplicateProject,
isDesktop,
listProjects,
pickProjectsRoot,
projectsRoot,
+ renameProject,
type ProjectInfo,
} from "@/projects";
import type { ProjectSortOption } from "./types";
-// Projects live on disk under a user-picked root (see @/projects). Thumbnails,
-// rename, duplicate and delete have no on-disk backing yet: the UI stays, the
-// operations are no-ops until the desktop host grows them.
+// Projects live on disk under a user-picked root (see @/projects); their
+// package.json is the record. Thumbnails have no on-disk backing yet: the UI
+// stays, the lookup is a no-op until the desktop host grows it.
async function getProjectThumbnail(_name: string): Promise<Blob | undefined> {
return undefined;
}
-async function setProjectName(_name: string, _newName: string): Promise<void> {
- // TODO: rename the project folder on disk.
-}
-
-async function duplicateProject(_name: string): Promise<ProjectInfo | null> {
- // TODO: copy the project folder on disk.
- return null;
-}
-
-async function deleteProject(_name: string): Promise<void> {
- // TODO: move the project folder to the trash.
-}
-
export function DashboardProjectsView() {
const navigate = useNavigate();
const [search, setSearch] = createSignal("");
@@ -85,7 +75,7 @@ export function DashboardProjectsView() {
const entries = projects() ?? [];
if (!query) return entries;
- return entries.filter((project) => project.name.toLowerCase().includes(query));
+ return entries.filter((project) => project.displayName.toLowerCase().includes(query));
});
const sortedProjects = createMemo(() => {
@@ -93,7 +83,7 @@ export function DashboardProjectsView() {
const entries = [...filteredProjects()];
if (sortMode === "alphabetical") {
- entries.sort((a, b) => a.name.localeCompare(b.name));
+ entries.sort((a, b) => a.displayName.localeCompare(b.displayName));
return entries;
}
@@ -115,7 +105,7 @@ export function DashboardProjectsView() {
const startRenaming = (project: ProjectInfo) => {
batch(() => {
- setRenameDraft(project.name);
+ setRenameDraft(project.displayName);
setRenamingProject(project.name);
});
};
@@ -125,8 +115,8 @@ export function DashboardProjectsView() {
await deleteProject(project.name);
track('project_deleted');
refetchProjects();
- } catch {
- toast.error("Failed to delete project");
+ } catch (e) {
+ toast.error("Failed to delete project", { description: (e as Error).message });
}
};
@@ -135,8 +125,8 @@ export function DashboardProjectsView() {
await duplicateProject(project.name);
track('project_duplicated');
refetchProjects();
- } catch {
- toast.error("Failed to duplicate project");
+ } catch (e) {
+ toast.error("Failed to duplicate project", { description: (e as Error).message });
}
};
@@ -175,7 +165,11 @@ export function DashboardProjectsView() {
event.stopPropagation();
if (trimmedName.length > 0 && projectName === renamingProject()) {
- await setProjectName(projectName, trimmedName);
+ try {
+ await renameProject(projectName, trimmedName);
+ } catch (e) {
+ toast.error("Failed to rename project", { description: (e as Error).message });
+ }
}
refetchProjects();
@@ -205,7 +199,8 @@ export function DashboardProjectsView() {
}
try {
- const project = await createProject(folderName(generateProjectName()));
+ const displayName = generateProjectName();
+ const project = await createProject(folderName(displayName), displayName);
track('project_created');
refetchProjects();
openProject(project);
@@ -287,7 +282,7 @@ export function DashboardProjectsView() {
when={renamingProject() === project.name}
fallback={
<p class="min-w-0 truncate text-xs text-foreground">
- {project.name}
+ {project.displayName}
</p>
}
>
diff --git a/apps/web/src/components/engine/db/global-db.ts b/apps/web/src/components/engine/db/global-db.ts
index bc217c93..d8c373d3 100644
--- a/apps/web/src/components/engine/db/global-db.ts
+++ b/apps/web/src/components/engine/db/global-db.ts
@@ -30,14 +30,6 @@ export interface Directory {
lastAccessedAt: string;
}
-export interface ProjectEntry {
- id: string;
- name: string;
- createdAt: string;
- lastAccessedAt: string;
- thumbnail?: Blob;
-}
-
export interface GlobalDBSchema extends idb.DBSchema {
directories: {
value: Directory;
@@ -64,13 +56,6 @@ const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {
},
});
-/** Session-only project registry. */
-const projects = new Map<string, ProjectEntry>();
-
-function byLastAccessedDesc<T extends { lastAccessedAt: string }>(a: T, b: T): number {
- return b.lastAccessedAt.localeCompare(a.lastAccessedAt);
-}
-
/**
* Saves the root directory handle to the database.
* If the same handle already exists, it will be updated.
@@ -130,105 +115,3 @@ export async function retrieveDirectoryHandle() {
return await navigator.storage.getDirectory();
}
-
-const PROJECT_ID_PATTERN = /^[A-Za-z0-9_-]{21}$/;
-
-export async function markProjectOpened(projectId: string): Promise<void> {
- if (!PROJECT_ID_PATTERN.test(projectId)) return;
-
- const now = new Date().toISOString();
- const existing = projects.get(projectId);
-
- projects.set(projectId, {
- ...existing,
- id: projectId,
- name: existing?.name ?? generateProjectName(),
- createdAt: existing?.createdAt ?? now,
- lastAccessedAt: now,
- });
-}
-
-export async function createProject(name?: string): Promise<ProjectEntry> {
- const now = new Date().toISOString();
- const entry: ProjectEntry = {
- id: nanoid(),
- name: name?.trim() || generateProjectName(),
- createdAt: now,
- lastAccessedAt: now,
- };
- projects.set(entry.id, entry);
- return entry;
-}
-
-export async function getProjectName(projectId: string): Promise<string> {
- const project = projects.get(projectId);
- // Projects on disk are named by their folder (see @/projects).
- if (!project) return projectId;
-
- return project.name;
-}
-
-export async function getProject(projectId: string): Promise<ProjectEntry | null> {
- if (!PROJECT_ID_PATTERN.test(projectId)) return null;
- return projects.get(projectId) ?? null;
-}
-
-export async function setProjectName(projectId: string, name: string): Promise<void> {
- if (!PROJECT_ID_PATTERN.test(projectId)) return;
-
- const existing = projects.get(projectId);
- const now = new Date().toISOString();
-
- projects.set(projectId, {
- ...existing,
- id: projectId,
- name,
- createdAt: existing?.createdAt ?? now,
- lastAccessedAt: now,
- });
-}
-
-export async function listRecentProjects(limit = 10): Promise<ProjectEntry[]> {
- return Array.from(projects.values()).sort(byLastAccessedDesc).slice(0, limit);
-}
-
-export async function setProjectThumbnail(projectId: string, thumbnail: Blob): Promise<void> {
- if (!PROJECT_ID_PATTERN.test(projectId)) return;
-
- const existing = projects.get(projectId);
- if (!existing) return;
-
- projects.set(projectId, { ...existing, thumbnail });
-}
-
-export async function getProjectThumbnail(projectId: string): Promise<Blob | null> {
- return projects.get(projectId)?.thumbnail ?? null;
-}
-
-export async function duplicateProject(projectId: string): Promise<ProjectEntry | null> {
- if (!PROJECT_ID_PATTERN.test(projectId)) return null;
-
- const source = projects.get(projectId);
- if (!source) return null;
-
- const newProjectId = nanoid();
- const now = new Date().toISOString();
-
- // TODO: copy the project's package/JSX contents once projects live on disk.
- const entry: ProjectEntry = {
- id: newProjectId,
- name: `${source.name} (Copy)`,
- createdAt: now,
- lastAccessedAt: now,
- thumbnail: source.thumbnail,
- };
-
- projects.set(newProjectId, entry);
- return entry;
-}
-
-export async function deleteProject(projectId: string): Promise<void> {
- if (!PROJECT_ID_PATTERN.test(projectId)) return;
-
- projects.delete(projectId);
-}
diff --git a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx
index 622055d6..55d0fa97 100644
--- a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx
+++ b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx
@@ -16,8 +16,8 @@ import { useNavigate } from "@solidjs/router";
import { getAllEntities } from "bitecs";
import { For, Show, createMemo } from "solid-js";
import { toast } from "somoto";
-import { deleteProject, duplicateProject, generateProjectName } from "@/components/engine/db";
-import { createProject, pickProjectsRoot, projectsRoot } from "@/projects";
+import { generateProjectName } from "@/components/engine/db";
+import { createProject, deleteProject, duplicateProject, pickProjectsRoot, projectsRoot } from "@/projects";
import { Not } from "bitecs";
import { ChildOf, isScene, useQuery, loadAsset, changeAssetDirectory, removeAsset, getAssetFile } from "@/components/engine";
import { projectRoute, useProjectId } from "@/hooks/use-project-id";
@@ -34,7 +34,8 @@ export function FileMenu() {
const handleNewProject = async () => {
try {
if (!projectsRoot() && !(await pickProjectsRoot())) return;
- const project = await createProject(folderName(generateProjectName()));
+ const displayName = generateProjectName();
+ const project = await createProject(folderName(displayName), displayName);
navigate(projectRoute(project.name));
} catch (e) {
toast.error("Failed to create project", {
@@ -44,27 +45,20 @@ export function FileMenu() {
};
const handleDuplicateProject = async () => {
- const currentId = projectId();
- if (!currentId) return;
-
try {
- const entry = await duplicateProject(currentId);
- if (!entry) return;
- navigate(projectRoute(entry.id));
- } catch {
- toast.error("Failed to duplicate project");
+ const copy = await duplicateProject(projectId());
+ navigate(projectRoute(copy.name));
+ } catch (e) {
+ toast.error("Failed to duplicate project", { description: (e as Error).message });
}
};
const handleDeleteProject = async () => {
- const currentId = projectId();
- if (!currentId) return;
-
try {
- await deleteProject(currentId);
+ await deleteProject(projectId());
navigate("/?dashboard=projects");
- } catch {
- toast.error("Failed to delete project");
+ } catch (e) {
+ toast.error("Failed to delete project", { description: (e as Error).message });
}
};
@@ -96,10 +90,7 @@ export function FileMenu() {
<DropdownMenuItem onSelect={handleNewProject}>
New project
</DropdownMenuItem>
- <DropdownMenuItem
- disabled={!projectId()}
- onSelect={handleDuplicateProject}
- >
+ <DropdownMenuItem onSelect={handleDuplicateProject}>
Duplicate project
</DropdownMenuItem>
</DropdownMenuGroup>
@@ -145,10 +136,7 @@ export function FileMenu() {
<DropdownMenuSeparator />
<DropdownMenuGroup>
- <DropdownMenuItem
- disabled={!projectId()}
- onSelect={handleDeleteProject}
- >
+ <DropdownMenuItem onSelect={handleDeleteProject}>
Delete project
</DropdownMenuItem>
</DropdownMenuGroup>
diff --git a/apps/web/src/components/sidebar-left/sidebar-left.tsx b/apps/web/src/components/sidebar-left/sidebar-left.tsx
index c7c056d6..14a5e343 100644
--- a/apps/web/src/components/sidebar-left/sidebar-left.tsx
+++ b/apps/web/src/components/sidebar-left/sidebar-left.tsx
@@ -10,7 +10,7 @@ import { Button } from "../ui/button";
import { Icon } from "../ui/icon";
import { ProjectMenu } from "./project-menu";
import { useProjectId } from "@/hooks/use-project-id";
-import { getProjectName, setProjectName } from "../engine/db";
+import { getProjectName, renameProject } from "@/projects";
import { createResource } from "solid-js";
import { cx } from "@/lib/cva";
@@ -52,7 +52,7 @@ type ProjectHeaderProps = {
export function ProjectHeader(props: ProjectHeaderProps) {
const projectId = useProjectId();
const [projectNameDraft, setProjectNameDraft] = createSignal<string | null>(null);
- const [projectName, { refetch: refetchProjectName }] = createResource(() => getProjectName(projectId() ?? "project"));
+ const [projectName, { refetch: refetchProjectName }] = createResource(() => getProjectName(projectId()));
const handleProjectNameInput = (event: InputEvent & { currentTarget: HTMLInputElement }) => {
setProjectNameDraft(event.currentTarget.value);
@@ -74,7 +74,7 @@ export function ProjectHeader(props: ProjectHeaderProps) {
const currentName = projectName() ?? "";
if (trimmedName.length > 0 && trimmedName !== currentName) {
- if (projectId()) await setProjectName(projectId()!, trimmedName);
+ await renameProject(projectId(), trimmedName);
}
refetchProjectName();
diff --git a/apps/web/src/context/engine.tsx b/apps/web/src/context/engine.tsx
index 68364c9c..3cabd1de 100644
--- a/apps/web/src/context/engine.tsx
+++ b/apps/web/src/context/engine.tsx
@@ -5,8 +5,6 @@
import { createEngine, invalidateAssets } from '@/components/engine';
import { clearAudioPeaksCache, clearAudioTrackCache, clearKeyframeIndexCache, clearVideoTrackCache } from '@/components/engine/decoders';
import { clearImageThumbnailCache } from '@/components/engine/timeline/render/image';
-import { markProjectOpened, setProjectThumbnail } from '@/components/engine/db';
-import { captureCanvasThumbnail } from '@/components/engine/thumbnail';
import { assert } from '@/utils';
import { createContext, onCleanup, onMount, useContext, createSignal, Show } from 'solid-js';
import { verifyHandlePermissions } from "@/utils/browser";
@@ -109,9 +107,6 @@ export function EngineProvider(props: EngineProviderProps) {
};
onMount(async () => {
- // Track project in global DB
- markProjectOpened(props.projectId);
-
const canvas = document.getElementById('engine-canvas') as HTMLCanvasElement;
resizeObserver.observe(canvas.parentElement!);
@@ -157,14 +152,6 @@ export function EngineProvider(props: EngineProviderProps) {
onCleanup(() => {
if (readyProjectId === props.projectId) readyProjectId = null;
- // Capture thumbnail before disposing the engine
- const canvas = engine.world.canvas;
- captureCanvasThumbnail(canvas).then((blob) => {
- if (blob) {
- setProjectThumbnail(props.projectId, blob);
- }
- });
-
resizeObserver.disconnect();
engine.dispose();
});
diff --git a/apps/web/src/context/export.tsx b/apps/web/src/context/export.tsx
index f2a2ca3c..d0003009 100644
--- a/apps/web/src/context/export.tsx
+++ b/apps/web/src/context/export.tsx
@@ -7,7 +7,7 @@ import { toast } from "somoto";
import { assert, downloadObject } from "@/utils";
import { useEngine } from "@/context/engine";
import { useProjectId } from "@/hooks/use-project-id";
-import { getProjectName } from "@/components/engine/db/global-db";
+import { getProjectName } from "@/projects";
import { track } from "@/lib/analytics";
import { ExportProgress, type ExportConfig } from "@/components/sidebar-right/inspector/export-progress";
import { renderScene, renderOverlay, cancelRender } from "@/context/render";
@@ -42,7 +42,7 @@ export function ExportProvider(props: { children: JSX.Element }) {
const format = config.format ?? "mp4";
const mimeType = MIME_TYPES[format];
- const name = (await getProjectName(projectId() ?? "project"))
+ const name = (await getProjectName(projectId()))
.replace(/\s+/g, "-")
.toLowerCase();
@@ -131,7 +131,7 @@ export function ExportProvider(props: { children: JSX.Element }) {
return;
}
- const projectName = (await getProjectName(projectId() ?? "project"))
+ const projectName = (await getProjectName(projectId()))
.replace(/\s+/g, "-")
.toLowerCase();
await downloadObject(blob, `${projectName}-frame.png`);
diff --git a/apps/web/src/hooks/use-project-id.ts b/apps/web/src/hooks/use-project-id.ts
index 4f0fefdd..ee80fa60 100644
--- a/apps/web/src/hooks/use-project-id.ts
+++ b/apps/web/src/hooks/use-project-id.ts
@@ -2,26 +2,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-import { z } from 'zod';
import { useParams } from "@solidjs/router";
import { createMemo } from 'solid-js';
-// A project id is the name of a project folder under the projects root
-// (see @/projects), so anything goes except path segments.
-const PROJECT_ID = z.string().min(1).regex(/^(?!\.{1,2}$)[^/\\]+$/);
-
/** Route for the editor with project `name` loaded (see `/projects/*name` in app.tsx). */
export const projectRoute = (name: string): string => `/projects/${encodeURIComponent(name)}`;
/**
- * The project folder name from the `/projects/*name` route, or null when the
- * route carries no valid name. Only meaningful under that route.
+ * The project id: the project folder name from the `/projects/*name` route.
+ * Whether it names a usable folder is decided by `projectDir` in @/projects.
*/
export function useProjectId() {
const params = useParams<{ name?: string }>();
- const projectId = createMemo(() => {
- const { success, data } = PROJECT_ID.safeParse(params.name);
- return success ? data : null;
- });
- return projectId;
+ return createMemo(() => params.name ?? '');
}
diff --git a/apps/web/src/pages/project.tsx b/apps/web/src/pages/project.tsx
index 6b867291..54678771 100644
--- a/apps/web/src/pages/project.tsx
+++ b/apps/web/src/pages/project.tsx
@@ -16,7 +16,7 @@ import { TimelineProvider } from '@/context/timeline';
import { EngineProvider as KootaEngineProvider } from '@/engine';
import { ProjectLoader } from '@/projects';
-/** `/projects/:name` — the editor, with the project folder `name` loaded. */
+/** `/projects/*name` — the editor, with the project folder `name` loaded. */
export function ProjectPage() {
const projectId = useProjectId();
diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.ts
index 6a701060..538c5272 100644
--- a/apps/web/src/projects/host.ts
+++ b/apps/web/src/projects/host.ts
@@ -3,9 +3,10 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Renderer half of on-disk projects. Projects live as folders under a root
-// the user picks once (persisted); the desktop main process scans, scaffolds,
-// compiles, and watches them. Desktop only for now: without the bridge every
-// call rejects and the root is null.
+// the user picks once (persisted); each project's package.json is its record
+// (`displayName`, `main`). The desktop main process scans, scaffolds, renames,
+// copies, trashes, compiles, and watches them. Desktop only for now: without
+// the bridge every call rejects and the root is null.
import { MAIN_CHANNELS } from '@desktop/main-channels';
import { mainBridge } from '@/lib/ipc';
@@ -37,11 +38,44 @@ export async function listProjects(): Promise<ProjectInfo[]> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { root });
}
-/** Creates a new project folder under the root and returns it. */
-export async function createProject(name: string): Promise<ProjectInfo> {
+/** Creates a new project folder `name` (with `displayName` in its package.json) under the root. */
+export async function createProject(name: string, displayName = name): Promise<ProjectInfo> {
const root = projectsRoot();
if (!root) throw new Error('No projects folder selected.');
- return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, name });
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, name, displayName });
+}
+
+/** The project called `name` under the root, or null when there is none. */
+export async function getProject(name: string): Promise<ProjectInfo | null> {
+ const dir = projectDir(name);
+ if (!dir || !isDesktop()) return null;
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_GET, { dir });
+}
+
+/** The human name of project `name` (its folder name when nothing else is known). */
+export async function getProjectName(name: string): Promise<string> {
+ return (await getProject(name).catch(() => null))?.displayName ?? name;
+}
+
+/** Sets the human name of project `name` (package.json `displayName`). */
+export async function renameProject(name: string, displayName: string): Promise<ProjectInfo> {
+ const dir = projectDir(name);
+ if (!dir) throw new Error(`Unknown project "${name}".`);
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_RENAME, { dir, displayName });
+}
+
+/** Copies project `name` next to itself and returns the copy. */
+export async function duplicateProject(name: string): Promise<ProjectInfo> {
+ const dir = projectDir(name);
+ if (!dir) throw new Error(`Unknown project "${name}".`);
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_DUPLICATE, { dir });
+}
+
+/** Moves project `name` to the trash. */
+export async function deleteProject(name: string): Promise<void> {
+ const dir = projectDir(name);
+ if (!dir) throw new Error(`Unknown project "${name}".`);
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_DELETE, { dir });
}
/** Absolute folder of the project called `name` under the current root, or null. */