Skip to content

The VS Code of video editing, built for agents.

TypeScript

feat: implement project moving functionality and enhance save location picker

konstantin-paulus83e734a5904f
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index 54d1411f..86c36918 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -13,7 +13,7 @@ import type { LogEntry, ScreenshotResult } from "@diffusionstudio/dapi";
import type { SourceEdit, WriteResult } from "./edit-types";
import type { AgentId } from "./mcp-config";
import type { EditorId, EditorInfo } from "./editors";
-import type { MissingProjectChoice } from "./projects";
+import type { MissingProjectChoice, SaveAction } from "./projects";
export const MAIN_WIRE = {
REQUEST: "main:request",
@@ -57,6 +57,7 @@ export const MAIN_CHANNELS = {
PROJECTS_CREATE: "projects:create",
PROJECTS_PICK_SAVE: "projects:pick-save",
PROJECTS_SAVE: "projects:save",
+ PROJECTS_MOVE: "projects:move",
PROJECTS_RENAME: "projects:rename",
PROJECTS_DUPLICATE: "projects:duplicate",
PROJECTS_DELETE: "projects:delete",
@@ -274,14 +275,19 @@ export type MainRequestMap = {
request: void;
response: ProjectInfo;
};
+ // Where to save a draft, or move a saved project; `name` fills the picker.
[MAIN_CHANNELS.PROJECTS_PICK_SAVE]: {
- request: { dir: string; displayName: string; startIn: string | null };
+ request: { dir: string; name: string; startIn: string | null; action: SaveAction };
response: string | null;
};
[MAIN_CHANNELS.PROJECTS_SAVE]: {
request: { dir: string; target: string };
response: ProjectInfo;
};
+ [MAIN_CHANNELS.PROJECTS_MOVE]: {
+ request: { dir: string; target: string };
+ response: ProjectInfo;
+ };
[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 31f7659c..810c590e 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -36,6 +36,7 @@ import {
renameProject,
resolveProject,
saveProject,
+ moveProject,
unwatchAll,
listEntries,
realPathEntry,
@@ -395,10 +396,11 @@ if (squirrelLaunch) {
askAboutMissingProject(mainWindow, displayName, dir),
);
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, () => createProject());
- mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_SAVE, ({ dir, displayName, startIn }) =>
- pickSaveLocation(mainWindow, dir, displayName, startIn),
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_SAVE, ({ dir, name, startIn, action }) =>
+ pickSaveLocation(mainWindow, dir, name, startIn, action),
);
mainBridge.handle(MAIN_CHANNELS.PROJECTS_SAVE, ({ dir, target }) => saveProject(dir, target));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_MOVE, ({ dir, target }) => moveProject(dir, target));
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).then(deleteProjectChats));
diff --git a/apps/desktop/src/projects.drafts.test.ts b/apps/desktop/src/projects.drafts.test.ts
index bb56ee86..19dafe96 100644
--- a/apps/desktop/src/projects.drafts.test.ts
+++ b/apps/desktop/src/projects.drafts.test.ts
@@ -20,7 +20,8 @@ vi.mock("electron", () => ({
ipcMain: { on: () => { } },
}));
-const { createProject, draftsRoot, duplicateProject, readManifest, saveProject, writeManifest } = await import("./projects");
+const { createProject, draftsRoot, duplicateProject, moveProject, readManifest, saveProject, writeManifest } =
+ await import("./projects");
let root: string;
@@ -83,4 +84,15 @@ describe("drafts", () => {
const saved = await saveProject(draft.dir, join(root, "saved"));
await expect(saveProject(saved.dir, join(root, "again"))).rejects.toThrow(/saved already/);
});
+
+ it("moves a saved project, keeping its name, and refuses to move a draft", async () => {
+ const draft = await createProject();
+ await expect(moveProject(draft.dir, join(root, "elsewhere"))).rejects.toThrow(/Save the draft/);
+
+ const saved = await saveProject(draft.dir, join(root, "My Ad"));
+ const target = join(root, "Archive", "Ad Folder");
+ const moved = await moveProject(saved.dir, target);
+ expect(moved).toMatchObject({ id: draft.id, dir: target, name: "Ad Folder", displayName: "My Ad", draft: false });
+ expect(await readdir(root)).not.toContain("My Ad");
+ });
});
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 433ea4f3..c2eb0d1b 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -205,7 +205,7 @@ async function defaultSaveFolder(): Promise<string> {
/** Characters no folder name can hold on one platform or another. */
const UNSAFE_NAME = /[\\/:*?"<>|]+/g;
-/** Why the draft in `dir` cannot be saved as `target`, or null when it can. */
+/** Why the project in `dir` cannot be saved or moved as `target`, or null when it can. */
async function saveProblem(dir: string, target: string): Promise<string | null> {
if (await exists(target)) {
return `"${basename(target)}" already exists in ${basename(dirname(target))}. Choose another name.`;
@@ -216,25 +216,30 @@ async function saveProblem(dir: string, target: string): Promise<string | null>
return null;
}
+/** What the save picker is asked for: saving a draft, or moving a saved project. */
+export type SaveAction = "save" | "move";
+
/**
- * Asks where to save the draft in `dir`: the folder it will become, or null
- * when the user cancels. Starts in `startIn` — the parent of the last
- * project saved — with the project's name filled in. A name that is taken is
- * refused rather than replaced, and a synced folder is warned about; either
- * way the picker comes back, since the user came here to save.
+ * Asks where to save the draft in `dir`, or where to move the project there:
+ * the folder it will become, or null when the user cancels. Starts in
+ * `startIn` — the parent of the last project saved — with `name` filled in.
+ * A name that is taken is refused rather than replaced, and a synced folder
+ * is warned about; either way the picker comes back, since the user came here
+ * to save.
*/
export async function pickSaveLocation(
window: BrowserWindow | null,
dir: string,
- displayName: string,
+ name: string,
startIn: string | null,
+ action: SaveAction = "save",
): Promise<string | null> {
const start = startIn && (await stat(startIn).catch(() => null))?.isDirectory() ? startIn : await defaultSaveFolder();
- const name = displayName.replace(UNSAFE_NAME, "-").trim() || basename(dir);
+ const folder = name.replace(UNSAFE_NAME, "-").trim() || basename(dir);
const options: Electron.SaveDialogOptions = {
- title: "Save project",
- buttonLabel: "Save",
- defaultPath: join(start, name),
+ title: action === "move" ? "Move project" : "Save project",
+ buttonLabel: action === "move" ? "Move" : "Save",
+ defaultPath: join(start, folder),
properties: ["createDirectory", "showOverwriteConfirmation"],
};
@@ -247,7 +252,11 @@ export async function pickSaveLocation(
const problem = await saveProblem(dir, filePath);
if (problem) {
- const message: Electron.MessageBoxOptions = { type: "warning", message: "Can't save here", detail: problem };
+ const message: Electron.MessageBoxOptions = {
+ type: "warning",
+ message: action === "move" ? "Can't move here" : "Can't save here",
+ detail: problem,
+ };
if (window) await dialog.showMessageBox(window, message);
else await dialog.showMessageBox(message);
continue;
@@ -887,6 +896,25 @@ export async function duplicateProject(dir: string): Promise<ProjectInfo> {
*/
export async function saveProject(dir: string, target: string): Promise<ProjectInfo> {
if (!isDraft(dir)) throw new Error("This project is saved already.");
+ await moveFolder(dir, target);
+ return renameProject(target, basename(target));
+}
+
+/**
+ * Moves the saved project in `dir` to `target`, as saving moves a draft —
+ * but it keeps its name, which is the user's already. A draft is saved
+ * rather than moved.
+ */
+export async function moveProject(dir: string, target: string): Promise<ProjectInfo> {
+ if (isDraft(dir)) throw new Error("Save the draft instead of moving it.");
+ await moveFolder(dir, target);
+ const project = await describe(target);
+ if (!project) throw new Error("Failed to move the project.");
+ return project;
+}
+
+/** Moves the project folder `dir` to `target`, once whatever is on its way into it has landed. */
+async function moveFolder(dir: string, target: string): Promise<void> {
if (!isAbsolute(target)) throw new Error(`The project folder must be an absolute path (got "${target}").`);
const problem = await saveProblem(dir, target);
if (problem) throw new Error(problem);
@@ -902,7 +930,6 @@ export async function saveProject(dir: string, target: string): Promise<ProjectI
await cp(dir, target, { recursive: true, errorOnExist: true, force: false });
await rm(dir, { recursive: true, force: true });
}
- return renameProject(target, basename(target));
}
/**
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 8f5fa061..5269d3b7 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
@@ -13,10 +13,21 @@ import {
DropdownMenuGroup,
} from "@/components/ui/dropdown-menu";
import { useLocation, useNavigate } from "@solidjs/router";
-import { For, Show, createMemo } from "solid-js";
+import { For, Show, createMemo, createResource } from "solid-js";
import { toast } from "somoto";
import { forgetProjectBundle } from "@/lib/db";
-import { createProject, deleteProject, duplicateProject } from "@/projects";
+import {
+ createProject,
+ deleteProject,
+ duplicateProject,
+ isWindowsDesktop,
+ listProjects,
+ openProjectFolder,
+ pickProjectFolder,
+ projectKey,
+ projectsRevision,
+} from "@/projects";
+import { listEditors, openInEditor, revealPath } from "@/lib/shell";
import { AssetId, ChildOf, Name, Root, Scene, getAssetFile, getActiveEntity, sortByItemIndex } from "@diffusionstudio/runtime";
import { assetName } from "@diffusionstudio/assets";
import { useQuery, useWorld } from "@diffusionstudio/koota-solid";
@@ -26,17 +37,26 @@ import { projectRoute } from "@/hooks/use-project-route";
import { useProject } from "@/context/project";
import { useExport } from "@/context/export";
import { getDefaultExportTemplate } from "@/components/sidebar-right/inspector/export-templates";
+import { openProjectFromList } from "@/components/dashboard/shared";
import { mimeTypeToExtension } from "@/utils";
import type { Entity } from "koota";
+import type { EditorInfo } from "@/lib/shell";
+import type { ProjectRecord } from "@/projects";
-export function FileMenu() {
+/** How many projects Open recent lists. */
+const RECENT_PROJECTS = 10;
+
+/**
+ * The File commands that have a key as well as an item: the menu offers them,
+ * and `ProjectMenu` binds their keys, since the menu is only mounted while open.
+ */
+export function useFileCommands() {
const navigate = useNavigate();
const location = useLocation();
const project = useProject();
- const library = useLibrary();
- const handleNewProject = async () => {
+ const newProject = async () => {
try {
const created = await createProject();
navigate(projectRoute(created.id), { state: location.state });
@@ -47,7 +67,18 @@ export function FileMenu() {
}
};
- const handleDuplicateProject = async () => {
+ const openProject = async () => {
+ try {
+ const dir = await pickProjectFolder();
+ if (!dir) return;
+ const opened = await openProjectFolder(dir);
+ navigate(projectRoute(projectKey(opened)), { state: location.state });
+ } catch (e) {
+ toast.error("Failed to open project", { description: (e as Error).message });
+ }
+ };
+
+ const duplicate = async () => {
try {
const copy = await duplicateProject(project.dir());
navigate(projectRoute(copy.id), { state: location.state });
@@ -56,6 +87,48 @@ export function FileMenu() {
}
};
+ return { newProject, openProject, duplicate };
+}
+
+export function FileMenu() {
+ const navigate = useNavigate();
+ const project = useProject();
+ const library = useLibrary();
+ const commands = useFileCommands();
+ const [editors] = createResource(listEditors, { initialValue: [] });
+
+ const handleSave = async () => {
+ try {
+ await project.save();
+ } catch (e) {
+ toast.error("Failed to save project", { description: (e as Error).message });
+ }
+ };
+
+ const handleMove = async () => {
+ try {
+ await project.move();
+ } catch (e) {
+ toast.error("Failed to move project", { description: (e as Error).message });
+ }
+ };
+
+ const handleReveal = async () => {
+ try {
+ await revealPath(project.dir());
+ } catch (e) {
+ toast.error("Failed to show the folder", { description: (e as Error).message });
+ }
+ };
+
+ const handleOpenInEditor = async (editor: EditorInfo) => {
+ try {
+ await openInEditor(editor.id, project.dir());
+ } catch (e) {
+ toast.error(`Failed to open in ${editor.label}`, { description: (e as Error).message });
+ }
+ };
+
const handleDeleteProject = async () => {
try {
await deleteProject(project.dir());
@@ -78,23 +151,64 @@ export function FileMenu() {
return (
<>
<DropdownMenuGroup>
- <DropdownMenuItem onSelect={handleNewProject}>
- New project
+ <DropdownMenuItem onSelect={commands.newProject}>
+ New
+ <DropdownMenuShortcut>⌘N</DropdownMenuShortcut>
</DropdownMenuItem>
- <DropdownMenuItem onSelect={handleDuplicateProject}>
- Duplicate project
+ <DropdownMenuItem onSelect={commands.openProject}>
+ Open...
+ <DropdownMenuShortcut>⌘O</DropdownMenuShortcut>
</DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Open recent</DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent class="w-[196px]">
+ <FileRecentMenu />
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ </DropdownMenuGroup>
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuGroup>
+ <DropdownMenuItem onSelect={handleSave} disabled={!project.draft()}>
+ Save...
+ <DropdownMenuShortcut>⌘S</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={commands.duplicate}>
+ Duplicate...
+ <DropdownMenuShortcut>⇧⌘S</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={handleMove} disabled={project.draft()}>
+ Move to...
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuGroup>
+ <DropdownMenuItem onSelect={handleReveal}>
+ {isWindowsDesktop() ? "Show in Explorer" : "Show in Finder"}
+ </DropdownMenuItem>
+ <For each={editors()}>
+ {(editor) => (
+ <DropdownMenuItem onSelect={() => handleOpenInEditor(editor)}>
+ Open in {editor.label}
+ </DropdownMenuItem>
+ )}
+ </For>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem onSelect={handleImportFromComputer}>
- Import from computer...
+ Import assets...
<DropdownMenuShortcut>⌘I</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuSub>
- <DropdownMenuSubTrigger>Asset</DropdownMenuSubTrigger>
+ <DropdownMenuSubTrigger>Assets</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent class="w-[196px]">
<FileAssetMenu />
@@ -127,6 +241,41 @@ export function FileMenu() {
);
}
+/**
+ * The projects opened last, the open one aside. Mounts with the submenu, so
+ * the list is read when it opens.
+ */
+export function FileRecentMenu() {
+ const navigate = useNavigate();
+ const location = useLocation();
+ const project = useProject();
+ const [projects] = createResource(projectsRevision, listProjects, { initialValue: [] });
+ const recent = createMemo(() =>
+ projects().filter((record) => record.dir !== project.dir()).slice(0, RECENT_PROJECTS)
+ );
+
+ const handleOpen = async (record: ProjectRecord) => {
+ const found = await openProjectFromList(record);
+ if (!found) return;
+ navigate(projectRoute(projectKey(found)), { state: location.state });
+ };
+
+ return (
+ <DropdownMenuGroup>
+ <For
+ each={recent()}
+ fallback={<DropdownMenuItem disabled>No recent projects</DropdownMenuItem>}
+ >
+ {(record) => (
+ <DropdownMenuItem onSelect={() => handleOpen(record)}>
+ <span class="min-w-0 flex-1 truncate">{record.displayName}</span>
+ </DropdownMenuItem>
+ )}
+ </For>
+ </DropdownMenuGroup>
+ );
+}
+
export function FileAssetMenu() {
const world = useWorld();
const library = useLibrary();
diff --git a/apps/web/src/components/sidebar-left/project-menu/folder-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/folder-menu.tsx
deleted file mode 100644
index bccc5c3f..00000000
--- a/apps/web/src/components/sidebar-left/project-menu/folder-menu.tsx
+++ /dev/null
@@ -1,75 +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 { For, Show, createResource } from "solid-js";
-import { toast } from "somoto";
-import {
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuShortcut,
-} from "@/components/ui/dropdown-menu";
-import { useProject } from "@/context/project";
-import { listEditors, openInEditor, revealPath } from "@/lib/shell";
-import { isWindowsDesktop } from "@/projects";
-
-import type { EditorInfo } from "@/lib/shell";
-
-/** What can be done with the project's folder. */
-export function FolderMenu() {
- const project = useProject();
- const [editors] = createResource(listEditors, { initialValue: [] });
-
- const handleSaveFolder = async () => {
- try {
- await project.save();
- } catch (e) {
- toast.error("Failed to save project", { description: (e as Error).message });
- }
- };
-
- const handleReveal = async () => {
- try {
- await revealPath(project.dir());
- } catch (e) {
- toast.error("Failed to show the folder", { description: (e as Error).message });
- }
- };
-
- const handleOpenInEditor = async (editor: EditorInfo) => {
- try {
- await openInEditor(editor.id, project.dir());
- } catch (e) {
- toast.error(`Failed to open in ${editor.label}`, { description: (e as Error).message });
- }
- };
-
- return (
- <>
- <DropdownMenuGroup>
- <DropdownMenuItem onSelect={handleSaveFolder} disabled={!project.draft()}>
- Save folder...
- <DropdownMenuShortcut>⌘S</DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={handleReveal}>
- {isWindowsDesktop() ? "Show in Explorer" : "Show in Finder"}
- </DropdownMenuItem>
- </DropdownMenuGroup>
-
- <Show when={editors().length > 0}>
- <DropdownMenuSeparator />
-
- <DropdownMenuGroup>
- <For each={editors()}>
- {(editor) => (
- <DropdownMenuItem onSelect={() => handleOpenInEditor(editor)}>
- Open in {editor.label}
- </DropdownMenuItem>
- )}
- </For>
- </DropdownMenuGroup>
- </Show>
- </>
- );
-}
diff --git a/apps/web/src/components/sidebar-left/project-menu/index.tsx b/apps/web/src/components/sidebar-left/project-menu/index.tsx
index 956f1d31..1ea745c2 100644
--- a/apps/web/src/components/sidebar-left/project-menu/index.tsx
+++ b/apps/web/src/components/sidebar-left/project-menu/index.tsx
@@ -22,8 +22,7 @@ import { isInputTarget } from "@/utils";
import { useEditorApi } from "@/dapi";
import { desktopAppPlatformLabel, downloadDesktopApp } from "@/lib/desktop-app";
import type { ProjectRouteState } from "@/hooks/use-project-route";
-import { FileMenu } from "./file-menu";
-import { FolderMenu } from "./folder-menu";
+import { FileMenu, useFileCommands } from "./file-menu";
import { EditMenu } from "./edit-menu";
import { ViewMenu } from "./view-menu";
import { ToolMenu } from "./tool-menu";
@@ -34,6 +33,7 @@ export function ProjectMenu() {
const navigate = useNavigate();
const location = useLocation<ProjectRouteState>();
const { isDesktop } = useEditorApi();
+ const fileCommands = useFileCommands();
const handleOpenDashboard = () => {
(document.activeElement as HTMLElement)?.blur?.();
@@ -46,15 +46,28 @@ export function ProjectMenu() {
};
/**
- * Leaving the editor is the app's command rather than the runtime's, so its
- * key is bound here, with the item that offers it.
+ * Leaving the editor, and the File commands that open or make another
+ * project, are the app's rather than the runtime's, so their keys are bound
+ * here, with the menu that offers them. ⌘S is the project's own (see
+ * `ProjectProvider`).
*/
const handleShortcut = (event: KeyboardEvent) => {
- if (!(event.metaKey || event.ctrlKey) || !event.shiftKey) return;
- if (event.key.toLowerCase() !== "d" || isInputTarget(event)) return;
-
- event.preventDefault();
- handleOpenDashboard();
+ if (!(event.metaKey || event.ctrlKey) || event.altKey || isInputTarget(event)) return;
+
+ const key = event.key.toLowerCase();
+ if (event.shiftKey && key === "d") {
+ event.preventDefault();
+ handleOpenDashboard();
+ } else if (event.shiftKey && key === "s") {
+ event.preventDefault();
+ fileCommands.duplicate();
+ } else if (!event.shiftKey && key === "n") {
+ event.preventDefault();
+ fileCommands.newProject();
+ } else if (!event.shiftKey && key === "o") {
+ event.preventDefault();
+ fileCommands.openProject();
+ }
};
onMount(() => {
@@ -96,15 +109,6 @@ export function ProjectMenu() {
</DropdownMenuPortal>
</DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>Folder</DropdownMenuSubTrigger>
- <DropdownMenuPortal>
- <DropdownMenuSubContent class="w-[196px]">
- <FolderMenu />
- </DropdownMenuSubContent>
- </DropdownMenuPortal>
- </DropdownMenuSub>
-
<DropdownMenuSub>
<DropdownMenuSubTrigger>Edit</DropdownMenuSubTrigger>
<DropdownMenuPortal>
diff --git a/apps/web/src/components/sidebar-left/sidebar-left.tsx b/apps/web/src/components/sidebar-left/sidebar-left.tsx
index 11fdb634..19e7fb49 100644
--- a/apps/web/src/components/sidebar-left/sidebar-left.tsx
+++ b/apps/web/src/components/sidebar-left/sidebar-left.tsx
@@ -185,7 +185,7 @@ function DraftBadge() {
>
Draft
</TooltipTrigger>
- <TooltipContent shortcut={isWindowsDesktop() ? "Ctrl+S" : "⌘S"}>Save folder</TooltipContent>
+ <TooltipContent shortcut={isWindowsDesktop() ? "Ctrl+S" : "⌘S"}>Save</TooltipContent>
</Tooltip>
</Show>
);
diff --git a/apps/web/src/context/project.tsx b/apps/web/src/context/project.tsx
index ce75b18b..c2fc5b67 100644
--- a/apps/web/src/context/project.tsx
+++ b/apps/web/src/context/project.tsx
@@ -7,12 +7,13 @@
// world is under), the folder is where it lives, 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, and as a draft is saved and its folder moves.
+// underneath the editor, and as a draft is saved or a project is moved and its
+// folder goes with it.
import { createContext, createMemo, createSignal, onCleanup, onMount, useContext, type Accessor, type JSX } from 'solid-js';
import { toast } from 'somoto';
-import { pickSaveLocation, refreshProject, renameProject, saveProject } from '@/projects';
+import { moveProject, pickSaveLocation, refreshProject, renameProject, saveProject } from '@/projects';
import type { ProjectInfo } from '@/projects';
@@ -35,6 +36,12 @@ export type ProjectContextValue = {
* cancelled.
*/
save: () => Promise<boolean>;
+ /**
+ * Moves a saved project: asks where, and moves its folder there. False
+ * when there was nothing to move (a draft, a move already running) or the
+ * user cancelled.
+ */
+ move: () => Promise<boolean>;
};
const ProjectContext = createContext<ProjectContextValue>();
@@ -49,6 +56,7 @@ export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Ele
// flushes what it still owes as it goes — on `dir`, so an empty one lets
// go of the folder, and the new one attaches it all again where it went.
const [moving, setMoving] = createSignal(false);
+ // One save or move at a time: both move the folder.
let saving = false;
// Memos, not plain reads: a refresh that found nothing new must not look
@@ -89,6 +97,26 @@ export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Ele
}
};
+ const move = async (): Promise<boolean> => {
+ if (draft() || saving) return false;
+ saving = true;
+ try {
+ const from = info().dir;
+ const target = await pickSaveLocation(from, info().name, 'move');
+ if (!target) return false;
+
+ setMoving(true);
+ try {
+ setInfo(await moveProject(from, target));
+ } finally {
+ setMoving(false);
+ }
+ return true;
+ } finally {
+ saving = false;
+ }
+ };
+
/** ⌘S saves a draft. A saved project is written as it is edited, so there it does nothing. */
const handleShortcut = async (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.shiftKey || event.altKey) return;
@@ -107,7 +135,7 @@ export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Ele
onCleanup(() => window.removeEventListener('keydown', handleShortcut));
return (
- <ProjectContext.Provider value={{ id, dir, draft, name, rename, refresh, save }}>
+ <ProjectContext.Provider value={{ id, dir, draft, name, rename, refresh, save, move }}>
{props.children}
</ProjectContext.Provider>
);
diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.ts
index 263b636e..e7224724 100644
--- a/apps/web/src/projects/host.ts
+++ b/apps/web/src/projects/host.ts
@@ -186,12 +186,13 @@ export async function createProject(collectionId?: string): Promise<ProjectInfo>
}
/**
- * Asks where to save the draft in `dir`, starting where the last project was
- * saved: the folder it will become, or null when the user cancels. Moves
- * nothing yet.
+ * Asks where to save the draft in `dir` — or, for `move`, where to move the
+ * saved project there — starting where the last project was saved, with
+ * `name` filled in: the folder it will become, or null when the user cancels.
+ * Moves nothing yet.
*/
-export function pickSaveLocation(dir: string, displayName: string): Promise<string | null> {
- return mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_SAVE, { dir, displayName, startIn: saveFolder() });
+export function pickSaveLocation(dir: string, name: string, action: 'save' | 'move' = 'save'): Promise<string | null> {
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_SAVE, { dir, name, startIn: saveFolder(), action });
}
/** The folder `path` is in. */
@@ -211,6 +212,19 @@ export async function saveProject(dir: string, target: string): Promise<ProjectI
return project;
}
+/**
+ * Moves the saved project in `dir` to `target` (from `pickSaveLocation`) and
+ * answers with the project where it now lives; its name stays. The list
+ * follows the folder, as it does a save — and so does the next save picker.
+ */
+export async function moveProject(dir: string, target: string): Promise<ProjectInfo> {
+ const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_MOVE, { dir, target });
+ await moveProjectRecord(dir, project.dir);
+ await remember(project);
+ storeSaveFolder(parentOf(project.dir));
+ return project;
+}
+
/**
* The project `ref` names: its id, or — for links made before ids existed,
* and folders opened by name — its folder name. Only projects on the list