bookish-press 0.11.2 → 0.12.1

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 (97) 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 +79 -0
  4. package/dist/components/chapter/Format.svelte +11 -1
  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/ImageChooser.svelte +8 -5
  15. package/dist/components/editor/ImageChooser.test.d.ts +1 -0
  16. package/dist/components/editor/ImageChooser.test.js +67 -0
  17. package/dist/components/editor/Permissions.svelte +10 -2
  18. package/dist/components/page/BookLoader.svelte +43 -6
  19. package/dist/components/page/BulkReferenceEditor.svelte +2 -2
  20. package/dist/components/page/Chapter.svelte +77 -70
  21. package/dist/components/page/Contexts.d.ts +14 -0
  22. package/dist/components/page/Contexts.js +14 -4
  23. package/dist/components/page/Edition.svelte +2 -10
  24. package/dist/components/page/EditionLoader.svelte +40 -7
  25. package/dist/components/page/Index.svelte +1 -1
  26. package/dist/components/page/Publish.svelte +0 -42
  27. package/dist/components/page/Reference.svelte +2 -2
  28. package/dist/components/page/References.svelte +5 -6
  29. package/dist/components/page/TitlePage.svelte +65 -0
  30. package/dist/components/page/TitlePage.svelte.d.ts +20 -0
  31. package/dist/components/page/UnsavedNotice.svelte +96 -0
  32. package/dist/components/page/UnsavedNotice.svelte.d.ts +7 -0
  33. package/dist/epub/xhtml.js +15 -0
  34. package/dist/models/CRUD.d.ts +28 -12
  35. package/dist/models/CRUD.emu.test.d.ts +1 -0
  36. package/dist/models/CRUD.emu.test.js +250 -0
  37. package/dist/models/CRUD.js +110 -72
  38. package/dist/models/book/Book.js +1 -1
  39. package/dist/models/book/Book.test.d.ts +1 -0
  40. package/dist/models/book/Book.test.js +124 -0
  41. package/dist/models/book/BookMedia.d.ts +5 -0
  42. package/dist/models/book/BookMedia.js +23 -7
  43. package/dist/models/book/BookMedia.test.d.ts +1 -0
  44. package/dist/models/book/BookMedia.test.js +40 -0
  45. package/dist/models/book/Chapter.js +28 -12
  46. package/dist/models/book/Chapter.test.d.ts +1 -0
  47. package/dist/models/book/Chapter.test.js +167 -0
  48. package/dist/models/book/Edition.d.ts +2 -0
  49. package/dist/models/book/Edition.js +34 -25
  50. package/dist/models/book/Edition.test.d.ts +1 -0
  51. package/dist/models/book/Edition.test.js +342 -0
  52. package/dist/models/book/Reference.js +5 -9
  53. package/dist/models/book/Reference.test.d.ts +1 -0
  54. package/dist/models/book/Reference.test.js +40 -0
  55. package/dist/models/book/Theme.js +34 -34
  56. package/dist/models/chapter/BlocksNode.d.ts +2 -0
  57. package/dist/models/chapter/BlocksNode.js +59 -3
  58. package/dist/models/chapter/BlocksNode.test.js +2 -2
  59. package/dist/models/chapter/Caret.js +12 -3
  60. package/dist/models/chapter/Caret.test.d.ts +1 -0
  61. package/dist/models/chapter/Caret.test.js +127 -0
  62. package/dist/models/chapter/ChapterNode.d.ts +3 -0
  63. package/dist/models/chapter/ChapterNode.js +11 -1
  64. package/dist/models/chapter/CommentNode.js +3 -2
  65. package/dist/models/chapter/EmbedNode.js +1 -1
  66. package/dist/models/chapter/FootnoteNode.js +1 -1
  67. package/dist/models/chapter/FormatNode.d.ts +5 -1
  68. package/dist/models/chapter/FormatNode.js +60 -20
  69. package/dist/models/chapter/LabelNode.js +4 -2
  70. package/dist/models/chapter/ListNode.js +11 -13
  71. package/dist/models/chapter/Node.test.js +2 -11
  72. package/dist/models/chapter/Operations.test.d.ts +1 -0
  73. package/dist/models/chapter/Operations.test.js +298 -0
  74. package/dist/models/chapter/ParagraphNode.js +29 -3
  75. package/dist/models/chapter/Parser.d.ts +49 -4
  76. package/dist/models/chapter/Parser.js +210 -88
  77. package/dist/models/chapter/Parser.test.js +31 -0
  78. package/dist/models/chapter/Roundtrip.test.d.ts +1 -0
  79. package/dist/models/chapter/Roundtrip.test.js +313 -0
  80. package/dist/models/chapter/SymbolBlockNode.d.ts +40 -0
  81. package/dist/models/chapter/SymbolBlockNode.js +75 -0
  82. package/dist/models/chapter/SymbolBlockNode.test.d.ts +1 -0
  83. package/dist/models/chapter/SymbolBlockNode.test.js +130 -0
  84. package/dist/models/chapter/SymbolNode.d.ts +32 -0
  85. package/dist/models/chapter/SymbolNode.js +61 -0
  86. package/dist/models/chapter/SymbolNode.test.d.ts +1 -0
  87. package/dist/models/chapter/SymbolNode.test.js +177 -0
  88. package/dist/models/chapter/TableNode.js +2 -2
  89. package/dist/models/chapter/TextNode.d.ts +8 -1
  90. package/dist/models/chapter/TextNode.js +22 -15
  91. package/dist/util/getSubdomain.js +5 -1
  92. package/dist/util/getSubdomain.test.d.ts +1 -0
  93. package/dist/util/getSubdomain.test.js +53 -0
  94. package/dist/util/mineReference.js +12 -5
  95. package/dist/util/mineReference.test.d.ts +1 -0
  96. package/dist/util/mineReference.test.js +62 -0
  97. package/package.json +12 -7
@@ -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;
@@ -10,6 +10,17 @@ async function loadStorage() {
10
10
  ]);
11
11
  return storage === undefined ? undefined : { storage, ...api };
12
12
  }
13
+ /**
14
+ * The name to store an uploaded file under: the file's name with a unique suffix
15
+ * before its extension, so uploads with the same name don't collide.
16
+ */
17
+ export function getUploadName(fileName, unique) {
18
+ // The extension is whatever follows the last dot, unless the dot starts the name (as in .hidden).
19
+ const dot = fileName.lastIndexOf('.');
20
+ const name = dot > 0 ? fileName.substring(0, dot) : fileName;
21
+ const extension = dot > 0 ? fileName.substring(dot + 1) : '';
22
+ return `${name}-${unique}${extension.length > 0 ? `.${extension}` : ''}`;
23
+ }
13
24
  export default class BookMedia {
14
25
  book;
15
26
  _images;
@@ -75,11 +86,18 @@ export default class BookMedia {
75
86
  // https://[firebase-domain]/v0/b/[projectid].appspot.com/o/images%2F[bookID]%2F[imagename]?alt=media
76
87
  // And we want
77
88
  // https://[firebase-domain]/v0/b/[projectid].appspot.com/o/images%2F[bookID]%2Fthumbnails%2F[imagename]?alt=media
89
+ // Find the book ID as a path segment in the object path, so a book ID that happens to
90
+ // appear elsewhere in the URL (such as the project ID) isn't mistaken for it.
78
91
  const bookID = this.book.getID();
79
- const bookIDIndex = url.indexOf(bookID);
80
- return bookIDIndex >= 0
81
- ? `${url.substring(0, bookIDIndex)}${bookID}%2Fthumbnails${url.substring(bookIDIndex + bookID.length)}`
82
- : url;
92
+ for (const separator of ['%2F', '/']) {
93
+ const segment = `${separator}${bookID}${separator}`;
94
+ const index = url.indexOf(segment);
95
+ if (index >= 0) {
96
+ const end = index + separator.length + bookID.length;
97
+ return `${url.substring(0, end)}${separator}thumbnails${url.substring(end)}`;
98
+ }
99
+ }
100
+ return url;
83
101
  }
84
102
  async getThumbnailURL(url, thumbnailRef, error, finished, attempt = 0) {
85
103
  const firebase = await loadStorage();
@@ -102,10 +120,8 @@ export default class BookMedia {
102
120
  }
103
121
  uploadWith(firebase, file, errorHandler, finishedHandler) {
104
122
  const { storage, ref, uploadBytes, getDownloadURL } = firebase;
105
- // Get the extension if there is one.
106
- const [name, extension] = file.name.split('.');
107
123
  // We use the file name given, but append a unique string to avoid collisions.
108
- const imageName = `${name}-${crypto.randomUUID()}.${extension ?? ''}`;
124
+ const imageName = getUploadName(file.name, crypto.randomUUID());
109
125
  // The canonical path format for Bookish images in the store is image/{bookid}/{imageid}
110
126
  // where {bookid} is the Firestore document ID of the book being edited and {imageid} is just a random id.
111
127
  const imageRef = ref(storage, `${this.getImagePath()}/${imageName}`);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ import { describe, test, expect } from 'vitest';
2
+ import BookMedia, { getUploadName } from './BookMedia';
3
+ import { makeBook } from '../../../tests/fixtures';
4
+ const media = new BookMedia(makeBook());
5
+ describe('getUploadName', () => {
6
+ const id = 'uuid';
7
+ test('keeps the extension', () => {
8
+ expect(getUploadName('photo.jpg', id)).toBe('photo-uuid.jpg');
9
+ });
10
+ test('uses the last dot for the extension', () => {
11
+ expect(getUploadName('my.photo.jpg', id)).toBe('my.photo-uuid.jpg');
12
+ });
13
+ test('omits the dot when there is no extension', () => {
14
+ expect(getUploadName('photo', id)).toBe('photo-uuid');
15
+ });
16
+ test('treats a leading dot as part of the name', () => {
17
+ expect(getUploadName('.hidden', id)).toBe('.hidden-uuid');
18
+ });
19
+ test('handles a trailing dot', () => {
20
+ expect(getUploadName('photo.', id)).toBe('photo-uuid');
21
+ });
22
+ });
23
+ describe('URLs', () => {
24
+ test('makeThumbnailURL inserts the thumbnails folder after the book ID', () => {
25
+ expect(media.makeThumbnailURL('https://firebasestorage.googleapis.com/v0/b/p.appspot.com/o/images%2Ftestbook%2Fcat.png?alt=media')).toBe('https://firebasestorage.googleapis.com/v0/b/p.appspot.com/o/images%2Ftestbook%2Fthumbnails%2Fcat.png?alt=media');
26
+ });
27
+ test('makeThumbnailURL leaves URLs without the book ID alone', () => {
28
+ expect(media.makeThumbnailURL('https://example.com/cat.png')).toBe('https://example.com/cat.png');
29
+ });
30
+ test('makeThumbnailURL finds the book ID in the image path, not elsewhere', () => {
31
+ expect(media.makeThumbnailURL('https://host/v0/b/testbook.appspot.com/o/images%2Ftestbook%2Fcat.png?alt=media')).toBe('https://host/v0/b/testbook.appspot.com/o/images%2Ftestbook%2Fthumbnails%2Fcat.png?alt=media');
32
+ });
33
+ test('stripTokenFromURL', () => {
34
+ expect(media.stripTokenFromURL('https://x/a?alt=media&token=abc')).toBe('https://x/a?alt=media');
35
+ expect(media.stripTokenFromURL('https://x/a?alt=media')).toBe('https://x/a?alt=media');
36
+ });
37
+ test('getImagePath', () => {
38
+ expect(media.getImagePath()).toBe('images/testbook/');
39
+ });
40
+ });
@@ -160,10 +160,11 @@ export default class Chapter {
160
160
  return this._ast;
161
161
  }
162
162
  getWordCount(edition) {
163
- if (this._wordCount === undefined)
164
- this._wordCount = this.getAST(edition)
165
- ?.toText()
166
- .split(/\s+/).length;
163
+ if (this._wordCount === undefined) {
164
+ const text = this.getAST(edition)?.toText();
165
+ if (text !== undefined)
166
+ this._wordCount = text.match(/\S+/g)?.length ?? 0;
167
+ }
167
168
  return this._wordCount;
168
169
  }
169
170
  /** Either a number of minutes, or undefined if there's no text yet, or null if forthcoming. */
@@ -185,22 +186,37 @@ export default class Chapter {
185
186
  CommonWords.forEach((word) => commonWords.add(word));
186
187
  // Get all the text in the chapter.
187
188
  let text = ast.toText();
188
- // Split by word boundaries.
189
- const words = text.split(/\b/);
189
+ // Split into alternating words and non-words, keeping both, since we keep non-words for context.
190
+ // Apostrophes are part of words, so contractions stay whole; letters in any script count.
191
+ const words = text
192
+ .split(/([\p{L}\p{M}\p{N}_\u2019']+)/u)
193
+ .filter((token) => token !== '');
190
194
  // Index the words
191
- const index = {};
195
+ // No prototype: book words like "constructor" or "toString"
196
+ // must not find Object's built-in properties.
197
+ const index = Object.create(null);
192
198
  words.forEach((word, wordNumber) => {
193
199
  // Skip non words. We keep them for search results.
194
- if (!/[a-zA-Z\u2019]+/.test(word))
200
+ if (!/\p{L}/u.test(word))
195
201
  return;
196
202
  word = word.toLowerCase();
203
+ // Index possessives under the word they belong to
204
+ // (children’s, students’ → children, students), and drop
205
+ // apostrophes that are really closing quotes (‘hello’).
206
+ const possessive = word.match(/^(.+?)['\u2019]s$/u) ??
207
+ word.match(/^(.+s)['\u2019]$/u);
208
+ if (possessive)
209
+ word = possessive[1];
210
+ else
211
+ word = word.replace(/^['\u2019]+|['\u2019]+$/gu, '');
197
212
  // Should we include?
198
213
  // • It shouldn't be a common word
199
- // • It shouldn't have an apostrophe
214
+ // • It shouldn't be a contraction (they’re, aren’t); names
215
+ // with apostrophes, like D’Ignazio, are fine
200
216
  // • It should be longer than two letters
201
217
  // • It shouldn't end in 'ly'
202
218
  if (!commonWords.has(word) &&
203
- word.indexOf('\u2019') < 0 &&
219
+ !/['\u2019](t|re|ll|ve|d|m)$/u.test(word) &&
204
220
  word.length > 2 &&
205
221
  word.substring(word.length - 2, word.length) !== 'ly') {
206
222
  // If we haven't started a list of occurrences, start one.
@@ -208,11 +224,11 @@ export default class Chapter {
208
224
  index[word] = [];
209
225
  let match = {
210
226
  left: words
211
- .slice(Math.max(0, wordNumber - 10), Math.max(0, wordNumber - 1) + 1)
227
+ .slice(Math.max(0, wordNumber - 10), wordNumber)
212
228
  .join(''),
213
229
  match: words[wordNumber],
214
230
  right: words
215
- .slice(Math.min(words.length - 1, wordNumber + 1), Math.min(words.length - 1, wordNumber + 10) + 1)
231
+ .slice(wordNumber + 1, wordNumber + 11)
216
232
  .join(''),
217
233
  };
218
234
  // Add the occurrence, but a lower case canonical version.
@@ -0,0 +1 @@
1
+ export {};