Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions app/src/lib/local_project.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { defaultConfig } from "./config";
import { loadIdentity } from "./identity";
import { LocalProject } from "./project";

describe("LocalProject.open", () => {
it("creates a single blank document when an empty project is opened twice concurrently", async () => {
const identity = await loadIdentity(defaultConfig);
const projectId = `concurrent-open-${crypto.randomUUID()}`;

const opened = await Promise.all([
LocalProject.open(identity, defaultConfig, projectId),
LocalProject.open(identity, defaultConfig, projectId),
]);
for (const project of opened) project.destroy();

const reopened = await LocalProject.open(identity, defaultConfig, projectId);
try {
expect(reopened.snapshot().paragraphs).toHaveLength(1);
} finally {
reopened.destroy();
}
});
});
25 changes: 19 additions & 6 deletions app/src/lib/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ const mapParagraph = (paragraph: ScreenplayParagraph) => {
return map;
};

const openingProjects = new Map<string, Promise<LocalProject>>();

export class LocalProject {
readonly doc = new Y.Doc();
readonly persistence: IndexeddbPersistence;
Expand Down Expand Up @@ -267,13 +269,24 @@ export class LocalProject {
projectId = "local-draft",
initialTitle = "Untitled screenplay",
) {
const project = new LocalProject(identity, projectId, config);
await project.persistence.whenSynced;
project.migrateParagraphText();
if (project.paragraphStore.length === 0) {
await project.createDocument(initialTitle);
// Opening the same empty project twice (e.g. a StrictMode double effect) would create two
// blank documents that merge in IndexedDB, so each open waits for the previous one to finish.
const previous = openingProjects.get(projectId);
const opening = (previous?.catch(() => undefined) ?? Promise.resolve()).then(async () => {
const project = new LocalProject(identity, projectId, config);
await project.persistence.whenSynced;
project.migrateParagraphText();
if (project.paragraphStore.length === 0) {
project.createDocument(initialTitle);
}
return project;
});
openingProjects.set(projectId, opening);
try {
return await opening;
} finally {
if (openingProjects.get(projectId) === opening) openingProjects.delete(projectId);
}
return project;
}

subscribe = (listener: () => void) => {
Expand Down
Loading