Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor project listing and update project handling logic

konstantin-paulus223a39b87b03
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index d385815b..3c5a33e0 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -43,7 +43,6 @@ export const MAIN_CHANNELS = {
PROJECTS_PICK_ROOT: "projects:pick-root",
PROJECTS_PICK_FOLDER: "projects:pick-folder",
PROJECTS_DEFAULT_ROOT: "projects:default-root",
- PROJECTS_LIST: "projects:list",
PROJECTS_SCAN: "projects:scan",
PROJECTS_GET: "projects:get",
PROJECTS_INIT: "projects:init",
@@ -222,10 +221,6 @@ export type MainRequestMap = {
request: void;
response: string | null;
};
- [MAIN_CHANNELS.PROJECTS_LIST]: {
- request: { dirs: string[] };
- response: ProjectInfo[];
- };
// Every project folder directly under `root`: what the app puts on its
// list when `root` is chosen as the projects root.
[MAIN_CHANNELS.PROJECTS_SCAN]: {
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 150f46f4..6b557684 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -28,7 +28,6 @@ import {
duplicateProject,
getProject,
initProject,
- listProjects,
pickFolder,
pickRoot,
renameProject,
@@ -311,7 +310,6 @@ if (app.requestSingleInstanceLock()) {
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_FOLDER, () => pickFolder(mainWindow));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT, () => defaultRoot(mainWindow));
- mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ dirs }) => listProjects(dirs));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_SCAN, ({ root }) => scanProjects(root));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_GET, ({ dir }) => getProject(dir));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_INIT, ({ dir }) => initProject(mainWindow, dir));
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 5134d5f7..8e073f75 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -389,17 +389,6 @@ async function confirmCloudLocation(
return response === 1;
}
-/**
- * The projects among `dirs`, in that order. A folder that is gone or holds
- * no entry is left out rather than reported: the app keeps its own list of
- * projects (see the web app's projects host), and this is how it reads the
- * list back off the disk. Reads only.
- */
-export async function listProjects(dirs: string[]): Promise<ProjectInfo[]> {
- const projects = await Promise.all(dirs.map(describe));
- return projects.filter((project): project is ProjectInfo => project !== null);
-}
-
/** 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 });
diff --git a/apps/web/src/components/dashboard/home-view.tsx b/apps/web/src/components/dashboard/home-view.tsx
index ac1ee910..feaee10b 100644
--- a/apps/web/src/components/dashboard/home-view.tsx
+++ b/apps/web/src/components/dashboard/home-view.tsx
@@ -62,6 +62,7 @@ import {
DashboardCardPreview,
createBackgroundClickHandler,
createNewProject,
+ openProjectFromList,
} from "./shared";
import { parseTimestamp } from "./utils";
@@ -156,7 +157,8 @@ export function DashboardHomeView() {
*/
const resolveTarget = async (): Promise<ProjectInfo | null> => {
const current = target();
- if (current.kind === "project") return current.project;
+ // A project off the list is its record; the folder is looked at now.
+ if (current.kind === "project") return openProjectFromList(current.project);
if (current.kind === "folder") return openProjectFolder(current.dir);
// Waits for the roots to come back from the database, and asks for one
@@ -242,9 +244,11 @@ export function DashboardHomeView() {
refetchProjects();
};
- const openProject = (project: ProjectInfo) => {
+ const openProject = async (project: ProjectInfo) => {
+ const found = await openProjectFromList(project);
+ if (!found) return;
track("project_opened");
- navigate(projectRoute(projectKey(project)));
+ navigate(projectRoute(projectKey(found)));
};
const handleCreateProject = async () => {
@@ -411,7 +415,7 @@ export function DashboardHomeView() {
<div class="flex shrink-0 flex-col">
<div class="flex items-end gap-6 px-6 pt-4 pb-3">
<h2 class="min-w-0 flex-1 text-2xl leading-6 font-450 text-foreground">
- Recent
+ Recents
</h2>
</div>
<div
diff --git a/apps/web/src/components/dashboard/project-card.tsx b/apps/web/src/components/dashboard/project-card.tsx
index c66ce1fb..8ab0a436 100644
--- a/apps/web/src/components/dashboard/project-card.tsx
+++ b/apps/web/src/components/dashboard/project-card.tsx
@@ -15,13 +15,13 @@ import {
} from "@/components/ui/context-menu";
import { TextField, TextFieldInput } from "@/components/ui/text-field";
import { track } from "@/lib/analytics";
-import { duplicateProject, renameProject, type ProjectInfo } from "@/projects";
+import { duplicateProject, renameProject, type ProjectRecord } from "@/projects";
import { DashboardCardButton, DashboardCardPreview, DashboardProjectThumbnail } from "./shared";
import { formatEditedAt } from "./utils";
type DashboardProjectCardProps = {
- project: ProjectInfo;
+ project: ProjectRecord;
/** Whether the card is the selected one in its grid. */
active: boolean;
/** A single click, or a right-click, landed on the card. */
@@ -146,7 +146,7 @@ export function DashboardProjectCard(props: DashboardProjectCardProps) {
onDelete={props.onDelete}
>
<DashboardCardPreview>
- <DashboardProjectThumbnail dir={props.project.dir} />
+ <DashboardProjectThumbnail cover={props.project.cover} />
</DashboardCardPreview>
<div class="flex flex-col gap-1 px-2">
<div class="relative h-4 w-full">
diff --git a/apps/web/src/components/dashboard/projects-view.tsx b/apps/web/src/components/dashboard/projects-view.tsx
index bb601574..66d26e26 100644
--- a/apps/web/src/components/dashboard/projects-view.tsx
+++ b/apps/web/src/components/dashboard/projects-view.tsx
@@ -20,6 +20,7 @@ import {
DashboardCardPreview,
DashboardViewSection,
createNewProject,
+ openProjectFromList,
} from "./shared";
import { DeleteProjectDialog } from "./delete-project-dialog";
import { DashboardProjectCard } from "./project-card";
@@ -78,9 +79,11 @@ export function DashboardProjectsView() {
return entries;
});
- const openProject = (project: ProjectInfo) => {
+ const openProject = async (project: ProjectInfo) => {
+ const found = await openProjectFromList(project);
+ if (!found) return;
track('project_opened');
- navigate(projectRoute(projectKey(project)));
+ navigate(projectRoute(projectKey(found)));
};
const handleDeleted = (project: ProjectInfo) => {
diff --git a/apps/web/src/components/dashboard/shared.tsx b/apps/web/src/components/dashboard/shared.tsx
index 88632e8b..0a4011e3 100644
--- a/apps/web/src/components/dashboard/shared.tsx
+++ b/apps/web/src/components/dashboard/shared.tsx
@@ -17,16 +17,17 @@ import {
onCleanup,
type JSX,
} from "solid-js";
-import { projectCoverKey, readProjectCover } from "@/projects";
import { Separator } from "../ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { toast } from "somoto";
import { track } from "@/lib/analytics";
import { forgetProjectBundle, generateProjectName } from "@/lib/db";
import {
+ checkProject,
createProject,
deleteProject,
ensureProjectsRoot,
+ forgetProject,
isDesktop,
type ProjectInfo,
} from "@/projects";
@@ -561,6 +562,33 @@ export async function createNewProject(): Promise<ProjectInfo | null> {
return project;
}
+/**
+ * The project as its folder holds it now, for opening it from the list: what
+ * the list shows is its record, and the folder is only looked at here. Null —
+ * with the reason shown, and a way to take the project off the list — when
+ * the folder is gone or no longer a project. The list is not touched on its
+ * own: a folder on a volume that is not mounted comes back with the volume.
+ */
+export async function openProjectFromList(project: ProjectInfo): Promise<ProjectInfo | null> {
+ if (!isDesktop()) return project;
+
+ const current = await checkProject(project);
+ if (current) return current;
+
+ toast.error(`Could not find ${project.displayName}`, {
+ description: `There is no project at ${project.dir}. It may be on a disk that is not connected.`,
+ action: {
+ label: "Remove from list",
+ onClick: () => {
+ forgetProject(project.dir).catch((e) => {
+ toast.error("Failed to remove project", { description: (e as Error).message });
+ });
+ },
+ },
+ });
+ return null;
+}
+
/**
* Moves `project` to the Trash, and drops the bundle we were holding for it —
* the folder is gone, so the cached copy of it is stale.
@@ -607,16 +635,12 @@ export function DashboardViewSection(props: DashboardViewSectionProps) {
}
/** The saved cover of the project in `dir`, or nothing when it has none yet. */
-export function DashboardProjectThumbnail(props: { dir: string }) {
- const [cover] = createResource(
- () => projectCoverKey(props.dir),
- () => readProjectCover(props.dir),
- );
-
+/** The project's cover, off its record; nothing while it has none. */
+export function DashboardProjectThumbnail(props: { cover: Blob | null }) {
// The URL the last cover was under is released as this one takes its place.
const url = createMemo<string | null>((previous) => {
if (previous) URL.revokeObjectURL(previous);
- const blob = cover();
+ const blob = props.cover;
return blob ? URL.createObjectURL(blob) : null;
}, null);
diff --git a/apps/web/src/context/project.tsx b/apps/web/src/context/project.tsx
index cf7bb396..ca75dd02 100644
--- a/apps/web/src/context/project.tsx
+++ b/apps/web/src/context/project.tsx
@@ -11,7 +11,7 @@
import { createContext, createMemo, createSignal, useContext, type Accessor, type JSX } from 'solid-js';
-import { getProject, renameProject } from '@/projects';
+import { refreshProject, renameProject } from '@/projects';
import type { ProjectInfo } from '@/projects';
@@ -46,7 +46,7 @@ export function ProjectProvider(props: { project: ProjectInfo; children: JSX.Ele
};
const refresh = async (): Promise<void> => {
- const next = await getProject(dir());
+ const next = await refreshProject(dir());
if (next) setInfo(next);
};
diff --git a/apps/web/src/lib/db.ts b/apps/web/src/lib/db.ts
index 2ddab9f0..e73dade9 100644
--- a/apps/web/src/lib/db.ts
+++ b/apps/web/src/lib/db.ts
@@ -5,6 +5,8 @@
import { openDB } from 'idb';
import type * as idb from 'idb';
+import type { ProjectInfo } from '@desktop/main-channels';
+
const adjectives = ["Golden", "Silent", "Fast", "Bright", "Dark", "Wild", "Calm"];
const nouns = ["River", "Mountain", "Dream", "Storm", "Sunset", "Forest", "Ocean"];
@@ -25,19 +27,12 @@ export function generateProjectName(): string {
* A project the app knows: one it created, one it was asked to open — from
* the folder picker, or `dapi open <path>` — or one found in the projects
* root when that was chosen. The dashboard lists these and nothing else.
- * Keyed by folder, which is how main addresses a project. The id is a copy of
- * what the folder's package.json said last time — enough to find the folder
- * a URL names without reading every record's package.json — and the folder
- * has the final say (see `resolveProject` in @/projects).
- *
- * The projects root itself is not in here: there is one, so it lives in
- * localStorage (see @/projects).
+ * Keyed by folder, which is how main addresses a project.
*/
-export interface ProjectRecord {
- dir: string; // Absolute path of the project folder.
- id: string; // package.json `projectId`; "" while the folder has none.
- createdAt: string; // When the app first put it on record.
+export interface ProjectRecord extends ProjectInfo {
+ recordedAt: string; // When the app first put it on record.
lastOpenedAt: string;
+ cover: Blob | null;
}
/**
@@ -87,6 +82,20 @@ const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {
},
});
+/** Last segment of a path, whichever separator it uses. */
+const folderLabel = (path: string): string => path.split(/[\\/]/).filter(Boolean).pop() ?? path;
+
+/**
+ * A record for a project the app has not looked at yet: the folder name
+ * stands in for the display name, and the record's own dates for the
+ * folder's. What a legacy root is upgraded to; the first open replaces it
+ * with what the folder actually says.
+ */
+function placeholderRecord(dir: string, recordedAt: string, lastOpenedAt: string): ProjectRecord {
+ const name = folderLabel(dir);
+ return { dir, id: '', name, displayName: name, entry: '', modifiedAt: lastOpenedAt, createdAt: recordedAt, recordedAt, lastOpenedAt, cover: null };
+}
+
/**
* Versions 1 and 2 kept a `roots` store: folders the dashboard scanned for
* projects (`kind: 'multi'`), and single project folders registered on their
@@ -103,50 +112,59 @@ async function retireRoots(db: idb.IDBPDatabase<GlobalDBSchema>, tx: UpgradeTran
const roots = (tx as unknown as idb.IDBPTransaction<unknown, string[], 'versionchange'>).objectStore('roots');
for (const root of (await roots.getAll()) as LegacyRoot[]) {
if (root.kind !== 'single') continue;
- await projects.put({ dir: root.path, id: '', createdAt: root.createdAt, lastOpenedAt: root.lastUsedAt });
+ await projects.put(placeholderRecord(root.path, root.createdAt, root.lastUsedAt));
}
db.deleteObjectStore('roots' as never);
}
-/** Last segment of a path, whichever separator it uses. */
-const folderLabel = (path: string): string => path.split(/[\\/]/).filter(Boolean).pop() ?? path;
-
// ---------------------------------------------------------------------------
// Project records
/**
- * Puts the project in `dir` on record, or marks the one already recorded
- * there as just opened. `id` is what its package.json says now — the record
- * keeps a copy, so a folder that has since been given an id gets it here.
+ * Puts `project` on record as just opened — what its folder says now,
+ * replacing the copy the record held — or on record for the first time.
*/
-export async function rememberProject(dir: string, id: string): Promise<ProjectRecord> {
+export async function rememberProject(project: ProjectInfo): Promise<ProjectRecord> {
const db = await dbPromise;
const now = new Date().toISOString();
- const existing = await db.get('projects', dir);
+ const existing = await db.get('projects', project.dir);
const record: ProjectRecord = existing
- ? { ...existing, id, lastOpenedAt: now }
- : { dir, id, createdAt: now, lastOpenedAt: now };
+ ? { ...existing, ...project, lastOpenedAt: now }
+ : { ...project, recordedAt: now, lastOpenedAt: now, cover: null };
await db.put('projects', record);
return record;
}
+/**
+ * Brings the record for `project` up to date with what its folder says,
+ * without marking it opened — for a project that changed while it was open,
+ * and for one that is closing. Nothing to do when it is not on record.
+ */
+export async function updateProjectRecord(project: ProjectInfo): Promise<void> {
+ const db = await dbPromise;
+ const tx = db.transaction('projects', 'readwrite');
+ const existing = await tx.store.get(project.dir);
+ if (existing) await tx.store.put({ ...existing, ...project });
+ await tx.done;
+}
+
/**
* Puts every project in `found` that is not on record yet on it, leaving the
* ones that are alone — they were opened when they were opened. Answers with
* how many were new. For the projects a freshly chosen root turns out to hold.
*/
-export async function addProjectRecords(found: Array<{ dir: string; id: string }>): Promise<number> {
+export async function addProjectRecords(found: ProjectInfo[]): Promise<number> {
const db = await dbPromise;
const now = new Date().toISOString();
const tx = db.transaction('projects', 'readwrite');
let added = 0;
- for (const { dir, id } of found) {
- if (await tx.store.getKey(dir)) continue;
- await tx.store.put({ dir, id, createdAt: now, lastOpenedAt: now });
+ for (const project of found) {
+ if (await tx.store.getKey(project.dir)) continue;
+ await tx.store.put({ ...project, recordedAt: now, lastOpenedAt: now, cover: null });
added++;
}
@@ -190,6 +208,19 @@ export async function moveProjectRecord(from: string, to: string): Promise<void>
await tx.done;
}
+/**
+ * Records `cover` as the picture of the project in `dir`, replacing the one
+ * before it. Nothing to do when the project is not on record: one deleted
+ * while its cover was still being taken is not put back.
+ */
+export async function rememberProjectCover(dir: string, cover: Blob): Promise<void> {
+ const db = await dbPromise;
+ const tx = db.transaction('projects', 'readwrite');
+ const existing = await tx.store.get(dir);
+ if (existing) await tx.store.put({ ...existing, cover });
+ await tx.done;
+}
+
/** Takes the project in `dir` off the record. The folder itself is left alone. */
export async function forgetProject(dir: string): Promise<void> {
const db = await dbPromise;
diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsx
index 68a3c8b9..a5cbd386 100644
--- a/apps/web/src/pages/editor.tsx
+++ b/apps/web/src/pages/editor.tsx
@@ -24,7 +24,7 @@ import { attachProjectConfig, isProjectConfigFile } from '@/engine/project-confi
import { loadProjectBundle, rememberProjectBundle } from '@/lib/db';
import { isCacheFile } from '@diffusionstudio/assets';
import { createEditWriter } from '@/projects/edits';
-import { compileProject, watchProject } from '@/projects/host';
+import { compileProject, refreshProject, watchProject } from '@/projects/host';
import { captureProjectCover } from '@/projects/cover';
import { useProject } from "@/context/project";
import { useEngineContext } from "@/engine";
@@ -178,6 +178,7 @@ export function EditorPage() {
onCleanup(() => {
disposed = true;
captureProjectCover(dir, engine.snapshot());
+ refreshProject(dir);
unwatch();
unmount();
config.dispose();
diff --git a/apps/web/src/pages/login.tsx b/apps/web/src/pages/login.tsx
index 0f87cffb..ecef0b50 100644
--- a/apps/web/src/pages/login.tsx
+++ b/apps/web/src/pages/login.tsx
@@ -10,6 +10,7 @@ import { Icon } from '@/components/ui/icon';
import { TextField, TextFieldInput, TextFieldLabel } from '@/components/ui/text-field';
import { DevAuthCodeInput } from '@/components/dev-auth-code-input';
import { useAuth } from '@/context/auth';
+import { useFullscreenState } from '@/hooks/use-fullscreen-state';
type OAuthButtonProps = {
icon: string;
@@ -33,6 +34,7 @@ function OAuthButton(props: OAuthButtonProps) {
export function LoginPage() {
const auth = useAuth();
+ const isFullscreen = useFullscreenState();
const [email, setEmail] = createSignal('');
const [otpSending, setOtpSending] = createSignal(false);
@@ -55,6 +57,9 @@ export function LoginPage() {
return (
<div class="flex flex-col bg-background fixed inset-0 z-999">
+ <Show when={!!window.desktop && !isFullscreen()}>
+ <div class="absolute inset-x-0 top-0 h-10 z-20" style="-webkit-app-region: drag;" />
+ </Show>
<Show when={!window.desktop}>
<div class="flex items-center gap-1 p-4">
<Icon name="diffusion-logo" class="size-6" />
diff --git a/apps/web/src/projects/cover.ts b/apps/web/src/projects/cover.ts
index 135443a9..da375d3a 100644
--- a/apps/web/src/projects/cover.ts
+++ b/apps/web/src/projects/cover.ts
@@ -2,100 +2,27 @@
* 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 { rememberProjectCover } from '@/lib/db';
-import { CACHE_DIR } from '@diffusionstudio/assets';
-
-import { createProjectFS } from './fs';
-import { getProject, isDesktop } from './host';
-
-/** Where the snapshot lives inside the project folder. */
-export const COVER_PATH = `${CACHE_DIR}/cover.png`;
-
-/** How many covers are kept in hand — enough for the projects one session closes. */
-const RECENT_LIMIT = 8;
-
-/** Captures under way, by project folder. */
-const pending = new Map<string, Promise<void>>();
-/** Covers taken this session, by project folder: the file, without the trip to disk. */
-const recent = new Map<string, Blob>();
-/** How often each project's cover has been replaced this session. */
-const [revisions, setRevisions] = createSignal<Record<string, number>>({});
-
-/**
- * Takes the cover of the project in `dir` from `snapshot` and writes it.
- * Call it as the project closes, with the snapshot already under way: the
- * capture is registered synchronously, so a read that follows waits for this
- * cover rather than answering with the last one.
- */
-export function captureProjectCover(dir: string, snapshot: Promise<Blob | null>): Promise<void> {
- if (!dir || !isDesktop()) return Promise.resolve();
-
- // Until the new one arrives there is no cover in hand: what is there
- // shows the project as it was before this session's edits.
- recent.delete(dir);
-
- const done = capture(dir, snapshot)
- .catch((error) => console.warn('[projects] could not write the project cover', error))
- .finally(() => {
- if (pending.get(dir) === done) pending.delete(dir);
- });
-
- pending.set(dir, done);
- return done;
-}
+import { isDesktop, markProjectsChanged } from './host';
/**
- * What to key a read of the project's cover on: a value that changes once a
- * new cover has been taken for `dir`, and stays put when another project's
- * cover is replaced. Read it as a resource's source and the read runs again
- * when the cover lands — which is what a card asking for the cover of a
- * project still closing needs.
+ * Takes the cover of the project in `dir` from `snapshot` and puts it on the
+ * project's record (see `ProjectRecord.cover`), where the dashboard reads it
+ * from with the rest of the record — never from the folder, which it must
+ * not touch at launch. Call it as the project closes, with the snapshot
+ * already under way; the list is told once the cover has landed, so a card
+ * for a project still closing picks it up.
*/
-export function projectCoverKey(dir: string): string {
- return `${revisions()[dir] ?? 0}:${dir}`;
-}
-
-/** The cover of the project in `dir`, or null while it has none. */
-export async function readProjectCover(dir: string): Promise<Blob | null> {
- if (!dir || !isDesktop()) return null;
-
- if (!recent.has(dir)) await pending.get(dir);
-
- const captured = recent.get(dir);
- if (captured) return captured;
+export async function captureProjectCover(dir: string, snapshot: Promise<Blob | null>): Promise<void> {
+ if (!dir || !isDesktop()) return;
try {
- const fs = createProjectFS(dir);
- // Asked for before it is read: a missing cover is the normal case
- // (every project that has not been opened yet), not a failed read.
- if (!(await fs.stat(COVER_PATH))) return null;
- return await fs.file(COVER_PATH);
+ const blob = await snapshot;
+ if (!blob) return;
+ await rememberProjectCover(dir, blob);
+ markProjectsChanged();
} catch (error) {
- console.warn('[projects] could not read the project cover', error);
- return null;
- }
-}
-
-async function capture(dir: string, snapshot: Promise<Blob | null>): Promise<void> {
- const blob = await snapshot;
- if (!blob) return;
-
- // A project closed by deleting it is already in the trash, and writing
- // would put its folder back — holding nothing but this one file.
- if (!(await getProject(dir))) return;
-
- await createProjectFS(dir).write(COVER_PATH, blob);
-
- remember(dir, blob);
- setRevisions((current) => ({ ...current, [dir]: (current[dir] ?? 0) + 1 }));
-}
-
-function remember(dir: string, blob: Blob): void {
- recent.set(dir, blob);
- // Insertion order, so the cover taken longest ago is the first to go.
- for (const key of recent.keys()) {
- if (recent.size <= RECENT_LIMIT) break;
- recent.delete(key);
+ console.warn('[projects] could not record the project cover', error);
}
}
diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.ts
index a2d1a31e..335a813c 100644
--- a/apps/web/src/projects/host.ts
+++ b/apps/web/src/projects/host.ts
@@ -10,15 +10,17 @@ import { mainBridge } from '@/lib/ipc';
import {
addProjectRecords,
findProjectRecords,
- forgetProject,
+ forgetProject as forgetProjectRecord,
listProjectRecords,
moveProjectRecord,
rememberProject,
+ updateProjectRecord,
} from '@/lib/db';
import type { CompileResult, ProjectInfo, SourceEdit, WriteResult } from '@desktop/main-channels';
+import type { ProjectRecord } from '@/lib/db';
-export type { CompileResult, ProjectInfo, SourceEdit, WriteResult };
+export type { CompileResult, ProjectInfo, ProjectRecord, SourceEdit, WriteResult };
// There is one projects root, so it is one localStorage value rather than a
// database row — read synchronously, so it is known from the first render.
@@ -49,11 +51,16 @@ 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;
/** Puts `project` on the list (or marks it just opened) and tells the views. */
async function remember(project: ProjectInfo): Promise<void> {
- await rememberProject(project.dir, project.id);
+ await rememberProject(project);
setProjectsRevision((revision) => revision + 1);
}
@@ -129,16 +136,48 @@ export async function ensureProjectsRoot(): Promise<string | null> {
}
/**
- * The projects the app knows that are still on disk, most recently opened
- * first. A record whose folder is gone (moved, trashed by hand, on a volume
- * that is not mounted) is skipped, not forgotten: it may well come back.
+ * 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<ProjectInfo[]> {
+export async function listProjects(): Promise<ProjectRecord[]> {
if (!isDesktop()) return [];
+ return listProjectRecords();
+}
- const records = await listProjectRecords();
- if (!records.length) return [];
- return mainBridge.call(MAIN_CHANNELS.PROJECTS_LIST, { dirs: records.map((record) => record.dir) });
+/**
+ * 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;
+}
+
+/**
+ * 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 folder under the root, named after `displayName`, and puts it on the list. */
@@ -166,7 +205,7 @@ export async function resolveProject(ref: string): Promise<ProjectInfo | null> {
const project = await mainBridge.call(MAIN_CHANNELS.PROJECTS_RESOLVE, { dir: record.dir });
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.dir, project.id);
+ await rememberProject(project);
return project;
}
return null;
@@ -223,7 +262,6 @@ export async function deleteProject(dir: string): Promise<void> {
await mainBridge.call(MAIN_CHANNELS.PROJECTS_DELETE, { dir });
await forgetProject(dir);
- setProjectsRevision((revision) => revision + 1);
}
/**