Open source CapCut alternative.
TypeScript
feat(site): choose where a new project lands
David Le941b870dd7ce
diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsxindex 6e6cd962..8cf27372 100644--- a/site/src/cut/components/AppSidebar.tsx+++ b/site/src/cut/components/AppSidebar.tsx@@ -4,7 +4,7 @@ import { useState } from "react";import { useQueryClient } from "@tanstack/react-query";import Link from "next/link";import { usePathname, useRouter } from "next/navigation";-import { Clapperboard, FolderOpen, Loader2, Plus } from "lucide-react";+import { Clapperboard, FolderOpen, Loader2 } from "lucide-react";import { Button } from "@/components/ui/button";import {Dialog,@@ -14,11 +14,12 @@ import {DialogTitle,} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";-import { apiFetch, getBackend } from "@/cut/lib/backend";import { seedNewProjectDoc } from "@/cut/lib/docCache";import { patchProjects } from "@/cut/lib/queries";+import { backendFor, type Residency } from "@/cut/lib/residency";import { track } from "@/lib/analytics";import { NavStorage } from "@/cut/components/NavStorage";+import { NewProjectButton } from "@/cut/components/NewProjectButton";import { NavUser } from "@/cut/components/NavUser";import { homeHref, projectHref, tabForPath, useCutBase, type CutTab } from "@/cut/lib/nav";import type { ProjectSummary } from "@/cut/lib/types";@@ -34,30 +35,32 @@ export function AppSidebar() {const router = useRouter();const base = useCutBase();const client = useQueryClient();- const [createOpen, setCreateOpen] = useState(false);+ // The residency the pending creation was launched for; null when the naming+ // dialog is closed.+ const [createIn, setCreateIn] = useState<Residency | null>(null);const [name, setName] = useState("");const [busy, setBusy] = useState(false);- const create = async () => {+ const create = async (r: Residency) => {setBusy(true);try {- const res = await apiFetch("/api/cut/projects", {+ const res = await backendFor(r).fetch("/api/cut/projects", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: name.trim() || "Untitled" }),});const project = (await res.json()) as ProjectSummary;- const kind = getBackend().kind;- patchProjects(client, kind === "cloud" ? "cloud" : "local", (s) => ({+ patchProjects(client, r, (s) => ({...s,projects: [project, ...s.projects],}));// A brand-new project's document is empty, so the editor about to open// needs no round trip to draw it.- seedNewProjectDoc(project.id, project.name, kind);+ seedNewProjectDoc(project.id, project.name, r);track("project_created", { source: "sidebar" });- // The sidebar creates on the globally bound backend, so the link carries- // that residency.+ // The link carries no residency; the editor resolves it by asking which+ // backend owns the id, so a cloud project created from a Mac still opens+ // against the cloud.router.push(projectHref(base, project.id, tabForPath(pathname), null));} finally {setBusy(false);@@ -79,15 +82,13 @@ export function AppSidebar() {<span className="text-[17px] font-semibold tracking-tight">Donkey Cut</span></div>- <Button+ <NewProjectButtonclassName="mb-5 w-full"- onClick={() => {+ onCreate={(r) => {setName("");- setCreateOpen(true);+ setCreateIn(r);}}- >- <Plus data-icon="inline-start" /> New project- </Button>+ /><nav className="flex flex-col gap-0.5">{NAV.map(({ tab, label, icon: Icon }) => {@@ -112,7 +113,7 @@ export function AppSidebar() {<NavStorage /><NavUser /></div>- <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <Dialog open={createIn !== null} onOpenChange={(o) => !o && setCreateIn(null)}><DialogContent className="sm:max-w-sm"><DialogHeader><DialogTitle>New project</DialogTitle>@@ -120,7 +121,7 @@ export function AppSidebar() {<formonSubmit={(e) => {e.preventDefault();- void create();+ if (createIn) void create(createIn);}}><Inputdiff --git a/site/src/cut/components/NewProjectButton.tsx b/site/src/cut/components/NewProjectButton.tsxnew file mode 100644index 00000000..e8920f2d--- /dev/null+++ b/site/src/cut/components/NewProjectButton.tsx@@ -0,0 +1,79 @@+"use client";++import { ChevronDown, Cloud, Laptop, Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { useNewProjectTarget } from "@/cut/lib/newProject";+import { RESIDENCY_LABEL, type Residency } from "@/cut/lib/residency";+import { cn } from "@/lib/utils";++const RESIDENCY_ICON: Record<Residency, typeof Cloud> = { local: Laptop, cloud: Cloud };++/**+ * Make a project, and say where it will land.+ *+ * The chevron is the residency choice, and it appears only when there is one+ * to make. Without the Donkey app running this Mac has no shelf, so every+ * project is a cloud project and this is a plain button. A folder pins its own+ * residency, since a project files only into a folder beside it.+ */+export function NewProjectButton({+ pinned = null,+ onCreate,+ className,+}: {+ pinned?: Residency | null;+ onCreate: (r: Residency) => void;+ className?: string;+}) {+ const { target, choices, pick } = useNewProjectTarget();+ const r = pinned ?? target;+ const Icon = RESIDENCY_ICON[r];++ if (pinned || choices.length < 2) {+ return (+ <Button className={className} onClick={() => onCreate(r)}>+ <Plus data-icon="inline-start" /> New project+ </Button>+ );+ }++ return (+ <div className={cn("flex", className)}>+ <Button className="min-w-0 flex-1 rounded-r-none" onClick={() => onCreate(r)}>+ <Plus data-icon="inline-start" /> New project+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ aria-label={`New projects go to ${RESIDENCY_LABEL[r]}`}+ className="gap-1 rounded-l-none border-l-primary-foreground/25 px-2"+ />+ }+ >+ <Icon className="size-3.5" />+ <ChevronDown className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuRadioGroup value={r} onValueChange={(v) => pick(v as Residency)}>+ {choices.map((c) => {+ const ChoiceIcon = RESIDENCY_ICON[c];+ return (+ <DropdownMenuRadioItem key={c} value={c}>+ <ChoiceIcon /> {RESIDENCY_LABEL[c]}+ </DropdownMenuRadioItem>+ );+ })}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 07b429dc..e3178d66 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -54,7 +54,6 @@ import {} from "@/components/ui/tooltip";import { MEDIA_CORS } from "@/cut/lib/mediaCors";import { capturePosterWhenReady, readPoster } from "@/cut/lib/posterCache";-import { engineOrigin, servedFromEngine } from "@/cut/lib/api";import { quotaErrorMessage } from "@/cut/lib/backend/cloud";import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";import { dropCachedDoc, seedNewProjectDoc } from "@/cut/lib/docCache";@@ -67,8 +66,9 @@ import {type Residency,} from "@/cut/lib/queries";import { useInView } from "@/cut/hooks/useInView";+import { useNewProjectTarget } from "@/cut/lib/newProject";+import { NewProjectButton } from "@/cut/components/NewProjectButton";import { track } from "@/lib/analytics";-import { authClient } from "@/lib/auth-client";import { useStartCheckout } from "@/queries/billing";import { clearProjectThreads } from "@/cut/lib/chatThreads";import { useGenerate } from "@/cut/lib/generate";@@ -185,17 +185,10 @@ export function ProjectsHome() {const mode = useCutMode();// The home never runs in shared mode; anything non-cloud lists as local.const homeMode: Residency = mode === "cloud" ? "cloud" : "local";- const { data: session } = authClient.useSession();- // Which backends this home lists. Engine presence is what the ConnectGate- // already resolved for this tab (same-origin page, or a memoized loopback- // origin) — never a fresh probe, which could raise the browser's- // local-network prompt.- const engineUp = servedFromEngine() || engineOrigin() !== "";- const residencies: Residency[] = !session- ? ["local"]- : engineUp- ? ["local", "cloud"]- : ["cloud"];+ // Which backends this home lists, and where its New project button aims.+ // They are the same question: a shelf this browser and account can reach is+ // a shelf a project can be made on.+ const { target, choices: residencies } = useNewProjectTarget();const dual = residencies.length > 1;const r0 = residencies[0];@@ -229,7 +222,9 @@ export function ProjectsHome() {const openFolder = useSearchParams().get("folder");const [selected, setSelected] = useState<Set<string>>(new Set());const [view, setView] = useState<View>("gallery");- const [createOpen, setCreateOpen] = useState(false);+ // The residency the pending creation was launched for; null when the naming+ // dialog is closed.+ const [createIn, setCreateIn] = useState<Residency | null>(null);const [folderCreating, setFolderCreating] = useState<Residency | null>(null);const [renaming, setRenaming] = useState<{ project: ProjectSummary; residency: Residency } | null>(null@@ -345,10 +340,10 @@ export function ProjectsHome() {router.push(projectHref(base, project.id, "projects", folderId));};- const create = async () => {+ const create = async (r: Residency) => {setBusy(true);try {- await openNewProject(r0, name.trim() || "Untitled", openFolder);+ await openNewProject(r, name.trim() || "Untitled", openFolder);} finally {setBusy(false);}@@ -444,18 +439,18 @@ export function ProjectsHome() {// the doc + media transfer and cleans up a half-made copy itself), then drop// the original. The copy landing first is what makes deleting it safe.const moveAcross = async (source: Residency, p: ProjectSummary) => {- const target: Residency = source === "cloud" ? "local" : "cloud";+ const dest: Residency = source === "cloud" ? "local" : "cloud";setDupError(null);setBusy(true);try {- await copyProjectAcross(backendFor(source), backendFor(target), p.id);+ await copyProjectAcross(backendFor(source), backendFor(dest), p.id);await backendFor(source).fetch(`/api/cut/projects/${p.id}`, { method: "DELETE" }).catch(() => {});// The chat history moved with the project; the old project's copy goes// with the project itself.clearProjectThreads(p.id);- await Promise.all([refresh(source), refresh(target)]);+ await Promise.all([refresh(source), refresh(dest)]);} catch (e) {setDupError(e instanceof Error && e.message ? e.message : "Could not move the project.");} finally {@@ -703,7 +698,7 @@ export function ProjectsHome() {<buttontype="button"data-no-marquee- onClick={() => void newProjectHere(dual ? (folderOwner ?? "local") : r0)}+ onClick={() => void newProjectHere(folderOwner ?? target)}className="flex w-full items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"><Plus className="size-4" /> New project@@ -798,11 +793,10 @@ export function ProjectsHome() {<FolderPlus data-icon="inline-start" /> New folder</Button>))}- {/* Local-first: with the engine present, creation is always local —- a project reaches the cloud by moving it from the editor. */}- <Button onClick={() => void newProjectHere(dual ? (folderOwner ?? "local") : r0)}>- <Plus data-icon="inline-start" /> New project- </Button>+ <NewProjectButton+ pinned={folderOwner}+ onCreate={(r) => void newProjectHere(r)}+ />{anyProjects && (<div className="flex rounded-lg border border-border bg-card p-0.5"><Button@@ -852,14 +846,13 @@ export function ProjectsHome() {<h1 className="text-lg font-semibold tracking-tight">Create a new project to get started</h1>- <Button- onClick={() => {+ <NewProjectButton+ pinned={folderOwner}+ onCreate={(r) => {setName("");- setCreateOpen(true);+ setCreateIn(r);}}- >- <Plus data-icon="inline-start" /> New project- </Button>+ /></div></div>) : (@@ -879,7 +872,7 @@ export function ProjectsHome() {</>)}- <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <Dialog open={createIn !== null} onOpenChange={(o) => !o && setCreateIn(null)}><DialogContent className="sm:max-w-sm"><DialogHeader><DialogTitle>New project</DialogTitle>@@ -887,7 +880,7 @@ export function ProjectsHome() {<formonSubmit={(e) => {e.preventDefault();- void create();+ if (createIn) void create(createIn);}}><Inputdiff --git a/site/src/cut/lib/newProject.ts b/site/src/cut/lib/newProject.tsnew file mode 100644index 00000000..0d840d15--- /dev/null+++ b/site/src/cut/lib/newProject.ts@@ -0,0 +1,74 @@+// Where the next new project lands.+//+// A project's residency is fixed the moment it is created, so creation is the+// one point where the user gets a say — and the say sticks: the choice is+// remembered on this browser until they change it. What they can choose from+// is not up to them. The cloud needs a signed-in account, this Mac needs the+// Donkey app running, and with only one of those reachable there is nothing to+// pick.+//+// The choice lives in a module-level store rather than component state because+// the control is on screen twice at once — the sidebar and the projects home —+// and picking in one has to move the other.+import { useSyncExternalStore } from "react";++import { authClient } from "@/lib/auth-client";+import { useLocalCompute } from "./backend/hooks";+import type { Residency } from "./residency";++const KEY = "cut-new-project-residency";++let choice: Residency | null = null;+const listeners = new Set<() => void>();++function current(): Residency {+ if (choice) return choice;+ try {+ const raw = localStorage.getItem(KEY);+ choice = raw === "cloud" || raw === "local" ? raw : "local";+ } catch {+ choice = "local";+ }+ return choice;+}++export function setNewProjectResidency(r: Residency) {+ if (current() === r) return;+ choice = r;+ try {+ localStorage.setItem(KEY, r);+ } catch {+ // Private mode: the choice holds for this session and not past a reload.+ }+ listeners.forEach((l) => l());+}++function subscribe(onChange: () => void) {+ listeners.add(onChange);+ return () => {+ listeners.delete(onChange);+ };+}++export type NewProjectTarget = {+ /** Where a project created right now would land. */+ target: Residency;+ /** What this browser and account can reach. A single entry means the button+ * has nothing to offer and the stored choice is ignored. */+ choices: Residency[];+ pick: (r: Residency) => void;+};++export function useNewProjectTarget(): NewProjectTarget {+ const { data: session } = authClient.useSession();+ // The engine is never probed here — this reads the answer the ConnectGate+ // already has, and redraws when it lands.+ const engineUp = useLocalCompute();+ const stored = useSyncExternalStore(subscribe, current, () => "local" as const);+ const choices: Residency[] = !session ? ["local"] : engineUp ? ["local", "cloud"] : ["cloud"];+ return {+ target: choices.includes(stored) ? stored : choices[0],+ choices,+ pick: setNewProjectResidency,+ };+}