The VS Code of video editing, built for agents.
TypeScript
/* 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 { createSignal } from 'solid-js';
import { MAIN_CHANNELS } from '@desktop/main-channels';
import { mainBridge } from '@/lib/ipc';
import {
findProjectRecords,
forgetProject as forgetProjectRecord,
getProjectRecord,
listProjectRecords,
moveProjectRecord,
rememberProject,
updateProjectRecord,
} from '@/lib/db';
import type { CompileResult, MissingProjectChoice, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';
import type { ProjectRecord } from '@/lib/db';
export type { CompileResult, MissingProjectChoice, ProjectInfo, ProjectRecord, SourceEdit, WriteResult };
// The folder the save picker starts in: the parent of the last project
// saved. One localStorage value, read synchronously. Kept under the key the
// projects root had, so the picker opens where an upgrading user's projects
// already are.
const SAVE_FOLDER_STORAGE_KEY = 'diffusion-studio:projects-root';
const storedSaveFolder = (): string | null => {
try {
return window.localStorage.getItem(SAVE_FOLDER_STORAGE_KEY);
} catch {
return null;
}
};
const [saveFolder, setSaveFolder] = createSignal<string | null>(storedSaveFolder());
/** The folder the save picker starts in: null until a project has been saved. */
export { saveFolder };
// Bumped whenever the list of known projects changes — one created, opened,
// renamed, copied, or deleted — so a view listing them can refetch on it.
const [projectsRevision, setProjectsRevision] = createSignal(1);
/** Changes whenever the list `listProjects` answers with would; a source for `createResource`. */
export { projectsRevision };
/** Tells the views the list changed, for a change made to the records directly (a cover landing). */
export function markProjectsChanged(): void {
setProjectsRevision((revision) => revision + 1);
}
export const isDesktop = (): boolean => !!window.desktop;
export const isWindowsDesktop = (): boolean => window.desktop?.platform === "win32";
export const isMacOSDesktop = (): boolean => window.desktop?.platform === "darwin";
/**
* Puts `project` on the list (or marks it just opened) and tells the views.
* A project new to the list is filed in `collectionId`, when one is given.
*/
async function remember(project: ProjectInfo, collectionId?: string): Promise<void> {
await rememberProject(project, collectionId);
setProjectsRevision((revision) => revision + 1);
}
/** Makes `folder` where the next save picker starts. */
function storeSaveFolder(folder: string): void {
try {
window.localStorage.setItem(SAVE_FOLDER_STORAGE_KEY, folder);
} catch (error) {
console.warn('[projects] could not store the save folder', error);
}
setSaveFolder(folder);
}
/**
* Opens the native folder picker for a folder to open as a single project.
* It changes nothing on its own — hand the path to `openProjectFolder`, which
* is what makes the folder a project.
*/
export async function pickProjectFolder(): Promise<string | null> {
if (!isDesktop()) return null;
return mainBridge.call(MAIN_CHANNELS.PROJECTS_PICK_FOLDER, undefined);
}
/**
* The projects the app knows, most recently opened first, as their records
* describe them — no folder is read. The dashboard shows this at launch, and
* reading a folder under Desktop or Documents there is what would make macOS
* ask for permission before the user has done anything; a project's folder
* is looked at when the project is opened (see `checkProject`). So a record
* whose folder is gone stays on the list until then: it may well come back
* (a volume that is not mounted), and if not, opening it says so.
*/
export async function listProjects(): Promise<ProjectRecord[]> {
if (!isDesktop()) return [];
return listProjectRecords();
}
/**
* What the folder of `project` holds now, its record brought up to date with
* it: the project as it is, or null when the folder is gone or no longer a
* project. For the moment before a project on the list is opened.
*/
export async function checkProject(project: ProjectInfo): Promise<ProjectInfo | null> {
const current = await getProject(project.dir);
if (current) await updateProjectRecord(current);
return current;
}
/**
* Finds `project` again when its folder is gone from where the record says:
* renamed in Finder, or moved to a folder next to it. Its record follows it to
* the new folder, and the project there comes back; null when it is nowhere
* near where it was.
*/
export async function relocateProject(project: ProjectInfo): Promise<ProjectInfo | null> {
const moved = await mainBridge.call(MAIN_CHANNELS.PROJECTS_FIND_MOVED, { dir: project.dir, id: project.id });
if (!moved) return null;
await moveProjectRecord(project.dir, moved.dir);
await remember(moved);
return moved;
}
/** Tells the user `project`'s folder can't be found, and asks what to do about it. */
export function askAboutMissingProject(project: ProjectInfo): Promise<MissingProjectChoice> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_ASK_MISSING, { displayName: project.displayName, dir: project.dir });
}
/**
* Asks the user where `project` went, with the folder picker: the project in
* the folder they choose, its record moved there. Null when they cancel; an
* error when the folder holds no project, or a different one.
*/
export async function locateProject(project: ProjectInfo): Promise<ProjectInfo | null> {
const dir = await pickProjectFolder();
if (!dir) return null;
const found = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir });
if (!found) throw new Error("That folder doesn't hold a project.");
// A record from before ids has nothing to compare with: the user's word goes.
if (project.id && found.id !== project.id) {
throw new Error(`That folder holds a different project ("${found.displayName}").`);
}
await moveProjectRecord(project.dir, found.dir);
await remember(found);
return found;
}
/**
* Re-reads the project in `dir` and brings its record up to date — for a
* project whose folder changed while it was open, and for one that is
* closing, so the dashboard shows what it was last edited as. Null when the
* folder is gone.
*/
export async function refreshProject(dir: string): Promise<ProjectInfo | null> {
const current = await getProject(dir);
if (!current) return null;
await updateProjectRecord(current);
setProjectsRevision((revision) => revision + 1);
return current;
}
/** Takes the project in `dir` off the list, leaving its folder alone, and tells the views. */
export async function forgetProject(dir: string): Promise<void> {
await forgetProjectRecord(dir);
setProjectsRevision((revision) => revision + 1);
}
/**
* Creates a project and puts it on the list, filed in `collectionId` when one
* is given. It starts as a draft, called "Untitled", in the app's own folder,
* so nothing is asked: where it lives and what it is called are settled when
* it is saved (see `saveProject`).
*/
export async function createProject(collectionId?: string): Promise<ProjectInfo> {
if (!isDesktop()) throw new Error('Creating a project requires the desktop app.');
const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_CREATE, undefined);
await remember(project, collectionId);
return project;
}
/**
* 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, 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. */
const parentOf = (path: string): string => path.replace(/[\\/]+[^\\/]*[\\/]*$/, '') || path;
/**
* Moves the draft in `dir` to `target` (from `pickSaveLocation`), names it
* after that folder, and answers with the project where it now lives. The
* list follows the folder, and the next save picker starts beside it. Nothing
* may hold the folder meanwhile — see `ProjectProvider`.
*/
export async function saveProject(dir: string, target: string): Promise<ProjectInfo> {
const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_SAVE, { dir, target });
await moveProjectRecord(dir, project.dir);
await remember(project);
storeSaveFolder(parentOf(project.dir));
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
* can be found; the records say which folders to look in, and the folders
* say what they are now (one may have been renamed or replaced behind our
* back, or be a folder that predates ids — in which case main gives it one
* here, so the app can put an id in the URL).
*/
export async function resolveProject(ref: string): Promise<ProjectInfo | null> {
if (!ref || !isDesktop()) return null;
for (const record of await findProjectRecords(ref)) {
// A folder renamed or moved since is looked for next to where it was.
const project =
(await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir: record.dir })) ?? (await relocateProject(record));
if (!project || (project.id !== ref && project.name !== ref)) continue;
// Just opened, and holding an id the record may not have had yet.
await rememberProject(project);
return project;
}
return null;
}
/**
* Opens the folder `dir` as a project, making it one first when it is not:
* the folder is created if missing and, when nothing in it can be an entry,
* given an `index.tsx` holding an empty stage — and nothing else. Put on the
* list, so it stays reachable by name or id across relaunches, filed in
* `collectionId` when it is new to the list and one is given. How
* `diffusion open <path>` lands anywhere on disk.
*/
export async function openProjectFolder(dir: string, collectionId?: string): Promise<ProjectInfo> {
if (!isDesktop()) throw new Error('Opening a project folder requires the desktop app.');
const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_INIT, { dir });
await remember(project, collectionId);
return project;
}
/** 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 });
}
/** Renames the project: `displayName` in the record. The folder keeps its name. */
export async function renameProject(dir: string, displayName: string): Promise<ProjectInfo> {
if (!dir) throw new Error('No project folder.');
const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RENAME, { dir, displayName });
await remember(project);
return project;
}
/**
* Copies the project in `dir` next to itself and returns the copy (a new id),
* on the list in the collection the original is in.
*/
export async function duplicateProject(dir: string): Promise<ProjectInfo> {
if (!dir) throw new Error('No project folder.');
const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_DUPLICATE, { dir });
const original = await getProjectRecord(dir);
await remember(project, original?.collectionId);
return project;
}
/** Moves the project in `dir` to the trash and takes it off the list. */
export async function deleteProject(dir: string): Promise<void> {
if (!dir) throw new Error('No project folder.');
await mainBridge.call(MAIN_CHANNELS.PROJECTS_DELETE, { dir });
await forgetProject(dir);
}
/**
* 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 });
}
/**
* Writes changed props back into the project's JSX. No compile follows: the
* canvas is already showing these values, and main keeps the write from
* reaching the watcher (see `noteContent` in the desktop's projects.ts).
*/
export function writeProject(dir: string, edits: SourceEdit[]): Promise<WriteResult> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_WRITE, { dir, edits });
}
/** The project's config (the `diffusion` field of its package.json), unparsed; null when absent. */
export function readProjectConfig(dir: string): Promise<unknown> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_CONFIG_READ, { dir });
}
/** Replaces the project's config (null removes the field). Kept from the watcher like `writeProject`. */
export function writeProjectConfig(dir: string, config: unknown): Promise<void> {
return mainBridge.call(MAIN_CHANNELS.PROJECTS_CONFIG_WRITE, { dir, config });
}
/**
* Watches a project folder and calls `onChange` with every file that changed
* since the last call, coalescing a burst of them — an install, a checkout, a
* folder dropped into the library — into one answer.
*
* The delay buys throughput and nothing else: main keeps the app's own writes
* out of this stream by their content rather than by their timing (see
* `noteContent` in the desktop's projects.ts) and writes whole files, so no
* amount of waiting here is load-bearing.
*/
export function watchProject(dir: string, onChange: (paths: string[]) => void, debounceMs = 80): () => void {
if (!isDesktop()) return () => { };
let pending: ReturnType<typeof setTimeout> | undefined;
let changed = new Set<string>();
const stop = mainBridge.handle(MAIN_CHANNELS.PROJECTS_CHANGED, (event) => {
if (event.dir !== dir) return;
changed.add(event.path);
clearTimeout(pending);
pending = setTimeout(() => {
const paths = [...changed];
changed = new Set();
onChange(paths);
}, debounceMs);
});
mainBridge.call(MAIN_CHANNELS.PROJECTS_WATCH, { dir });
return () => {
clearTimeout(pending);
stop();
mainBridge.call(MAIN_CHANNELS.PROJECTS_UNWATCH, { dir }).catch(() => { });
};
}