Skip to content

The VS Code of video editing, built for agents.

TypeScript

Enhance project management with nanoid integration and channel updates

konstantin-pauluse3d7d8415012
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index cb3ead68..f6e26f14 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -39,6 +39,7 @@
"@diffusionstudio/jsx": "*",
"babel-preset-solid": "^1.9.12",
"esbuild": "^0.28.1",
+ "nanoid": "^6.0.1",
"ts-morph": "^28.0.0",
"update-electron-app": "^3.0.0",
"yaml": "^2.9.0"
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index 3e5fba2f..bd70d086 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -43,6 +43,7 @@ export const MAIN_CHANNELS = {
PROJECTS_PICK_ROOT: "projects:pick-root",
PROJECTS_LIST: "projects:list",
PROJECTS_GET: "projects:get",
+ PROJECTS_RESOLVE: "projects:resolve",
PROJECTS_CREATE: "projects:create",
PROJECTS_RENAME: "projects:rename",
PROJECTS_DUPLICATE: "projects:duplicate",
@@ -69,11 +70,17 @@ export const MAIN_CHANNELS = {
/**
* 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.
+ * entry. Its package.json is the project record: `projectId` is what the
+ * project is, `displayName` the human name, `main` the entry file.
*/
export type ProjectInfo = {
- /** Folder name, doubles as the project id. */
+ /**
+ * package.json `projectId`: the project's identity, and the segment its URL
+ * carries. Empty for a folder that predates ids and has not been opened
+ * since — `PROJECTS_RESOLVE` is what gives one out.
+ */
+ id: string;
+ /** Folder name. Renaming the project moves it, so it is not the identity. */
name: string;
/** Human name from package.json `displayName` (falls back to the folder name). */
displayName: string;
@@ -134,10 +141,15 @@ export type MainRequestMap = {
[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_RESOLVE]: {
+ request: { root: string; ref: string };
+ response: ProjectInfo | null;
+ };
[MAIN_CHANNELS.PROJECTS_CREATE]: {
- request: { root: string; name: string; displayName: string };
+ request: { root: string; displayName: string };
response: ProjectInfo;
};
+ // Renames the project: `displayName` in the record, and the folder with it.
[MAIN_CHANNELS.PROJECTS_RENAME]: {
request: { dir: string; displayName: string };
response: ProjectInfo;
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 353ed248..2dd2a74d 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -22,6 +22,7 @@ import {
listProjects,
pickRoot,
renameProject,
+ resolveProject,
unwatchAll,
listEntries,
markSelfWriteAbsolute,
@@ -272,8 +273,9 @@ if (app.requestSingleInstanceLock()) {
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ root }) => listProjects(root));
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_RESOLVE, ({ root, ref }) => resolveProject(root, ref));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, displayName }) =>
+ createProject(root, displayName),
);
mainBridge.handle(MAIN_CHANNELS.PROJECTS_RENAME, ({ dir, displayName }) => renameProject(dir, displayName));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_DUPLICATE, ({ dir }) => duplicateProject(dir));
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 804e7e03..c86ee4d1 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -5,8 +5,8 @@
// 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.
+// The package.json is the project record (`projectId`, `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
@@ -18,6 +18,7 @@ import { watch, type FSWatcher } from "node:fs";
import { cp, mkdir, readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { nanoid } from "nanoid";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import type { TransformOptions } from "@babel/core";
@@ -73,7 +74,12 @@ async function exists(path: string): Promise<boolean> {
}
}
-type PackageJson = { name?: string; displayName?: string; main?: string } & Record<string, unknown>;
+type PackageJson = {
+ name?: string;
+ projectId?: string;
+ displayName?: string;
+ main?: string;
+} & Record<string, unknown>;
async function readPackage(dir: string): Promise<PackageJson | null> {
try {
@@ -87,6 +93,37 @@ async function writePackage(dir: string, pkg: PackageJson): Promise<void> {
await writeFile(join(dir, "package.json"), JSON.stringify(pkg, null, 2) + "\n", "utf8");
}
+// ---------------------------------------------------------------------------
+// Identity
+
+// A project is named twice: `displayName` is what the user calls it and the
+// folder is what the disk calls it, and renaming moves both. Neither can be
+// the project's identity, so the record carries an id that nothing renames —
+// it is what the app's URLs point at, and what the editor keys the open world
+// by. Top level rather than inside `diffusion`, which `writeConfig` replaces
+// whole. A `nanoid()`: 21 url-safe characters, so it takes no encoding to be
+// a path segment.
+
+/** The id a record carries, or "" for a folder that predates them. */
+const recordedId = (pkg: PackageJson | null): string =>
+ typeof pkg?.projectId === "string" ? pkg.projectId.trim() : "";
+
+/**
+ * The project's id, minting and recording one when the folder has none: a
+ * folder made before ids existed, or by hand, gets one the first time the app
+ * opens it (see `resolveProject`).
+ */
+async function ensureProjectId(dir: string): Promise<string> {
+ const pkg = await readPackage(dir);
+ const existing = recordedId(pkg);
+ if (existing) return existing;
+
+ const id = nanoid();
+ markSelfWrite(dir, "package.json");
+ await writePackage(dir, { ...(pkg ?? packageJson(basename(dir), basename(dir))), projectId: id });
+ return id;
+}
+
/** 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;
@@ -109,6 +146,7 @@ async function describe(dir: string): Promise<ProjectInfo | null> {
const name = basename(dir);
const [folder, file] = await Promise.all([stat(dir), stat(join(dir, entry))]);
return {
+ id: recordedId(pkg),
name,
displayName: pkg?.displayName?.trim() || name,
dir,
@@ -132,20 +170,101 @@ export async function pickRoot(window: BrowserWindow | null): Promise<string | n
return filePaths[0];
}
-/** Every direct child folder of `root` that holds an entry file. */
-export async function listProjects(root: string): Promise<ProjectInfo[]> {
+/** Direct child folders of `root` that could hold a project, in a stable order. */
+async function childDirs(root: string): Promise<string[]> {
const entries = await readdir(root, { withFileTypes: true });
- const projects = await Promise.all(
- entries
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")
- .map((entry) => describe(join(root, entry.name))),
- );
+ return entries
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")
+ .map((entry) => entry.name)
+ .sort()
+ .map((name) => join(root, name));
+}
+
+/** Every direct child folder of `root` that holds an entry file. Reads only. */
+export async function listProjects(root: string): Promise<ProjectInfo[]> {
+ const dirs = await childDirs(root);
+ const projects = await Promise.all(dirs.map(describe));
return projects.filter((project): project is ProjectInfo => project !== null);
}
+/**
+ * Where an id was last seen, so opening the project the URL names usually
+ * costs one package.json read instead of a scan of the root. Never trusted
+ * without rereading the file: a stale entry (folder renamed behind our back,
+ * project deleted) just falls through to the scan.
+ */
+const dirsById = new Map<string, string>();
+
+const cacheKey = (root: string, id: string): string => `${root}\n${id}`;
+
+/** Drops every cached id that pointed at `dir` (it moved, or is gone). */
+function forgetDir(dir: string): void {
+ for (const [key, cached] of dirsById) {
+ if (cached === dir) dirsById.delete(key);
+ }
+}
+
+/**
+ * The project `ref` names under `root`: an id first, then a folder name, so
+ * links made before ids existed still open. Whatever is found is left holding
+ * an id — this is where a folder that predates them gets one — and the caller
+ * can send the app to that id's URL.
+ *
+ * Ids live in a file the user can copy, so two folders can end up with the
+ * same one. Nothing here can tell which was meant, so it settles for being
+ * predictable: the cache answers first, so a project stays the one that was
+ * already open, and a cold scan is ordered by folder name.
+ */
+export async function resolveProject(root: string, ref: string): Promise<ProjectInfo | null> {
+ if (!ref) return null;
+
+ const found = async (dir: string): Promise<ProjectInfo | null> => {
+ dirsById.set(cacheKey(root, await ensureProjectId(dir)), dir);
+ return describe(dir);
+ };
+
+ const cached = dirsById.get(cacheKey(root, ref));
+ if (cached && recordedId(await readPackage(cached)) === ref) {
+ const project = await describe(cached);
+ if (project) return project;
+ }
+
+ let dirs: string[];
+ try {
+ dirs = await childDirs(root);
+ } catch {
+ return null;
+ }
+ const ids = await Promise.all(dirs.map(async (dir) => recordedId(await readPackage(dir))));
+
+ const byId = dirs[ids.indexOf(ref)];
+ if (byId) return found(byId);
+
+ const byName = dirs.find((dir) => basename(dir) === ref);
+ return byName ? found(byName) : null;
+}
+
// ---------------------------------------------------------------------------
// Scaffold
+/** Folder-safe project name: "Golden River 15 Aug" -> "golden-river-15-aug". */
+function folderName(name: string): string {
+ return (
+ name
+ .toLowerCase()
+ .replace(/[^a-z0-9._-]+/g, "-")
+ .replace(/^[-.]+|[-.]+$/g, "")
+ .slice(0, 64) || "project"
+ );
+}
+
+/** `base`, or `base-2`, `base-3`... when the folder is taken. */
+async function freeFolder(root: string, base: string): Promise<string> {
+ let name = base;
+ for (let i = 2; await exists(join(root, name)); i++) name = `${base}-${i}`;
+ return name;
+}
+
/** npm names: lowercase, url-safe, no leading dot or underscore, <= 214 chars. */
function packageName(name: string): string {
const cleaned = name
@@ -188,6 +307,7 @@ const SCRIPTS: Record<string, string> = {
const packageJson = (name: string, displayName: string): PackageJson => ({
name: packageName(name),
+ projectId: nanoid(),
displayName,
private: true,
type: "module",
@@ -246,7 +366,7 @@ on the canvas.
| Path | What it is |
| ---- | ---------- |
| \`index.tsx\` | The entry. Its default export renders the composition. |
-| \`package.json\` | The project record: \`displayName\` (the name shown in the app), \`main\` (the entry), \`diffusion\` (how each scene is exported), and the dapi commands as scripts. |
+| \`package.json\` | The project record: \`projectId\` (its identity, kept across renames), \`displayName\` (the name shown in the app), \`main\` (the entry), \`diffusion\` (how each scene is exported), and the dapi commands as scripts. |
| \`tsconfig.json\` | Types for the composition tags, through \`jsxImportSource\`. |
| \`assets.yml\` | The asset library: for every asset its library path, where its bytes are, and what it was found to be. Written by the app; hand edits are read on the next load. |
| \`assets/\` | Files the app produced itself, generations under \`assets/generated/\`. Media imported from elsewhere on disk is linked where it lies, never copied. |
@@ -347,12 +467,19 @@ async function ensurePackage(dir: string, name: string, displayName: string, ent
return;
}
const next = { ...pkg };
+ if (!recordedId(next)) next.projectId = nanoid();
if (typeof next.displayName !== "string") next.displayName = displayName;
if (typeof next.main !== "string") next.main = entry;
// The commands are a menu rather than a record: a project that keeps its own
// scripts is left with them, one with none is given the dapi surface.
if (typeof next.scripts !== "object" || next.scripts === null) next.scripts = { ...SCRIPTS };
- if (next.displayName !== pkg.displayName || next.main !== pkg.main || next.scripts !== pkg.scripts) {
+ if (
+ next.projectId !== pkg.projectId ||
+ next.displayName !== pkg.displayName ||
+ next.main !== pkg.main ||
+ next.scripts !== pkg.scripts
+ ) {
+ markSelfWrite(dir, "package.json");
await writePackage(dir, next);
}
}
@@ -378,10 +505,13 @@ export async function scaffold(dir: string, displayName = basename(dir)): Promis
await writeIfMissing(dir, "README.md", readme(displayName));
}
-/** Creates a fresh project folder under `root`. Fails if the folder exists. */
-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.`);
+/**
+ * Creates a fresh project folder under `root`, named after `displayName`. A
+ * taken name is numbered rather than refused: the folder is a label, the id
+ * inside it is the project.
+ */
+export async function createProject(root: string, displayName: string): Promise<ProjectInfo> {
+ const dir = join(root, await freeFolder(root, folderName(displayName)));
await mkdir(dir, { recursive: true });
await scaffold(dir, displayName);
const project = await describe(dir);
@@ -389,27 +519,72 @@ export async function createProject(root: string, name: string, displayName: str
return project;
}
-/** Sets the human name (package.json `displayName`). */
+/**
+ * Renames the project: the human name in the record, and the folder with it,
+ * so what the user sees in Finder keeps matching what they see in the app.
+ * This is the only thing here that moves a folder — nothing syncs the two
+ * behind the user's back — and it costs the project neither its identity nor
+ * its links, both of which are the id.
+ */
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);
+ const name = displayName.trim() || basename(dir);
+ markSelfWrite(dir, "package.json");
+ await writePackage(dir, { ...pkg, displayName: name });
+
+ const project = await describe(await renameFolder(dir, name));
if (!project) throw new Error("Not a project folder.");
return project;
}
+/**
+ * Moves the project folder to match `displayName`; answers where it ended up.
+ * Best effort by design: the folder can be locked, open elsewhere, or on a
+ * volume that will not have it, and none of that should cost the user the
+ * name they just typed.
+ */
+async function renameFolder(dir: string, displayName: string): Promise<string> {
+ const root = dirname(dir);
+ const base = folderName(displayName);
+ const current = basename(dir);
+ // Already named after it, numbered suffix and all: moving `my-clip-2` to
+ // `my-clip` (or to `my-clip-3`) shuffles folders that are equally right.
+ if (current === base || (current.startsWith(`${base}-`) && /^\d+$/.test(current.slice(base.length + 1)))) {
+ return dir;
+ }
+
+ try {
+ const target = join(root, await freeFolder(root, base));
+ // The watcher holds the old path, and the renderer re-watches the new one
+ // as soon as it hears where the project went.
+ unwatchProject(dir);
+ await rename(dir, target);
+ forgetDir(dir);
+ return target;
+ } catch {
+ return dir;
+ }
+}
+
/** 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);
+ const target = join(root, await freeFolder(root, `${source.name}-copy`));
await cp(dir, target, { recursive: true, errorOnExist: true, force: false });
- await renameProject(target, `${source.displayName} (Copy)`);
+ // The record came along with everything else, id included, and two folders
+ // answering to one id is the thing the id exists to prevent. The folder is
+ // already named for the copy, so the record is written here rather than
+ // through `renameProject` (which would move it again).
+ const pkg = await readPackage(target);
+ await writePackage(target, {
+ ...(pkg ?? packageJson(basename(target), source.displayName)),
+ projectId: nanoid(),
+ displayName: `${source.displayName} (Copy)`,
+ });
const project = await describe(target);
if (!project) throw new Error("Failed to duplicate the project.");
return project;
@@ -419,6 +594,7 @@ export async function duplicateProject(dir: string): Promise<ProjectInfo> {
export async function deleteProject(dir: string): Promise<void> {
unwatchProject(dir);
await shell.trashItem(dir);
+ forgetDir(dir);
}
// ---------------------------------------------------------------------------
diff --git a/apps/web/src/app.tsx b/apps/web/src/app.tsx
index f24209ae..6fef68ae 100644
--- a/apps/web/src/app.tsx
+++ b/apps/web/src/app.tsx
@@ -80,7 +80,7 @@ function App() {
>
<Route path="/auth/callback" component={AuthCallbackPage} />
<Route path="/" component={() => <AuthGate><DashboardPage /></AuthGate>} />
- <Route path="/projects/*name" component={() => <AuthGate><ProjectPage /></AuthGate>} />
+ <Route path="/projects/*ref" component={() => <AuthGate><ProjectPage /></AuthGate>} />
<Route path="*404" component={NotFoundPage} />
</RouterComponent>
);
diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsx
index 91dbf848..d586e02c 100644
--- a/apps/web/src/components/dashboard/projects-view.tsx
+++ b/apps/web/src/components/dashboard/projects-view.tsx
@@ -41,7 +41,7 @@ import {
} from "./shared";
import { DashboardSearchPanel } from "./search-bar";
import { DashboardProjectsFolderBar } from "./projects-folder-bar";
-import { projectRoute } from "@/hooks/use-project-id";
+import { projectRoute } from "@/hooks/use-project-route";
import { Icon } from "../ui/icon";
import { track } from "@/lib/analytics";
import {
@@ -51,6 +51,7 @@ import {
isDesktop,
listProjects,
pickProjectsRoot,
+ projectKey,
projectsRoot,
renameProject,
type ProjectInfo,
@@ -61,7 +62,7 @@ import type { ProjectSortOption } from "./types";
// 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> {
+async function getProjectThumbnail(_id: string): Promise<Blob | undefined> {
return undefined;
}
@@ -109,24 +110,24 @@ export function DashboardProjectsView() {
});
const openProject = (project: ProjectInfo) => {
- if (renamingProject() === project.name) return;
+ if (renamingProject() === project.dir) return;
track('project_opened');
- navigate(projectRoute(project.name));
+ navigate(projectRoute(projectKey(project)));
};
const startRenaming = (project: ProjectInfo) => {
batch(() => {
setRenameDraft(project.displayName);
- setRenamingProject(project.name);
+ setRenamingProject(project.dir);
});
};
const handleDelete = async (project: ProjectInfo) => {
try {
- await deleteProject(project.name);
+ await deleteProject(project.dir);
track('project_deleted');
- setSelectedProject((current) => (current === project.name ? null : current));
+ setSelectedProject((current) => (current === project.dir ? null : current));
refetchProjects();
} catch (e) {
toast.error("Failed to delete project", { description: (e as Error).message });
@@ -148,7 +149,7 @@ export function DashboardProjectsView() {
const handleDuplicate = async (project: ProjectInfo) => {
try {
- await duplicateProject(project.name);
+ await duplicateProject(project.dir);
track('project_duplicated');
refetchProjects();
} catch (e) {
@@ -172,7 +173,7 @@ export function DashboardProjectsView() {
refetchProjects();
};
- const handleKeyDownRenameInput = async (event: KeyboardEvent, projectName: string) => {
+ const handleKeyDownRenameInput = async (event: KeyboardEvent, project: ProjectInfo) => {
const input = event.currentTarget as HTMLInputElement;
const trimmedName = renameDraft()?.trim() ?? "";
@@ -190,9 +191,11 @@ export function DashboardProjectsView() {
event.preventDefault();
event.stopPropagation();
- if (trimmedName.length > 0 && projectName === renamingProject()) {
+ // The folder moves with the name, so the list is refetched below
+ // rather than patched: every path in it has just changed.
+ if (trimmedName.length > 0 && project.dir === renamingProject()) {
try {
- await renameProject(projectName, trimmedName);
+ await renameProject(project.dir, trimmedName);
} catch (e) {
toast.error("Failed to rename project", { description: (e as Error).message });
}
@@ -231,8 +234,7 @@ export function DashboardProjectsView() {
if (!projectsRoot()) return;
}
- const displayName = generateProjectName();
- const project = await createProject(folderName(displayName), displayName);
+ const project = await createProject(generateProjectName());
track('project_created');
refetchProjects();
openProject(project);
@@ -293,24 +295,24 @@ export function DashboardProjectsView() {
<ContextMenu
modal={false}
onOpenChange={(open) => {
- if (open) setSelectedProject(project.name);
+ if (open) setSelectedProject(project.dir);
}}
>
<ContextMenuTrigger as="div" class="contents">
<DashboardCardButton
- active={selectedProject() === project.name}
- onClick={() => setSelectedProject(project.name)}
+ active={selectedProject() === project.dir}
+ onClick={() => setSelectedProject(project.dir)}
onDoubleClick={() => openProject(project)}
onEscape={() => setSelectedProject(null)}
onDelete={() => setPendingDelete(project)}
>
<DashboardCardPreview>
- <ProjectThumbnail name={project.name} />
+ <ProjectThumbnail id={projectKey(project)} />
</DashboardCardPreview>
<div class="flex flex-col gap-1 px-2">
<div class="relative h-4 w-full">
<Show
- when={renamingProject() === project.name}
+ when={renamingProject() === project.dir}
fallback={
<p class="min-w-0 truncate text-xs text-foreground">
{project.displayName}
@@ -325,7 +327,7 @@ export function DashboardProjectsView() {
onInput={handleRenameInput}
onFocus={handleFocusRenameInput}
onBlur={handleBlurRenameInput}
- onKeyDown={(e: KeyboardEvent) => handleKeyDownRenameInput(e, project.name)}
+ onKeyDown={(e: KeyboardEvent) => handleKeyDownRenameInput(e, project)}
placeholder="Project name"
aria-label="Project name"
class="absolute inset-x-0 top-1/2 h-5 w-full -translate-y-1/2 border border-ring bg-input px-1 py-0 ring-1 ring-inset ring-ring"
@@ -395,8 +397,8 @@ export function DashboardProjectsView() {
);
}
-function ProjectThumbnail(props: { name: string }) {
- const [thumbnail] = createResource(() => props.name, getProjectThumbnail);
+function ProjectThumbnail(props: { id: string }) {
+ const [thumbnail] = createResource(() => props.id, getProjectThumbnail);
const url = createMemo(() => {
const blob = thumbnail();
if (!blob) return null;
@@ -428,14 +430,6 @@ const SORT_OPTIONS: Array<{ id: ProjectSortOption; label: string }> = [
const MAX_VISIBLE_PROJECTS = 11;
-/** Folder-safe project name: "Golden River 15 Aug" -> "golden-river-15-aug". */
-function folderName(name: string): string {
- return name
- .toLowerCase()
- .replace(/[^a-z0-9._-]+/g, "-")
- .replace(/^[-.]+|[-.]+$/g, "") || "project";
-}
-
function parseTimestamp(value: string): number {
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? 0 : parsed;
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 304f6e80..b1158972 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
@@ -24,7 +24,8 @@ import { assetName } from "@diffusionstudio/assets";
import { useWorld } from "@diffusionstudio/koota-solid";
import { useLibrary } from "@/engine/library";
import { pickAndImport } from "@/engine/asset-actions";
-import { projectRoute, useProjectId } from "@/hooks/use-project-id";
+import { projectRoute } from "@/hooks/use-project-route";
+import { useProject } from "@/context/project";
import { useEngine } from "@/context/engine";
import { useExport } from "@/context/export";
import { getDefaultExportTemplate } from "@/components/sidebar-right/inspector/export-templates";
@@ -32,15 +33,14 @@ import { mimeTypeToExtension } from "@/utils";
export function FileMenu() {
const navigate = useNavigate();
- const projectId = useProjectId();
+ const project = useProject();
const library = useLibrary();
const handleNewProject = async () => {
try {
if (!projectsRoot() && !(await pickProjectsRoot())) return;
- const displayName = generateProjectName();
- const project = await createProject(folderName(displayName), displayName);
- navigate(projectRoute(project.name));
+ const created = await createProject(generateProjectName());
+ navigate(projectRoute(created.id));
} catch (e) {
toast.error("Failed to create project", {
description: (e as Error).message,
@@ -50,8 +50,8 @@ export function FileMenu() {
const handleDuplicateProject = async () => {
try {
- const copy = await duplicateProject(projectId());
- navigate(projectRoute(copy.name));
+ const copy = await duplicateProject(project.dir());
+ navigate(projectRoute(copy.id));
} catch (e) {
toast.error("Failed to duplicate project", { description: (e as Error).message });
}
@@ -59,7 +59,7 @@ export function FileMenu() {
const handleDeleteProject = async () => {
try {
- await deleteProject(projectId());
+ await deleteProject(project.dir());
navigate("/?dashboard=projects");
} catch (e) {
toast.error("Failed to delete project", { description: (e as Error).message });
@@ -310,11 +310,3 @@ export function FileExportSpecificSceneMenu() {
</DropdownMenuGroup>
);
}
-
-/** Folder-safe project name: "Golden River 15 Aug" -> "golden-river-15-aug". */
-function folderName(name: string): string {
- return name
- .toLowerCase()
- .replace(/[^a-z0-9._-]+/g, "-")
- .replace(/^[-.]+|[-.]+$/g, "") || "project";
-}
diff --git a/apps/web/src/components/sidebar-left/sidebar-left.tsx b/apps/web/src/components/sidebar-left/sidebar-left.tsx
index 14a5e343..a179fce4 100644
--- a/apps/web/src/components/sidebar-left/sidebar-left.tsx
+++ b/apps/web/src/components/sidebar-left/sidebar-left.tsx
@@ -6,12 +6,11 @@ import { Assets } from "./assets";
import { useLayout } from "@/context/layout";
import { useEditorApi } from "@/context/dapi";
import { createSignal, Show } from "solid-js";
+import { toast } from "somoto";
import { Button } from "../ui/button";
import { Icon } from "../ui/icon";
import { ProjectMenu } from "./project-menu";
-import { useProjectId } from "@/hooks/use-project-id";
-import { getProjectName, renameProject } from "@/projects";
-import { createResource } from "solid-js";
+import { useProject } from "@/context/project";
import { cx } from "@/lib/cva";
export function SidebarLeft() {
@@ -50,16 +49,15 @@ type ProjectHeaderProps = {
}
export function ProjectHeader(props: ProjectHeaderProps) {
- const projectId = useProjectId();
+ const project = useProject();
const [projectNameDraft, setProjectNameDraft] = createSignal<string | null>(null);
- const [projectName, { refetch: refetchProjectName }] = createResource(() => getProjectName(projectId()));
const handleProjectNameInput = (event: InputEvent & { currentTarget: HTMLInputElement }) => {
setProjectNameDraft(event.currentTarget.value);
};
const handleFocusNameInput = (event: FocusEvent & { currentTarget: HTMLInputElement }) => {
- setProjectNameDraft(projectName() ?? null);
+ setProjectNameDraft(project.name());
event.currentTarget.select();
};
@@ -71,20 +69,23 @@ export function ProjectHeader(props: ProjectHeaderProps) {
if (event.key === "Enter") {
const input = event.currentTarget;
const trimmedName = projectNameDraft()?.trim() ?? "";
- const currentName = projectName() ?? "";
- if (trimmedName.length > 0 && trimmedName !== currentName) {
- await renameProject(projectId(), trimmedName);
+ // The rename the folder follows: the project keeps its id, so the URL
+ // and the open editor are untouched by the move.
+ if (trimmedName.length > 0 && trimmedName !== project.name()) {
+ try {
+ await project.rename(trimmedName);
+ } catch (e) {
+ toast.error("Failed to rename project", { description: (e as Error).message });
+ }
}
- refetchProjectName();
setProjectNameDraft(null);
input.blur();
}
if (event.key === "Escape") {
event.currentTarget.blur();
- refetchProjectName();
setProjectNameDraft(null);
}
};
@@ -95,7 +96,7 @@ export function ProjectHeader(props: ProjectHeaderProps) {
<div class="flex items-center w-full">
<input
type="text"
- value={projectNameDraft() ?? projectName() ?? ""}
+ value={projectNameDraft() ?? project.name()}
onInput={handleProjectNameInput}
onFocus={handleFocusNameInput}
onBlur={handleBlurNameInput}
diff --git a/apps/web/src/context/dapi/api.tsx b/apps/web/src/context/dapi/api.tsx
index b9ea095f..5daa51d7 100644
--- a/apps/web/src/context/dapi/api.tsx
+++ b/apps/web/src/context/dapi/api.tsx
@@ -5,7 +5,7 @@
import { createEffect, createContext, useContext, onCleanup } from "solid-js";
import { useEngine } from '@/context/engine';
import { useWorld } from '@diffusionstudio/koota-solid';
-import { useProjectId } from '@/hooks/use-project-id';
+import { useProject } from '@/context/project';
import { useAuth } from '@/context/auth';
import { t, q, q0 } from "@/lib/cli-rpc";
import { handleContextGet } from "./context";
@@ -37,7 +37,7 @@ type EditorApiContextValue = {
const EditorApiContext = createContext<EditorApiContextValue>();
export function EditorApiProvider(props: EditorApiProviderProps) {
- const projectId = useProjectId();
+ const project = useProject();
const engine = useEngine();
const auth = useAuth();
const isFullscreen = useFullscreenState();
@@ -57,7 +57,7 @@ export function EditorApiProvider(props: EditorApiProviderProps) {
const world = useWorld();
createEffect(() => {
- if (!window.desktop || !engine.initialized() || projectId() !== engine.world.projectId) return;
+ if (!window.desktop || !engine.initialized() || project.id() !== engine.world.projectId) return;
const router = createAppRouter({ getEngine, world, getUser, requireAuth });
diff --git a/apps/web/src/context/export.tsx b/apps/web/src/context/export.tsx
index d0003009..383d7e25 100644
--- a/apps/web/src/context/export.tsx
+++ b/apps/web/src/context/export.tsx
@@ -6,8 +6,7 @@ import { createContext, useContext, onCleanup, onMount } from "solid-js";
import { toast } from "somoto";
import { assert, downloadObject } from "@/utils";
import { useEngine } from "@/context/engine";
-import { useProjectId } from "@/hooks/use-project-id";
-import { getProjectName } from "@/projects";
+import { useProject } from "@/context/project";
import { track } from "@/lib/analytics";
import { ExportProgress, type ExportConfig } from "@/components/sidebar-right/inspector/export-progress";
import { renderScene, renderOverlay, cancelRender } from "@/context/render";
@@ -29,7 +28,7 @@ const ExportContext = createContext<ExportContextValue>();
export function ExportProvider(props: { children: JSX.Element }) {
const engine = useEngine();
const { world } = engine;
- const projectId = useProjectId();
+ const project = useProject();
const exporting = () => !!renderOverlay();
@@ -42,9 +41,7 @@ export function ExportProvider(props: { children: JSX.Element }) {
const format = config.format ?? "mp4";
const mimeType = MIME_TYPES[format];
- const name = (await getProjectName(projectId()))
- .replace(/\s+/g, "-")
- .toLowerCase();
+ const name = project.name().replace(/\s+/g, "-").toLowerCase();
let target: FileSystemFileHandle;
try {
@@ -131,9 +128,7 @@ export function ExportProvider(props: { children: JSX.Element }) {
return;
}
- const projectName = (await getProjectName(projectId()))
- .replace(/\s+/g, "-")
- .toLowerCase();
+ const projectName = project.name().replace(/\s+/g, "-").toLowerCase();
await downloadObject(blob, `${projectName}-frame.png`);
};
diff --git a/apps/web/src/context/project.tsx b/apps/web/src/context/project.tsx
new file mode 100644
index 00000000..f3077454
--- /dev/null
+++ b/apps/web/src/context/project.tsx
@@ -0,0 +1,64 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * 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/. */
+
+// The open project, for everything that acts on it. A project is three names
+// at once and they come apart: the id is what it *is* (the URL, the key the
+// world is under), the folder is where it lives (and moves, when the project
+// is renamed), and the display name is what the user calls it. Resolving the
+// URL to a project happens once, in ProjectPage; this is that answer, kept
+// current as the project is renamed underneath the editor.
+
+import { createContext, createMemo, createSignal, useContext, type Accessor, type JSX } from 'solid-js';
+
+import { getProject, renameProject } from '@/projects';
+
+import type { ProjectInfo } from '@/projects';
+
+type ProjectContextValue = {
+ /** package.json `projectId`: what the project is, whatever it is called. */
+ id: Accessor<string>;
+ /** Absolute project folder. Moves when the project is renamed. */
+ dir: Accessor<string>;
+ /** package.json `displayName`: what the user calls it. */
+ name: Accessor<string>;
+ /** Renames the project — the record, and the folder with it. */
+ rename: (displayName: string) => Promise<void>;
+ /** Re-reads the record, for when something else wrote it. */
+ refresh: () => Promise<void>;
+};
+
+const ProjectContext = createContext<ProjectContextValue>();
+
+export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Element }) {
+ // Seeded once: the subtree is keyed on the project, so a different one
+ // arrives as a new provider rather than as a new value here.
+ const [info, setInfo] = createSignal(props.project);
+
+ // Memos, not plain reads: `dir` re-mounts the scene when it changes, and a
+ // refresh that found nothing new must not look like a move.
+ const id = createMemo(() => info().id);
+ const dir = createMemo(() => info().dir);
+ const name = createMemo(() => info().displayName);
+
+ const rename = async (displayName: string): Promise<void> => {
+ setInfo(await renameProject(dir(), displayName));
+ };
+
+ const refresh = async (): Promise<void> => {
+ const next = await getProject(dir());
+ if (next) setInfo(next);
+ };
+
+ return (
+ <ProjectContext.Provider value={{ id, dir, name, rename, refresh }}>
+ {props.children}
+ </ProjectContext.Provider>
+ );
+}
+
+export function useProject(): ProjectContextValue {
+ const project = useContext(ProjectContext);
+ if (!project) throw new Error('useProject must be used within a ProjectProvider');
+ return project;
+}
diff --git a/apps/web/src/hooks/use-project-id.ts b/apps/web/src/hooks/use-project-id.ts
deleted file mode 100644
index ee80fa60..00000000
--- a/apps/web/src/hooks/use-project-id.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * 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 { useParams } from "@solidjs/router";
-import { createMemo } from 'solid-js';
-
-/** 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 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 }>();
- return createMemo(() => params.name ?? '');
-}
diff --git a/apps/web/src/hooks/use-project-route.ts b/apps/web/src/hooks/use-project-route.ts
new file mode 100644
index 00000000..4d61af25
--- /dev/null
+++ b/apps/web/src/hooks/use-project-route.ts
@@ -0,0 +1,23 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * 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 { useParams } from "@solidjs/router";
+import { createMemo } from 'solid-js';
+
+/**
+ * Route for the editor with the project `id` loaded (see `/projects/*ref` in
+ * app.tsx). The id, not the folder name: a project keeps it when it is
+ * renamed, so the link keeps working (and so does the restored last route).
+ */
+export const projectRoute = (id: string): string => `/projects/${encodeURIComponent(id)}`;
+
+/**
+ * The `/projects/*ref` segment: a project id, or a folder name for links made
+ * before ids existed. `resolveProject` in @/projects decides which it is; the
+ * editor then rewrites the URL to the id it finds.
+ */
+export function useProjectRef() {
+ const params = useParams<{ ref?: string }>();
+ return createMemo(() => params.ref ?? '');
+}
diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsx
index 6f92b2c9..c6b75ae2 100644
--- a/apps/web/src/pages/editor.tsx
+++ b/apps/web/src/pages/editor.tsx
@@ -19,8 +19,8 @@ import { attachLibrary, isLibraryFile } from '@/engine/library';
import { attachProjectConfig, isProjectConfigFile } from '@/engine/project-config';
import { isCacheFile } from '@diffusionstudio/assets';
import { createEditWriter } from '@/projects/edits';
-import { compileProject, watchProject, projectDir } from '@/projects/host';
-import { useProjectId } from "@/hooks/use-project-id";
+import { compileProject, watchProject } from '@/projects/host';
+import { useProject } from "@/context/project";
import type { Mount } from '@diffusionstudio/reconciler';
import type { EditWriter } from '@/projects/edits';
@@ -31,11 +31,14 @@ export function EditorPage() {
const { uiVisible, timelineMinimized, timelineHeight, setTimelineHeight } = useLayout();
const { isDesktop, isFullscreen } = useEditorApi();
const [resizing, setResizing] = createSignal(false);
- const name = useProjectId();
+ const project = useProject();
const world = useWorld();
+ // Keyed on the folder, not the project: a rename moves it, and everything
+ // below holds a path — the watcher, the library, the writer — so all of it
+ // is torn down and re-attached where the project now is.
createEffect(() => {
- const dir = projectDir(name());
+ const dir = project.dir();
if (!dir) return;
let mounted: Mount | undefined;
@@ -92,10 +95,13 @@ export function EditorPage() {
if (isLibraryFile(path)) {
library.load();
} else {
- // package.json is the config and the record (`main`) in one, so a
- // hand edit to it reloads both; the app's own config writes never
- // reach here (main keeps them from the watcher).
- if (isProjectConfigFile(path)) config.load();
+ // package.json is the config and the record (`main`, `displayName`)
+ // in one, so a hand edit to it reloads both; the app's own config
+ // writes never reach here (main keeps them from the watcher).
+ if (isProjectConfigFile(path)) {
+ config.load();
+ void project.refresh();
+ }
loadProject();
}
});
diff --git a/apps/web/src/pages/project.tsx b/apps/web/src/pages/project.tsx
index a790191c..1a3ee338 100644
--- a/apps/web/src/pages/project.tsx
+++ b/apps/web/src/pages/project.tsx
@@ -2,47 +2,80 @@
* 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 { Show } from 'solid-js';
-import { Navigate } from '@solidjs/router';
+import { Show, createEffect, createMemo, createResource } from 'solid-js';
+import { Navigate, useNavigate } from '@solidjs/router';
import { EditorPage } from './editor';
import { LayoutProvider } from "@/context/layout";
import { PromptInputProvider } from "@/context/prompt-input";
import { EngineProvider } from '@/context/engine';
import { EditorApiProvider } from '@/context/dapi';
import { ExportProvider } from '@/context/export';
-import { useProjectId } from '@/hooks/use-project-id';
+import { ProjectProvider } from '@/context/project';
+import { projectRoute, useProjectRef } from '@/hooks/use-project-route';
+import { resolveProject } from '@/projects';
import { ECSProvider } from '@/context/ecs';
import { TimelineProvider } from '@/context/timeline';
import { EngineProvider as KootaEngineProvider } from '@/engine';
-/** `/projects/*name` — the editor, with the project folder `name` loaded. */
+/** `/projects/*ref` — the editor, with the project `ref` names loaded. */
export function ProjectPage() {
- const projectId = useProjectId();
+ const ref = useProjectRef();
+ const navigate = useNavigate();
+
+ // The ref the project was found for. Rewriting the URL to the id below
+ // changes the ref without changing the project, so the lookup is held on
+ // what it already answered rather than run again — refetching would tear
+ // the editor down and build it back for the project already in it.
+ let resolvedId = '';
+ const target = createMemo<string>((previous) => {
+ const next = ref();
+ return previous && next === resolvedId ? previous : next;
+ }, '');
+
+ // Which folder that is, is main's to answer: the URL carries the project's
+ // id, and the folder it names can be renamed out from under the link.
+ const [project] = createResource(target, resolveProject);
+
+ // The id is the project's address. A URL that named the folder (a link from
+ // before ids, a bookmark from before a rename) is swapped for the canonical
+ // one, so the next rename leaves it alone.
+ createEffect(() => {
+ const id = project()?.id;
+ if (!id) return;
+ resolvedId = id;
+ if (id !== ref()) navigate(projectRoute(id), { replace: true });
+ });
return (
/**
- * using show with keyed to ensure the engine provider is remounted when the project id changes
+ * keyed so the engine provider is remounted when the project changes —
+ * on the project, not on its folder: renaming one must not tear down the
+ * world the user is working in.
*/
- <Show when={projectId()} keyed fallback={<Navigate href="/" />}>
- {(id) => (
- <KootaEngineProvider projectId={id}>
- <EngineProvider projectId={id}>
- <EditorApiProvider>
- <TimelineProvider>
- <ECSProvider>
- <ExportProvider>
- <PromptInputProvider>
- <LayoutProvider>
- <EditorPage />
- </LayoutProvider>
- </PromptInputProvider>
- </ExportProvider>
- </ECSProvider>
- </TimelineProvider>
- </EditorApiProvider>
- </EngineProvider>
- </KootaEngineProvider>
- )}
+ <Show when={!project.loading}>
+ <Show when={project()} keyed fallback={<Navigate href="/" />}>
+ {(found) => (
+ <ProjectProvider project={found}>
+ <KootaEngineProvider projectId={found.id}>
+ <EngineProvider projectId={found.id}>
+ <EditorApiProvider>
+ <TimelineProvider>
+ <ECSProvider>
+ <ExportProvider>
+ <PromptInputProvider>
+ <LayoutProvider>
+ <EditorPage />
+ </LayoutProvider>
+ </PromptInputProvider>
+ </ExportProvider>
+ </ECSProvider>
+ </TimelineProvider>
+ </EditorApiProvider>
+ </EngineProvider>
+ </KootaEngineProvider>
+ </ProjectProvider>
+ )}
+ </Show>
</Show>
)
}
diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.ts
index 030a77b7..4729ee03 100644
--- a/apps/web/src/projects/host.ts
+++ b/apps/web/src/projects/host.ts
@@ -4,9 +4,15 @@
// Renderer half of on-disk projects. Projects live as folders under a root
// 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.
+// (`projectId`, `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.
+//
+// A project is addressed by its folder — an absolute path, which is what main
+// takes — and identified by its id, which is what the app's URLs carry and
+// what survives the folder being renamed. `resolveProject` is the one bridge
+// between the two; callers get the folder from the `ProjectInfo` it answers
+// with (and the open project's from `@/context/project`).
import { MAIN_CHANNELS } from '@desktop/main-channels';
import { mainBridge } from '@/lib/ipc';
@@ -38,55 +44,57 @@ export async function listProjects(): Promise<ProjectInfo[]> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { root });
}
-/** 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> {
+/** Creates a project folder under the root, named after `displayName`. */
+export async function createProject(displayName: string): Promise<ProjectInfo> {
const root = projectsRoot();
if (!root) throw new Error('No projects folder selected.');
- return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, name, displayName });
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, 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 project `ref` names under the root: its id, or — for links made before
+ * ids existed, and folders opened by name — its folder name. What comes back
+ * always carries an id, so the app can put that in the URL.
+ */
+export async function resolveProject(ref: string): Promise<ProjectInfo | null> {
+ const root = projectsRoot();
+ if (!root || !isDesktop()) return null;
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { root, ref });
}
-/** 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;
+/** The project in the folder `dir`, or null when there is none. */
+export async function getProject(dir: string): Promise<ProjectInfo | null> {
+ if (!dir || !isDesktop()) return null;
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_GET, { dir });
}
-/** 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}".`);
+/**
+ * Renames the project: `displayName` in the record, and the folder with it.
+ * The folder moves, so the answer says where the project now lives — hold on
+ * to it. Its id has not changed, and neither has its URL.
+ */
+export async function renameProject(dir: string, displayName: string): Promise<ProjectInfo> {
+ if (!dir) throw new Error('No project folder.');
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}".`);
+/** Copies the project in `dir` next to itself and returns the copy (a new id). */
+export async function duplicateProject(dir: string): Promise<ProjectInfo> {
+ if (!dir) throw new Error('No project folder.');
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}".`);
+/** Moves the project in `dir` to the trash. */
+export async function deleteProject(dir: string): Promise<void> {
+ if (!dir) throw new Error('No project folder.');
return mainBridge.call(MAIN_CHANNELS.PROJECTS_DELETE, { dir });
}
-/** Absolute folder of the project called `name` under the current root, or null. */
-export function projectDir(name: string): string | null {
- const root = projectsRoot();
- if (!root) return null;
- // Names are folder names, never paths.
- if (!name || name === '.' || name === '..' || /[\\/]/.test(name)) return null;
- const separator = root.includes('\\') ? '\\' : '/';
- return `${root}${separator}${name}`;
-}
+/**
+ * What to put in a project's URL: its id, or its folder name while it has
+ * none (a folder that predates ids gets one the next time it is opened).
+ */
+export const projectKey = (project: ProjectInfo): string => project.id || project.name;
export function compileProject(dir: string): Promise<CompileResult> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_COMPILE, { dir });
diff --git a/package-lock.json b/package-lock.json
index f9d25675..c679d21f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -52,6 +52,7 @@
"@diffusionstudio/jsx": "*",
"babel-preset-solid": "^1.9.12",
"esbuild": "^0.28.1",
+ "nanoid": "^6.0.1",
"ts-morph": "^28.0.0",
"update-electron-app": "^3.0.0",
"yaml": "^2.9.0"
@@ -67,6 +68,24 @@
"typescript": "~5.9.3"
}
},
+ "apps/desktop/node_modules/nanoid": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz",
+ "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.js"
+ },
+ "engines": {
+ "node": "^22 || ^24 || >=26"
+ }
+ },
"apps/web": {
"name": "@diffusionstudio/web",
"version": "0.132.1",
diff --git a/reference/context.md b/reference/context.md
index 9758dca1..75c40061 100644
--- a/reference/context.md
+++ b/reference/context.md
@@ -12,7 +12,7 @@ One JSON object:
```ts
{
- projectId: string;
+ projectId: string; // package.json `projectId`, stable across renames
entityCount: number;
scenes: number[]; // ids of the top-level scenes
activeSceneId: number | null; // null if no scene is active