bookish-press 0.11.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/components/chapter/Block.svelte +19 -0
  2. package/dist/components/chapter/Block.svelte.d.ts +1 -0
  3. package/dist/components/chapter/ChapterBody.test.js +69 -0
  4. package/dist/components/chapter/Format.svelte +4 -0
  5. package/dist/components/chapter/Marginal.svelte +2 -1
  6. package/dist/components/chapter/Symbol.svelte +27 -0
  7. package/dist/components/chapter/Symbol.svelte.d.ts +7 -0
  8. package/dist/components/editor/BookishEditor.svelte +41 -153
  9. package/dist/components/editor/Commands.js +45 -44
  10. package/dist/components/editor/Commands.test.d.ts +1 -0
  11. package/dist/components/editor/Commands.test.js +791 -0
  12. package/dist/components/editor/Editing.d.ts +51 -0
  13. package/dist/components/editor/Editing.js +201 -0
  14. package/dist/components/editor/Permissions.svelte +10 -2
  15. package/dist/components/page/BookLoader.svelte +43 -6
  16. package/dist/components/page/BulkReferenceEditor.svelte +2 -2
  17. package/dist/components/page/Chapter.svelte +77 -70
  18. package/dist/components/page/Contexts.d.ts +14 -0
  19. package/dist/components/page/Contexts.js +14 -4
  20. package/dist/components/page/Edition.svelte +2 -10
  21. package/dist/components/page/EditionLoader.svelte +40 -7
  22. package/dist/components/page/Index.svelte +1 -1
  23. package/dist/components/page/Publish.svelte +0 -42
  24. package/dist/components/page/Reference.svelte +2 -2
  25. package/dist/components/page/References.svelte +5 -6
  26. package/dist/components/page/TitlePage.svelte +65 -0
  27. package/dist/components/page/TitlePage.svelte.d.ts +20 -0
  28. package/dist/components/page/UnsavedNotice.svelte +96 -0
  29. package/dist/components/page/UnsavedNotice.svelte.d.ts +7 -0
  30. package/dist/epub/xhtml.js +15 -0
  31. package/dist/models/CRUD.d.ts +28 -12
  32. package/dist/models/CRUD.emu.test.d.ts +1 -0
  33. package/dist/models/CRUD.emu.test.js +250 -0
  34. package/dist/models/CRUD.js +110 -72
  35. package/dist/models/book/Book.js +1 -1
  36. package/dist/models/book/Book.test.d.ts +1 -0
  37. package/dist/models/book/Book.test.js +124 -0
  38. package/dist/models/book/BookMedia.d.ts +5 -0
  39. package/dist/models/book/BookMedia.js +23 -7
  40. package/dist/models/book/BookMedia.test.d.ts +1 -0
  41. package/dist/models/book/BookMedia.test.js +40 -0
  42. package/dist/models/book/Chapter.js +28 -12
  43. package/dist/models/book/Chapter.test.d.ts +1 -0
  44. package/dist/models/book/Chapter.test.js +167 -0
  45. package/dist/models/book/Edition.d.ts +2 -0
  46. package/dist/models/book/Edition.js +34 -25
  47. package/dist/models/book/Edition.test.d.ts +1 -0
  48. package/dist/models/book/Edition.test.js +342 -0
  49. package/dist/models/book/Reference.js +5 -9
  50. package/dist/models/book/Reference.test.d.ts +1 -0
  51. package/dist/models/book/Reference.test.js +40 -0
  52. package/dist/models/chapter/BlocksNode.d.ts +2 -0
  53. package/dist/models/chapter/BlocksNode.js +59 -3
  54. package/dist/models/chapter/BlocksNode.test.js +2 -2
  55. package/dist/models/chapter/Caret.js +12 -3
  56. package/dist/models/chapter/Caret.test.d.ts +1 -0
  57. package/dist/models/chapter/Caret.test.js +127 -0
  58. package/dist/models/chapter/ChapterNode.d.ts +3 -0
  59. package/dist/models/chapter/ChapterNode.js +11 -1
  60. package/dist/models/chapter/CommentNode.js +3 -2
  61. package/dist/models/chapter/EmbedNode.js +1 -1
  62. package/dist/models/chapter/FootnoteNode.js +1 -1
  63. package/dist/models/chapter/FormatNode.d.ts +5 -1
  64. package/dist/models/chapter/FormatNode.js +60 -20
  65. package/dist/models/chapter/LabelNode.js +4 -2
  66. package/dist/models/chapter/ListNode.js +11 -13
  67. package/dist/models/chapter/Node.test.js +2 -11
  68. package/dist/models/chapter/Operations.test.d.ts +1 -0
  69. package/dist/models/chapter/Operations.test.js +298 -0
  70. package/dist/models/chapter/ParagraphNode.js +29 -3
  71. package/dist/models/chapter/Parser.d.ts +49 -4
  72. package/dist/models/chapter/Parser.js +210 -88
  73. package/dist/models/chapter/Parser.test.js +31 -0
  74. package/dist/models/chapter/Roundtrip.test.d.ts +1 -0
  75. package/dist/models/chapter/Roundtrip.test.js +313 -0
  76. package/dist/models/chapter/SymbolBlockNode.d.ts +40 -0
  77. package/dist/models/chapter/SymbolBlockNode.js +75 -0
  78. package/dist/models/chapter/SymbolBlockNode.test.d.ts +1 -0
  79. package/dist/models/chapter/SymbolBlockNode.test.js +130 -0
  80. package/dist/models/chapter/SymbolNode.d.ts +32 -0
  81. package/dist/models/chapter/SymbolNode.js +61 -0
  82. package/dist/models/chapter/SymbolNode.test.d.ts +1 -0
  83. package/dist/models/chapter/SymbolNode.test.js +177 -0
  84. package/dist/models/chapter/TableNode.js +2 -2
  85. package/dist/models/chapter/TextNode.d.ts +8 -1
  86. package/dist/models/chapter/TextNode.js +22 -15
  87. package/dist/util/getSubdomain.js +5 -1
  88. package/dist/util/getSubdomain.test.d.ts +1 -0
  89. package/dist/util/getSubdomain.test.js +53 -0
  90. package/dist/util/mineReference.js +12 -5
  91. package/dist/util/mineReference.test.d.ts +1 -0
  92. package/dist/util/mineReference.test.js +62 -0
  93. package/package.json +12 -7
@@ -0,0 +1,250 @@
1
+ /**
2
+ * CRUD.ts against the Firestore emulator, through the app's own Firebase
3
+ * singletons: what each write actually leaves in the database. Every other
4
+ * test mocks CRUD, so these are the only tests of the code that persists
5
+ * people's books.
6
+ */
7
+ import { signInWithEmailAndPassword, signOut } from 'firebase/auth';
8
+ import { doc, getDoc } from 'firebase/firestore';
9
+ import { auth, db } from './Firebase';
10
+ import { createBook, createNewEdition, isSubdomainAvailable, listenToBooksByName, updateEdition, updateLock, } from './CRUD';
11
+ import Book, {} from './book/Book';
12
+ import Edition, {} from './book/Edition';
13
+ import { editionPathFor, listDocIDs, patchDoc, readDoc, resetAuth, resetFirestore, seedBook, setBookAccess, signUpForToken, S, ARR, TEST_PASSWORD, unique, } from '../../tests/support/emulator';
14
+ let owner;
15
+ let editor;
16
+ beforeAll(async () => {
17
+ await resetFirestore();
18
+ await resetAuth();
19
+ owner = await signUpForToken(`crud-owner-${unique()}@example.com`);
20
+ editor = await signUpForToken(`crud-editor-${unique()}@example.com`);
21
+ });
22
+ async function signInAs(user) {
23
+ if (!auth)
24
+ throw new Error('No Firebase auth');
25
+ await signOut(auth);
26
+ await signInWithEmailAndPassword(auth, user.email, TEST_PASSWORD);
27
+ }
28
+ /** Load a book and its first edition the way the app's listeners do. */
29
+ async function load(bookID) {
30
+ if (!db)
31
+ throw new Error('No Firestore');
32
+ const bookDoc = await getDoc(doc(db, 'books', bookID));
33
+ const book = Book.fromJSON(bookID, bookDoc.data());
34
+ const editionID = book.getEditions()[0].ref.id;
35
+ const editionDoc = await getDoc(doc(db, `books/${bookID}/editions/${editionID}`));
36
+ let edition = Edition.fromJSON(editionDoc.ref, editionDoc.data());
37
+ // Chapter text lives in chapter documents; load it as EditionLoader does.
38
+ const chapters = await Promise.all(edition.chapters.map(async (c) => c.ref ? ((await getDoc(c.ref)).data()?.text ?? '') : ''));
39
+ edition = edition.withChapters(edition.chapters.map((c, i) => c.withText(chapters[i])));
40
+ return { book, edition };
41
+ }
42
+ describe('createBook', () => {
43
+ test('creates a book owned by its creator, with one edition and chapter', async () => {
44
+ await signInAs(owner);
45
+ const bookID = await createBook(owner.uid);
46
+ const book = await readDoc(`books/${bookID}`);
47
+ expect(book).toMatchObject({
48
+ title: 'Untitled',
49
+ published: false,
50
+ uids: [owner.uid],
51
+ });
52
+ const editions = book?.editions;
53
+ expect(editions).toHaveLength(1);
54
+ const edition = await readDoc(editions[0].ref);
55
+ expect(edition).toMatchObject({ number: 1, published: null });
56
+ const chapters = edition?.chapters;
57
+ expect(chapters).toHaveLength(1);
58
+ // The chapter's text document exists and its ref was persisted.
59
+ expect(await readDoc(chapters[0].ref)).toEqual({ text: '' });
60
+ });
61
+ });
62
+ describe('updateEdition', () => {
63
+ let bookID;
64
+ beforeEach(async () => {
65
+ bookID = `crud${unique()}`;
66
+ await seedBook(owner.uid, bookID, {
67
+ chapters: [
68
+ { id: 'one', title: 'One', text: 'First.' },
69
+ { id: 'two', title: 'Two', text: 'Second.' },
70
+ ],
71
+ });
72
+ await signInAs(owner);
73
+ });
74
+ test('writes only changed chapter text', async () => {
75
+ const { book, edition } = await load(bookID);
76
+ const one = edition.getChapter('one');
77
+ const revised = edition.withRevisedChapter(one, one.withText('First, revised.'));
78
+ await updateEdition(book, edition, revised);
79
+ const path = `${editionPathFor(bookID)}/chapters`;
80
+ expect(await readDoc(`${path}/one`)).toEqual({
81
+ text: 'First, revised.',
82
+ });
83
+ expect(await readDoc(`${path}/two`)).toEqual({ text: 'Second.' });
84
+ });
85
+ test('creates documents for new chapters and returns their refs', async () => {
86
+ const { book, edition } = await load(bookID);
87
+ const added = edition.withNewChapter();
88
+ const refs = await updateEdition(book, edition, added);
89
+ expect(refs.size).toBe(1);
90
+ const [, ref] = [...refs][0];
91
+ expect(await readDoc(ref.path)).toEqual({ text: '' });
92
+ const saved = await readDoc(editionPathFor(bookID));
93
+ expect(saved?.chapters).toHaveLength(3);
94
+ });
95
+ test('deletes documents of removed chapters', async () => {
96
+ const { book, edition } = await load(bookID);
97
+ await updateEdition(book, edition, edition.withoutChapter('two'));
98
+ expect(await listDocIDs(`${editionPathFor(bookID)}/chapters`)).toEqual([
99
+ 'one',
100
+ ]);
101
+ const saved = await readDoc(editionPathFor(bookID));
102
+ expect((saved?.chapters).map((c) => c.id)).toEqual([
103
+ 'one',
104
+ ]);
105
+ });
106
+ test('keeps the book’s copy of the edition’s summary in sync', async () => {
107
+ const { book, edition } = await load(bookID);
108
+ await updateEdition(book, edition, edition.withSummary('A summary.'));
109
+ const saved = await readDoc(`books/${bookID}`);
110
+ expect((saved?.editions)[0].summary).toBe('A summary.');
111
+ });
112
+ test('reports failure when the book can’t be updated', async () => {
113
+ // An edition editor saves a change to the edition's summary, which
114
+ // the book mirrors, after losing access to the book itself (here, by
115
+ // the owner removing them mid-session). The edition write is allowed
116
+ // but the book's isn't, so the save must fail rather than report
117
+ // success with the book out of sync.
118
+ await patchDoc(editionPathFor(bookID), {
119
+ uids: ARR(S(owner.uid), S(editor.uid)),
120
+ });
121
+ await setBookAccess(bookID, [owner.uid], [editor.uid]);
122
+ await signInAs(editor);
123
+ const { book, edition } = await load(bookID);
124
+ await setBookAccess(bookID, [owner.uid], []);
125
+ await expect(updateEdition(book, edition, edition.withSummary('Changed.'))).rejects.toMatchObject({ code: 'permission-denied' });
126
+ });
127
+ });
128
+ describe('createNewEdition', () => {
129
+ test('copies chapter text into a new, unpublished, numbered edition', async () => {
130
+ const bookID = `crudedition${unique()}`;
131
+ await seedBook(owner.uid, bookID, {
132
+ published: 1700000000000,
133
+ chapters: [
134
+ { id: 'one', title: 'One', text: 'Published text.' },
135
+ { id: 'two', title: 'Two', text: 'More text.' },
136
+ ],
137
+ });
138
+ await signInAs(owner);
139
+ const { book } = await load(bookID);
140
+ const revised = await createNewEdition(book);
141
+ expect(revised.getEditions()).toHaveLength(2);
142
+ const newPath = revised
143
+ .getEditions()
144
+ .find((e) => e.ref.path !== editionPathFor(bookID)).ref.path;
145
+ const created = await readDoc(newPath);
146
+ expect(created).toMatchObject({ number: 2, published: null });
147
+ const chapters = created?.chapters;
148
+ const texts = await Promise.all(chapters.map(async (c) => (await readDoc(c.ref))?.text));
149
+ expect(texts).toEqual(['Published text.', 'More text.']);
150
+ // The new edition's chapters are its own documents, not the old ones.
151
+ for (const c of chapters)
152
+ expect(c.ref.startsWith(newPath)).toBe(true);
153
+ // The original is untouched.
154
+ expect(await readDoc(editionPathFor(bookID))).toMatchObject({
155
+ number: 1,
156
+ published: 1700000000000,
157
+ });
158
+ });
159
+ });
160
+ describe('updateLock', () => {
161
+ let bookID;
162
+ beforeEach(async () => {
163
+ bookID = `crudlock${unique()}`;
164
+ await seedBook(owner.uid, bookID, {
165
+ editionEditors: [editor.uid],
166
+ chapters: [{ id: 'one', title: 'One', text: 'Text.' }],
167
+ });
168
+ });
169
+ test('takes and releases a lease', async () => {
170
+ await signInAs(owner);
171
+ const { edition } = await load(bookID);
172
+ expect(await updateLock(edition, owner.uid, 'one', true)).toBe(true);
173
+ expect((await readDoc(editionPathFor(bookID)))?.active).toEqual({
174
+ one: owner.uid,
175
+ });
176
+ const locked = edition.withLock(owner.uid, 'one', true);
177
+ expect(await updateLock(locked, owner.uid, 'one', false)).toBe(false);
178
+ expect((await readDoc(editionPathFor(bookID)))?.active).toEqual({});
179
+ });
180
+ test('does not take a lease someone else holds', async () => {
181
+ await signInAs(owner);
182
+ const { edition: ownersCopy } = await load(bookID);
183
+ await signInAs(editor);
184
+ const { edition: editorsCopy } = await load(bookID);
185
+ expect(await updateLock(editorsCopy, editor.uid, 'one', true)).toBe(true);
186
+ // The owner's copy predates the editor's lease.
187
+ await signInAs(owner);
188
+ expect(await updateLock(ownersCopy, owner.uid, 'one', true)).toBe(false);
189
+ expect((await readDoc(editionPathFor(bookID)))?.active).toEqual({
190
+ one: editor.uid,
191
+ });
192
+ });
193
+ test('does not overwrite edits made since the edition was loaded', async () => {
194
+ await signInAs(owner);
195
+ const { edition: stale } = await load(bookID);
196
+ // Someone else retitles the edition after this copy was loaded.
197
+ await patchDoc(editionPathFor(bookID), { title: S('Retitled') });
198
+ await updateLock(stale, owner.uid, 'one', true);
199
+ expect((await readDoc(editionPathFor(bookID)))?.title).toBe('Retitled');
200
+ });
201
+ });
202
+ describe('subdomains', () => {
203
+ test('a draft’s subdomain is taken, even for people who can’t see it', async () => {
204
+ const bookID = `cruddomain${unique()}`;
205
+ const domain = `draft-${unique()}`;
206
+ await seedBook(owner.uid, bookID, {
207
+ domain,
208
+ chapters: [{ id: 'one', title: 'One', text: 'Text.' }],
209
+ });
210
+ await signInAs(editor);
211
+ expect(await isSubdomainAvailable(domain)).toBe(false);
212
+ expect(await isSubdomainAvailable(`free-${unique()}`)).toBe(true);
213
+ // Only signed-in people may ask.
214
+ await signOut(auth);
215
+ await expect(isSubdomainAvailable(domain)).rejects.toMatchObject({
216
+ code: 'functions/unauthenticated',
217
+ });
218
+ });
219
+ test('a book can be found by subdomain by readers and by its editors', async () => {
220
+ const published = `crudpub${unique()}`;
221
+ const pubDomain = `pub-${unique()}`;
222
+ await seedBook(owner.uid, published, {
223
+ domain: pubDomain,
224
+ published: 1700000000000,
225
+ chapters: [{ id: 'one', title: 'One', text: 'Text.' }],
226
+ });
227
+ const draft = `cruddraft${unique()}`;
228
+ const draftDomain = `draft-${unique()}`;
229
+ await seedBook(owner.uid, draft, {
230
+ domain: draftDomain,
231
+ editionEditors: [editor.uid],
232
+ chapters: [{ id: 'one', title: 'One', text: 'Text.' }],
233
+ });
234
+ const find = async (name) => {
235
+ let unsubscribe = () => { };
236
+ const found = await new Promise((resolve, reject) => {
237
+ unsubscribe = listenToBooksByName(name, (books) => resolve(books.map((b) => b.getID())), reject);
238
+ });
239
+ unsubscribe();
240
+ return found;
241
+ };
242
+ await signOut(auth);
243
+ expect(await find(pubDomain)).toEqual([published]);
244
+ expect(await find(draftDomain)).toEqual([]);
245
+ await signInAs(editor);
246
+ expect(await find(draftDomain)).toEqual([draft]);
247
+ await signInAs(owner);
248
+ expect(await find(draftDomain)).toEqual([draft]);
249
+ });
250
+ });
@@ -1,5 +1,5 @@
1
1
  import { auth, db, functions } from './Firebase';
2
- import { collection, getDocs, getDoc, setDoc, doc, addDoc, query, where, deleteDoc, onSnapshot, } from 'firebase/firestore';
2
+ import { collection, getDocs, getDoc, setDoc, doc, addDoc, query, where, deleteDoc, deleteField, runTransaction, onSnapshot, } from 'firebase/firestore';
3
3
  import { httpsCallable } from 'firebase/functions';
4
4
  import Edition from './book/Edition';
5
5
  import Book, {} from './book/Book';
@@ -7,45 +7,78 @@ function editionPath(bookID, editionID) {
7
7
  return `books/${bookID}/editions/${editionID}`;
8
8
  }
9
9
  const NO_DATABASE_CONNECTION = 'Not connected to database';
10
- ///////////////
11
- //// READ BOOKS
12
- ///////////////
13
- function listenToBooks(constraint, react) {
10
+ /** Report listener failures somewhere visible when the caller doesn't. */
11
+ const logListenError = (error) => console.error('Listener failed', error);
12
+ function toBooks(docs) {
13
+ return docs.map((doc) => Book.fromJSON(doc.id, doc.data()));
14
+ }
15
+ /**
16
+ * Listen to the books matching all of the given constraints. Security rules
17
+ * only allow queries they can prove return readable books, so every query
18
+ * must be constrained by publication or by the reader's own role.
19
+ */
20
+ function listenToBooks(constraints, react, error = logListenError) {
14
21
  if (!db)
15
22
  throw NO_DATABASE_CONNECTION;
16
- try {
17
- return onSnapshot(query(collection(db, 'books'), constraint), (snapshot) => react(snapshot.empty
18
- ? []
19
- : snapshot.docs.map((doc) => Book.fromJSON(doc.id, doc.data()))));
20
- }
21
- catch (err) {
22
- throw 'Issue querying database';
23
- }
23
+ return onSnapshot(query(collection(db, 'books'), ...constraints), (snapshot) => react(toBooks(snapshot.docs)), error);
24
24
  }
25
- export function listenToPublishedBooks(react) {
26
- return listenToBooks(where('published', '==', true), react);
25
+ export function listenToPublishedBooks(react, error) {
26
+ return listenToBooks([where('published', '==', true)], react, error);
27
27
  }
28
- export function listenToEditableBooks(userID, react) {
29
- return listenToBooks(where('uids', 'array-contains', userID), react);
28
+ export function listenToEditableBooks(userID, react, error) {
29
+ return listenToBooks([where('uids', 'array-contains', userID)], react, error);
30
30
  }
31
- export function listenToPartiallyEditableBooks(userID, react) {
32
- return listenToBooks(where('readuids', 'array-contains', userID), react);
31
+ export function listenToPartiallyEditableBooks(userID, react, error) {
32
+ return listenToBooks([where('readuids', 'array-contains', userID)], react, error);
33
33
  }
34
- export function listenToBooksByName(name, react) {
35
- return listenToBooks(where('domain', '==', name), react);
34
+ /**
35
+ * Listen to the books with the given subdomain that the current user may
36
+ * read: published ones, and drafts they collaborate on. That takes three
37
+ * queries, since rules can't prove an unconstrained domain query is safe;
38
+ * results are merged, and reported once each query has answered.
39
+ */
40
+ export function listenToBooksByName(name, react, error = logListenError) {
41
+ const uid = auth?.currentUser?.uid;
42
+ const named = where('domain', '==', name);
43
+ const constraints = [
44
+ [named, where('published', '==', true)],
45
+ ...(uid
46
+ ? [
47
+ [named, where('uids', 'array-contains', uid)],
48
+ [named, where('readuids', 'array-contains', uid)],
49
+ ]
50
+ : []),
51
+ ];
52
+ const results = constraints.map(() => undefined);
53
+ let failed = false;
54
+ const unsubscribes = constraints.map((constraint, index) => listenToBooks(constraint, (books) => {
55
+ results[index] = books;
56
+ if (failed || results.some((r) => r === undefined))
57
+ return;
58
+ const byID = new Map();
59
+ for (const book of results.flat())
60
+ if (book)
61
+ byID.set(book.getID(), book);
62
+ react([...byID.values()]);
63
+ }, (e) => {
64
+ if (failed)
65
+ return;
66
+ failed = true;
67
+ error(e);
68
+ }));
69
+ return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
36
70
  }
37
- export function listenToBookWithID(id, react) {
71
+ export function listenToBookWithID(id, react, error = logListenError) {
38
72
  if (!db)
39
73
  throw NO_DATABASE_CONNECTION;
40
- const ref = doc(db, 'books', id);
41
74
  return onSnapshot(doc(db, 'books', id), (doc) => {
42
75
  if (!doc.metadata.hasPendingWrites)
43
76
  react(doc.exists()
44
77
  ? Book.fromJSON(id, doc.data())
45
78
  : null);
46
- });
79
+ }, error);
47
80
  }
48
- export function listenToEdition(bookID, editionID, react) {
81
+ export function listenToEdition(bookID, editionID, react, error = logListenError) {
49
82
  if (!db)
50
83
  throw NO_DATABASE_CONNECTION;
51
84
  return onSnapshot(doc(db, 'books', bookID, 'editions', editionID), (doc) => {
@@ -53,9 +86,9 @@ export function listenToEdition(bookID, editionID, react) {
53
86
  react(doc.exists()
54
87
  ? Edition.fromJSON(doc.ref, doc.data())
55
88
  : null);
56
- });
89
+ }, error);
57
90
  }
58
- export function listenToChapters(bookID, editionID, react) {
91
+ export function listenToChapters(bookID, editionID, react, error = logListenError) {
59
92
  if (!db)
60
93
  throw NO_DATABASE_CONNECTION;
61
94
  return onSnapshot(collection(db, 'books', bookID, 'editions', editionID, 'chapters'), (docs) => {
@@ -69,7 +102,7 @@ export function listenToChapters(bookID, editionID, react) {
69
102
  chapters.push([doc.ref, doc.data().text ?? '']);
70
103
  });
71
104
  react(chapters);
72
- });
105
+ }, error);
73
106
  }
74
107
  /////////////////
75
108
  //// MANAGE USERS
@@ -77,7 +110,7 @@ export function listenToChapters(bookID, editionID, react) {
77
110
  /** Hit the authentication database to get user emails. */
78
111
  export async function getUserEmails(uids) {
79
112
  if (!functions)
80
- throw Error("Can't publish, no connection to Firebase functions.");
113
+ throw Error('Not connected to Firebase functions.');
81
114
  // The function only answers signed-in users, and a page load can get here
82
115
  // before Firebase has restored the sign-in, so wait for it.
83
116
  await auth?.authStateReady();
@@ -91,7 +124,7 @@ export async function getUserEmails(uids) {
91
124
  }
92
125
  export async function createUser(email) {
93
126
  if (!functions)
94
- throw Error("Can't publish, no connection to Firebase functions.");
127
+ throw Error('Not connected to Firebase functions.');
95
128
  const createUserWithEmail = httpsCallable(functions, 'createUserWithEmailGen2');
96
129
  const result = await createUserWithEmail({
97
130
  email,
@@ -151,14 +184,16 @@ export async function createNewEdition(book) {
151
184
  return book;
152
185
  const latestDraft = Edition.fromJSON(latestDraftDoc.ref, latestDraftData);
153
186
  // Make a copy without chapter and edition refs, because we want to create new ones,
154
- // and with an incremented edition number.
155
- let newEdition = latestDraft.withoutRefs();
187
+ // with an incremented edition number, as an unpublished draft (only
188
+ // publishers may create published editions, and a new edition isn't).
189
+ let newEdition = latestDraft
190
+ .withoutRefs()
191
+ .withIncrementedEditionNumber()
192
+ .asPublished(false);
156
193
  // Create a copy of the existing draft as a new edition.
157
194
  const newEditionRef = await addDoc(collection(db, 'books', book.id, 'editions'), newEdition.toObject());
158
- // Create a new edition that has the new ref and an updated edition number.
159
- newEdition = newEdition
160
- .withRef(newEditionRef)
161
- .withIncrementedEditionNumber();
195
+ // Remember the new edition's ref.
196
+ newEdition = newEdition.withRef(newEditionRef);
162
197
  // Add the chapter text of the existing edition into the new edition's chapters, so it gets copied over. We have to do this because the chapter text is stored in the chapter documents, not the edition document.
163
198
  const textByID = new Map();
164
199
  for (const chapter of latestDraft.chapters) {
@@ -187,17 +222,41 @@ export async function createNewEdition(book) {
187
222
  await updateBook(book);
188
223
  return book;
189
224
  }
225
+ /**
226
+ * Take (lock) or release a lease on some content of an edition, so two
227
+ * people don't edit it at once. Only the edition's `active` field is written,
228
+ * in a transaction, so a lease can't overwrite edits made elsewhere since the
229
+ * edition was loaded, and can't be taken while someone else holds it.
230
+ * Returns whether the caller holds the lease afterwards.
231
+ */
190
232
  export async function updateLock(edition, uid, content, lock) {
191
233
  if (!db)
192
234
  throw NO_DATABASE_CONNECTION;
193
- if (edition.editionRef === undefined)
235
+ const database = db;
236
+ const editionRef = edition.editionRef;
237
+ if (editionRef === undefined)
194
238
  return false;
195
- if (lock && edition.hasLease(uid, content))
196
- return true;
197
- if (!lock && !edition.hasLease(uid, content))
198
- return true;
199
- await setDoc(doc(db, editionPath(edition.bookRef.id, edition.editionRef.id)), edition.withLock(uid, content, lock).toObject());
200
- return lock;
239
+ const ref = doc(database, editionPath(edition.bookRef.id, editionRef.id));
240
+ return runTransaction(database, async (transaction) => {
241
+ const current = await transaction.get(ref);
242
+ const active = (current.data()?.active ?? {});
243
+ const holder = active[content];
244
+ if (lock) {
245
+ if (holder === uid)
246
+ return true;
247
+ if (holder !== undefined)
248
+ return false;
249
+ transaction.update(ref, { [`active.${content}`]: uid });
250
+ return true;
251
+ }
252
+ else {
253
+ if (holder === uid)
254
+ transaction.update(ref, {
255
+ [`active.${content}`]: deleteField(),
256
+ });
257
+ return false;
258
+ }
259
+ });
201
260
  }
202
261
  /**
203
262
  * Persists the edition in the database, creating and deleting chapters as necessary.
@@ -256,7 +315,7 @@ export async function updateEdition(book, previousEdition, newEdition) {
256
315
  const newKeys = Object.keys(newInfo);
257
316
  if (previousKeys.length !== newKeys.length ||
258
317
  !previousKeys.every((key) => previousInfo[key] === newInfo[key])) {
259
- updateBook(book.withRevisedEdition(previousEdition, newEdition));
318
+ await updateBook(book.withRevisedEdition(previousEdition, newEdition));
260
319
  }
261
320
  }
262
321
  }
@@ -269,34 +328,13 @@ export async function updateBook(book) {
269
328
  throw Error("Can't update book, not connected to Firebase.");
270
329
  await setDoc(doc(db, 'books', book.getID()), book.toJSON());
271
330
  }
331
+ /**
332
+ * Whether no book has claimed this subdomain yet. Drafts aren't readable by
333
+ * everyone, so this asks a function that can see every book.
334
+ */
272
335
  export async function isSubdomainAvailable(subdomain) {
273
- if (!db)
274
- throw Error('Not connected to Firebase.');
275
- return (await getBookIDWithSubdomain(subdomain)) === null;
276
- }
277
- export async function getBookIDWithSubdomain(subdomain) {
278
- if (!db)
279
- throw Error('Not connected to Firebase.');
280
- const matches = await getDocs(query(collection(db, 'books'), where('domain', '==', subdomain)));
281
- return matches.empty ? null : matches.docs[0].id;
282
- }
283
- export async function publish(edition) {
284
- if (!db)
285
- throw Error('Cannot publish, no database connection');
286
336
  if (!functions)
287
- throw Error('Cannot publish, no cloud connection');
288
- const editionRef = edition.getEditionRef();
289
- const bookRef = edition.getBookRef();
290
- if (editionRef === undefined)
291
- return `Cannot publish, no edition ID`;
292
- // Get a reference to the publishing function
293
- const publishEdition = httpsCallable(functions, 'publishEdition');
294
- // Call the function, passing
295
- const result = await publishEdition({
296
- bookID: bookRef.id,
297
- editionID: editionRef.id,
298
- });
299
- return result.data;
300
- // Update the edition's published status in the book.
301
- // await updateBook(book.withEditionAsPublished(true, index));
337
+ throw Error('Not connected to Firebase.');
338
+ const check = httpsCallable(functions, 'isSubdomainAvailableGen2');
339
+ return (await check({ domain: subdomain })).data.available;
302
340
  }
@@ -19,7 +19,7 @@ export default class Book {
19
19
  // The published state is always true if some edition's published flag isn't null.
20
20
  this.published = editions.some((edition) => edition.published !== null);
21
21
  // We always keep editions in ascending edition number for easy reference.
22
- this.editions = editions.sort((a, b) => a.number - b.number);
22
+ this.editions = editions.toSorted((a, b) => a.number - b.number);
23
23
  this.domain = domain;
24
24
  this.uids = uids;
25
25
  this.media = new BookMedia(this);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,124 @@
1
+ import { describe, test, expect } from 'vitest';
2
+ import Book, {} from './Book';
3
+ import { makeEdition } from '../../../tests/fixtures';
4
+ function info(id, number, options = {}) {
5
+ return {
6
+ ref: { id },
7
+ summary: '',
8
+ number,
9
+ published: null,
10
+ editionuids: [],
11
+ chapteruids: [],
12
+ ...options,
13
+ };
14
+ }
15
+ function book(editions, uids = ['owner']) {
16
+ return new Book('b', 'Title', [], '', null, editions, null, uids);
17
+ }
18
+ describe('toJSON readuids', () => {
19
+ test('is the union of every edition’s edition and chapter uids', () => {
20
+ const json = book([
21
+ info('e1', 1, { editionuids: ['a', 'b'], chapteruids: ['c'] }),
22
+ info('e2', 2, { editionuids: ['b'], chapteruids: ['c', 'd'] }),
23
+ ]).toJSON();
24
+ expect(json.readuids.toSorted()).toEqual(['a', 'b', 'c', 'd']);
25
+ });
26
+ test('has no duplicates', () => {
27
+ const json = book([
28
+ info('e1', 1, { editionuids: ['a', 'a'], chapteruids: ['a'] }),
29
+ ]).toJSON();
30
+ expect(json.readuids).toEqual(['a']);
31
+ });
32
+ test('is empty when no edition grants access', () => {
33
+ expect(book([info('e1', 1)]).toJSON().readuids).toEqual([]);
34
+ expect(book([]).toJSON().readuids).toEqual([]);
35
+ });
36
+ test('does not include book-level editors, who have their own access', () => {
37
+ const json = book([info('e1', 1, { editionuids: ['x'] })], ['owner']).toJSON();
38
+ expect(json.readuids).toEqual(['x']);
39
+ expect(json.uids).toEqual(['owner']);
40
+ });
41
+ test('tracks revisions to an edition’s editors', () => {
42
+ const b = book([info('edition1', 1, { editionuids: ['old'] })]);
43
+ const edition = makeEdition().withEditors(['new']);
44
+ const revised = b.withRevisedEdition(edition, edition);
45
+ expect(revised.toJSON().readuids).toEqual(['new']);
46
+ });
47
+ test('serializes every field', () => {
48
+ const editions = [info('e1', 1, { published: 5 })];
49
+ expect(new Book('b', 'T', ['A'], 'D', 'cover', editions, 'sub', [
50
+ 'u',
51
+ ]).toJSON()).toEqual({
52
+ title: 'T',
53
+ authors: ['A'],
54
+ description: 'D',
55
+ cover: 'cover',
56
+ published: true,
57
+ domain: 'sub',
58
+ editions,
59
+ uids: ['u'],
60
+ readuids: [],
61
+ });
62
+ });
63
+ });
64
+ describe('editions', () => {
65
+ test('keeps editions sorted without mutating the caller’s array', () => {
66
+ const editions = [info('e2', 2), info('e1', 1), info('e3', 3)];
67
+ const b = book(editions);
68
+ expect(b.getEditions().map((e) => e.number)).toEqual([1, 2, 3]);
69
+ expect(editions.map((e) => e.number)).toEqual([2, 1, 3]);
70
+ });
71
+ test('published reflects whether any edition is published', () => {
72
+ expect(book([info('e1', 1)]).published).toBe(false);
73
+ expect(book([info('e1', 1), info('e2', 2, { published: 1 })]).published).toBe(true);
74
+ });
75
+ test('getLatestEditionID', () => {
76
+ expect(book([
77
+ info('e2', 2),
78
+ info('e3', 3),
79
+ info('e1', 1),
80
+ ]).getLatestEditionID()).toBe('e3');
81
+ expect(book([]).getLatestEditionID()).toBeUndefined();
82
+ });
83
+ test('getLatestPublishedEditionID', () => {
84
+ expect(book([
85
+ info('e3', 3),
86
+ info('e2', 2, { published: 100 }),
87
+ info('e1', 1, { published: 50 }),
88
+ ]).getLatestPublishedEditionID()).toBe('e2');
89
+ expect(book([info('e1', 1)]).getLatestPublishedEditionID()).toBeUndefined();
90
+ });
91
+ test('getEditionNumberID', () => {
92
+ const b = book([info('e1', 1), info('e2', 2)]);
93
+ expect(b.getEditionNumberID(2)).toBe('e2');
94
+ expect(b.getEditionNumberID(3)).toBeUndefined();
95
+ });
96
+ test('withRevisedEdition replaces the edition with the same number', () => {
97
+ const b = book([info('edition1', 1), info('e2', 2)]);
98
+ const previous = makeEdition();
99
+ const revised = previous.withSummary('New summary');
100
+ const newBook = b.withRevisedEdition(previous, revised);
101
+ expect(newBook.getEditions().map((e) => e.summary)).toEqual([
102
+ 'New summary',
103
+ '',
104
+ ]);
105
+ expect(b.getEditions()[0].summary).toBe('');
106
+ });
107
+ test('withRevisedEdition ignores unknown or ref-less editions', () => {
108
+ const b = book([info('e2', 2)]);
109
+ const previous = makeEdition();
110
+ expect(b.withRevisedEdition(previous, previous)).toBe(b);
111
+ expect(book([info('edition1', 1)]).withRevisedEdition(previous, previous.withRef(undefined))).toBeInstanceOf(Book);
112
+ });
113
+ });
114
+ describe('subdomains', () => {
115
+ test('withSubdomain sets, and empty clears', () => {
116
+ const b = book([]);
117
+ expect(b.getSubdomain()).toBeNull();
118
+ const named = b.withSubdomain('amy');
119
+ expect(named.getSubdomain()).toBe('amy');
120
+ expect(named.hasSubdomain('amy')).toBe(true);
121
+ expect(named.withSubdomain('').getSubdomain()).toBeNull();
122
+ expect(b.getSubdomain()).toBeNull();
123
+ });
124
+ });
@@ -1,5 +1,10 @@
1
1
  import type { StorageReference } from 'firebase/storage';
2
2
  import type Book from './Book';
3
+ /**
4
+ * The name to store an uploaded file under: the file's name with a unique suffix
5
+ * before its extension, so uploads with the same name don't collide.
6
+ */
7
+ export declare function getUploadName(fileName: string, unique: string): string;
3
8
  export type Image = {
4
9
  url: string;
5
10
  thumb: string;