The VS Code of video editing, built for agents.
TypeScript
Refactor project root management and enhance folder selection logic
konstantin-paulusf1c171ccb363
diff --git a/apps/web/src/components/dashboard/projects-folder-bar.tsx b/apps/web/src/components/dashboard/projects-folder-bar.tsxindex 648ddae0..65b3276c 100644--- a/apps/web/src/components/dashboard/projects-folder-bar.tsx+++ b/apps/web/src/components/dashboard/projects-folder-bar.tsx@@ -8,7 +8,7 @@ import { toast } from "somoto";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";import { revealPath } from "@/lib/shell";-import { isDesktop, pickProjectsRoot, projectsRoot } from "@/projects";+import { isDesktop, pickProjectsRoot, projectsRoot, rootsReady } from "@/projects";/*** Footer bar of the projects view: shows the projects root and the actions on@@ -16,6 +16,10 @@ import { isDesktop, pickProjectsRoot, projectsRoot } from "@/projects";* browser build (see @/projects).*/export function DashboardProjectsFolderBar() {+ // Blank rather than "No folder selected" until the database has answered:+ // the root arrives a tick after the bar first renders.+ const rootLabel = () => (rootsReady() ? projectsRoot() ?? "No folder selected" : "");+const handleChange = async () => {try {await pickProjectsRoot();@@ -49,7 +53,7 @@ export function DashboardProjectsFolderBar() {<div class="flex min-w-0 flex-1 flex-col justify-center gap-1"><p class="h-4 text-xs text-foreground">Project folder</p><p class="min-w-0 truncate text-xs text-muted-foreground">- {projectsRoot() ?? "No folder selected"}+ {rootLabel()}</p></div></div>diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsxindex d586e02c..bb6a0797 100644--- a/apps/web/src/components/dashboard/projects-view.tsx+++ b/apps/web/src/components/dashboard/projects-view.tsx@@ -48,9 +48,9 @@ import {createProject,deleteProject,duplicateProject,+ ensureProjectsRoot,isDesktop,listProjects,- pickProjectsRoot,projectKey,projectsRoot,renameProject,@@ -209,18 +209,6 @@ export function DashboardProjectsView() {};};- const handleChooseRoot = async () => {- if (!isDesktop()) {- toast.error("Projects on disk are only available in the desktop app");- return;- }- try {- await pickProjectsRoot();- } catch (e) {- toast.error("Failed to choose projects folder", { description: (e as Error).message });- }- };-// New project is the one card a single click still acts on, so a double// click lands on it as two clicks — the guard keeps that from creating two// projects.@@ -229,10 +217,13 @@ export function DashboardProjectsView() {setCreating(true);try {- if (!projectsRoot()) {- await handleChooseRoot();- if (!projectsRoot()) return;+ if (!isDesktop()) {+ toast.error("Projects on disk are only available in the desktop app");+ return;}+ // Waits for the roots to come back from the database, and asks for one+ // when there is none to wait for.+ if (!(await ensureProjectsRoot())) return;const project = await createProject(generateProjectName());track('project_created');diff --git a/apps/web/src/components/engine/api/assets.ts b/apps/web/src/components/engine/api/assets.tsindex e4a7ec56..599a6718 100644--- a/apps/web/src/components/engine/api/assets.ts+++ b/apps/web/src/components/engine/api/assets.ts@@ -9,7 +9,6 @@ import { ALL_FORMATS, InputTrack, UrlSource } from 'mediabunny';import { BlobSource } from 'mediabunny';import { Input } from 'mediabunny';import { nanoid } from "nanoid";-import { saveDirectoryHandle, retrieveDirectoryHandle } from "../db";import { GeometryType, PaintType } from "../components";import { secondsToFrames } from "../utils/time";import { toast } from "somoto";@@ -42,6 +41,7 @@ type MediaInput =type AssetState = {projectId: string;counter: number;+ /** Where the browser build writes asset files: the origin private file system. */directoryHandle: Promise<FileSystemDirectoryHandle>;version: Accessor<number>;setVersion: Setter<number>;@@ -63,7 +63,7 @@ export function initAssets(world: EngineWorld, projectId: string): void {assetStates.set(world, {projectId,counter: 0,- directoryHandle: retrieveDirectoryHandle(),+ directoryHandle: navigator.storage.getDirectory(),version,setVersion,selected,@@ -552,20 +552,6 @@ export async function uploadAssets(world: EngineWorld, ids?: string[]) {return results.filter((ref) => ref !== null);}-/** Prompts the user for a new OPFS root directory and persists the handle. */-export async function changeAssetDirectory(world: EngineWorld): Promise<void> {- try {- const directory = await window.showDirectoryPicker({- mode: 'readwrite',- startIn: 'videos',- });- await saveDirectoryHandle(directory);- assetState(world).directoryHandle = Promise.resolve(directory);- } catch (error) {- console.error('Failed to change directory:', error);- }-}-/** Selects a single asset by id (replacing any prior selection). */export function selectAsset(world: EngineWorld, id: string): void {const asset = world.assets.get(id);diff --git a/apps/web/src/components/engine/db/global-db.ts b/apps/web/src/components/engine/db/global-db.tsindex d8c373d3..438a11a0 100644--- a/apps/web/src/components/engine/db/global-db.ts+++ b/apps/web/src/components/engine/db/global-db.ts@@ -22,96 +22,92 @@ export function generateProjectName(): string {return `${adj} ${noun} ${day} ${month}`;}-export interface Directory {+/**+ * A folder the user keeps projects in (desktop; see @/projects). A path+ * rather than a handle: on desktop the main process does the reading, and it+ * takes paths.+ *+ * Stored as a list because there will be several. The app works against one+ * at a time for now — the most recently used, so no separate "active" flag+ * can end up pointing at a root that was removed.+ */+export interface ProjectRoot {id: string;+ /** Absolute path of the folder. */+ path: string;+ /** Its last segment, for showing it. */name: string;- handle: FileSystemDirectoryHandle;createdAt: string;- lastAccessedAt: string;+ lastUsedAt: string;}export interface GlobalDBSchema extends idb.DBSchema {- directories: {- value: Directory;+ roots: {+ value: ProjectRoot;key: string;indexes: {- 'by-name': string;- 'by-last-accessed': string;+ 'by-path': string;+ 'by-last-used': string;};};}-const DB_NAME = 'global-db';+const DB_NAME = 'diffusion-studio-idb';const DB_VERSION = 1;const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {upgrade(db) {- if (!db.objectStoreNames.contains('directories')) {- const store = db.createObjectStore('directories', {- keyPath: 'id',- });- store.createIndex('by-name', 'name');- store.createIndex('by-last-accessed', 'lastAccessedAt');+ if (!db.objectStoreNames.contains('roots')) {+ const store = db.createObjectStore('roots', { keyPath: 'id' });+ store.createIndex('by-path', 'path', { unique: true });+ store.createIndex('by-last-used', 'lastUsedAt');}},});++// ---------------------------------------------------------------------------+// Project roots++/** Last segment of a path, whichever separator it uses. */+const folderLabel = (path: string): string => path.split(/[\\/]/).filter(Boolean).pop() ?? path;+/**- * Saves the root directory handle to the database.- * If the same handle already exists, it will be updated.+ * Records `path` as a projects root, or marks the one already recorded for it+ * as just used — which is what makes it the active one.*/-export async function saveDirectoryHandle(handle: FileSystemDirectoryHandle) {+export async function rememberProjectRoot(path: string): Promise<ProjectRoot> {const db = await dbPromise;const now = new Date().toISOString();+ const existing = await db.getFromIndex('roots', 'by-path', path);- let id = nanoid();- let createdAt = now;+ const root: ProjectRoot = existing+ ? { ...existing, name: folderLabel(path), lastUsedAt: now }+ : { id: nanoid(), path, name: folderLabel(path), createdAt: now, lastUsedAt: now };- const existingEntries = await db.getAll('directories');- for (const entry of existingEntries) {- if (typeof entry.handle?.isSameEntry !== 'function') continue;- if (await entry.handle.isSameEntry(handle)) {- id = entry.id;- createdAt = entry.createdAt;- break;- }- }-- const entry: Directory = {- id,- name: handle.name,- handle,- createdAt,- lastAccessedAt: now,- };+ await db.put('roots', root);+ return root;+}- await db.put('directories', entry);- return entry;+/** Every projects root, most recently used first. */+export async function listProjectRoots(): Promise<ProjectRoot[]> {+ const db = await dbPromise;+ return (await db.getAllFromIndex('roots', 'by-last-used')).reverse();}-/**- * Returns the most recently accessed root directory, or null if none exists.- */-export async function retrieveLastAccessedDirectory(): Promise<Directory | null> {+/** The root the app is working against: the one used last, or null when there is none. */+export async function lastUsedProjectRoot(): Promise<ProjectRoot | null> {const db = await dbPromise;const cursor = await db- .transaction('directories', 'readonly')- .store.index('by-last-accessed')+ .transaction('roots', 'readonly')+ .store.index('by-last-used').openCursor(null, 'prev');return cursor?.value ?? null;}-/**- * Finds the last accessed directory handle, or falls back to the origin- * private file system as a scratch location for asset files.- * @returns The directory handle.- */-export async function retrieveDirectoryHandle() {- const lastAccessed = await retrieveLastAccessedDirectory();- if (lastAccessed) {- return lastAccessed.handle;- }-- return await navigator.storage.getDirectory();+/** Forgets a projects root. The folder itself is left alone. */+export async function forgetProjectRoot(id: string): Promise<void> {+ const db = await dbPromise;+ await db.delete('roots', id);}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.tsxindex b1158972..57e8aefc 100644--- a/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx+++ b/apps/web/src/components/sidebar-left/project-menu/file-menu.tsx@@ -16,7 +16,7 @@ import { useNavigate } from "@solidjs/router";import { For, Show, createMemo } from "solid-js";import { toast } from "somoto";import { generateProjectName } from "@/components/engine/db";-import { createProject, deleteProject, duplicateProject, pickProjectsRoot, projectsRoot } from "@/projects";+import { createProject, deleteProject, duplicateProject, ensureProjectsRoot } from "@/projects";import { Not } from "bitecs";import { ChildOf, isScene, useQuery } from "@/components/engine";import { AssetId, getAssetFile } from "@diffusionstudio/runtime";@@ -38,7 +38,7 @@ export function FileMenu() {const handleNewProject = async () => {try {- if (!projectsRoot() && !(await pickProjectsRoot())) return;+ if (!(await ensureProjectsRoot())) return;const created = await createProject(generateProjectName());navigate(projectRoute(created.id));} catch (e) {diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.tsindex 4729ee03..13b7af37 100644--- a/apps/web/src/projects/host.ts+++ b/apps/web/src/projects/host.ts@@ -14,31 +14,69 @@// between the two; callers get the folder from the `ProjectInfo` it answers// with (and the open project's from `@/context/project`).+import { createSignal } from 'solid-js';+import { MAIN_CHANNELS } from '@desktop/main-channels';import { mainBridge } from '@/lib/ipc';-import { store } from '@/init';-import { createStoredSignal } from '@/lib/store/signal';+import { lastUsedProjectRoot, rememberProjectRoot } from '@/components/engine/db';import type { CompileResult, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';export type { CompileResult, ProjectInfo, SourceEdit, WriteResult };-const rootItem = store.define<string | null>('projects.root', null);-const [projectsRoot, setProjectsRoot] = createStoredSignal(rootItem);+// The roots live in the app's IndexedDB (see @/components/engine/db) as a list+// keyed by path. The app works against one of them — the one used last — but+// the store is already the list several roots will need, so growing into them+// is UI rather than a migration.+//+// Reading a database is asynchronous, so the root starts null and arrives a+// tick later. Every call here waits for it, leaving only the UI to tell "no+// root yet" from "no root picked" — which is what `rootsReady` is for.++const [projectsRoot, setProjectsRoot] = createSignal<string | null>(null);+const [rootsReady, setRootsReady] = createSignal(false);-/** The projects root folder, or null until the user picks one. */+/** The projects root folder: null until one is picked, and until `rootsReady`. */export { projectsRoot };+/** Whether the roots have been read back from the database yet. */+export { rootsReady };++const ready = new Promise<void>((resolve) => {+ lastUsedProjectRoot()+ .then((root) => setProjectsRoot(root?.path ?? null))+ .catch((error) => console.error('[projects] could not read the projects roots', error))+ .finally(() => {+ setRootsReady(true);+ resolve();+ });+});+export const isDesktop = (): boolean => !!window.desktop;/** Opens the native folder picker and remembers the chosen root. */export async function pickProjectsRoot(): Promise<string | null> {const root = await mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_ROOT, undefined);- if (root) setProjectsRoot(root);+ if (!root) return null;++ await rememberProjectRoot(root);+ setProjectsRoot(root);return root;}+/**+ * The root to work against, waited for and — when there is none to wait for —+ * asked of the user. Null when they decline, or off the desktop, where there+ * is no folder to pick.+ */+export async function ensureProjectsRoot(): Promise<string | null> {+ if (!isDesktop()) return null;+ await ready;+ return projectsRoot() ?? pickProjectsRoot();+}+export async function listProjects(): Promise<ProjectInfo[]> {+ await ready;const root = projectsRoot();if (!root || !isDesktop()) return [];return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { root });@@ -46,6 +84,7 @@ export async function listProjects(): Promise<ProjectInfo[]> {/** Creates a project folder under the root, named after `displayName`. */export async function createProject(displayName: string): Promise<ProjectInfo> {+ await ready;const root = projectsRoot();if (!root) throw new Error('No projects folder selected.');return mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, { root, displayName });@@ -57,6 +96,7 @@ export async function createProject(displayName: string): Promise<ProjectInfo> {* always carries an id, so the app can put that in the URL.*/export async function resolveProject(ref: string): Promise<ProjectInfo | null> {+ await ready;const root = projectsRoot();if (!root || !isDesktop()) return null;return mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { root, ref });