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
@@ -0,0 +1,96 @@
1
+ <script lang="ts">/**
2
+ * Shown when Bookish refuses to save an author's edits (for example,
3
+ * because their access was revoked while they were writing). The edits
4
+ * are still on screen; this explains what happened and lets the author
5
+ * copy them before they're lost.
6
+ */
7
+ import Button from "../app/Button.svelte";
8
+ import { getUnsaved } from "./Contexts";
9
+ let { reload = () => location.reload() } = $props();
10
+ const unsaved = getUnsaved();
11
+ let copied = $state(false);
12
+ let fallback = $state(undefined);
13
+ let showFallback = $state(false);
14
+ let text = $derived(($unsaved?.chapters ?? []).map((chapter) => `${chapter.title}\n\n${chapter.text}`).join("\n\n\n"));
15
+ async function copy() {
16
+ try {
17
+ await navigator.clipboard.writeText(text);
18
+ copied = true;
19
+ } catch {
20
+ // Some browsers refuse the clipboard; offer the text to select.
21
+ showFallback = true;
22
+ }
23
+ }
24
+ $effect(() => {
25
+ if (showFallback && fallback) {
26
+ fallback.focus();
27
+ fallback.select();
28
+ }
29
+ });
30
+ </script>
31
+
32
+ {#if $unsaved}
33
+ <section class="unsaved" role="alert" aria-labelledby="unsaved-title">
34
+ <p id="unsaved-title">
35
+ <strong>Your latest changes couldn’t be saved</strong> because you
36
+ no longer have permission to edit
37
+ {$unsaved.chapters.length === 1
38
+ ? `“${$unsaved.chapters[0].title}”`
39
+ : 'these chapters'}. They’re still here; copy them before you
40
+ leave.
41
+ </p>
42
+ <div class="actions">
43
+ <Button tooltip="copy unsaved text" command={copy}
44
+ >{copied ? 'copied' : 'copy unsaved text'}</Button
45
+ >
46
+ <Button
47
+ tooltip="discard unsaved changes and reload"
48
+ command={reload}>discard and reload</Button
49
+ >
50
+ </div>
51
+ {#if showFallback}
52
+ <textarea
53
+ bind:this={fallback}
54
+ readonly
55
+ aria-label="Unsaved text"
56
+ rows="6">{text}</textarea
57
+ >
58
+ {/if}
59
+ </section>
60
+ {/if}
61
+
62
+ <style>
63
+ .unsaved {
64
+ box-sizing: border-box;
65
+ width: 100%;
66
+ max-width: 50em;
67
+ margin: var(--app-chrome-padding) auto;
68
+ padding: var(--app-chrome-padding);
69
+ padding-left: calc(2 * var(--app-chrome-padding));
70
+ /* The app's Instructions pattern (a rule down the left side), with
71
+ the rule in the error color as the notice's one red accent. */
72
+ border-left: var(--app-chrome-border-size) solid var(--app-error-color);
73
+ background: var(--app-background-color);
74
+ color: var(--app-font-color);
75
+ font-family: var(--app-font);
76
+ font-size: var(--app-chrome-font-size);
77
+ display: flex;
78
+ flex-direction: column;
79
+ gap: var(--app-chrome-padding);
80
+ }
81
+ p {
82
+ margin: 0;
83
+ }
84
+ strong {
85
+ font-weight: 700;
86
+ }
87
+ .actions {
88
+ display: flex;
89
+ flex-wrap: wrap;
90
+ gap: var(--app-chrome-padding);
91
+ }
92
+ textarea {
93
+ width: 100%;
94
+ font-family: var(--bookish-paragraph-font-family, serif);
95
+ }
96
+ </style>
@@ -0,0 +1,7 @@
1
+ interface Props {
2
+ /** Reloads the page; replaceable for tests. */
3
+ reload?: () => void;
4
+ }
5
+ declare const UnsavedNotice: import("svelte").Component<Props, {}, "">;
6
+ type UnsavedNotice = ReturnType<typeof UnsavedNotice>;
7
+ export default UnsavedNotice;
@@ -23,12 +23,14 @@ import FootnoteNode from '../models/chapter/FootnoteNode';
23
23
  import FormatNode from '../models/chapter/FormatNode';
24
24
  import InlineCodeNode from '../models/chapter/InlineCodeNode';
25
25
  import LabelNode from '../models/chapter/LabelNode';
26
+ import SymbolNode from '../models/chapter/SymbolNode';
26
27
  import LineBreakNode from '../models/chapter/LineBreakNode';
27
28
  import LinkNode from '../models/chapter/LinkNode';
28
29
  import ListNode from '../models/chapter/ListNode';
29
30
  import ParagraphNode from '../models/chapter/ParagraphNode';
30
31
  import QuoteNode from '../models/chapter/QuoteNode';
31
32
  import RuleNode from '../models/chapter/RuleNode';
33
+ import SymbolBlockNode from '../models/chapter/SymbolBlockNode';
32
34
  import TableNode from '../models/chapter/TableNode';
33
35
  import TextNode from '../models/chapter/TextNode';
34
36
  /**
@@ -120,6 +122,12 @@ function block_(node, local) {
120
122
  return table(node, local);
121
123
  if (node instanceof RuleNode)
122
124
  return '<hr/>';
125
+ // Lines of symbols expand to the blocks their definitions make.
126
+ if (node instanceof SymbolBlockNode)
127
+ return node
128
+ .getBlocks()
129
+ .map((b) => block_(b, local))
130
+ .join('\n');
123
131
  // Editorial comments and parse errors are for authors, not readers.
124
132
  if (node instanceof CommentNode || node instanceof ErrorNode)
125
133
  return '';
@@ -239,6 +247,13 @@ function inline(node, local) {
239
247
  if (node instanceof LabelNode)
240
248
  // An empty anchor, so links to this label resolve. toHTML() drops these.
241
249
  return `<span id="${escapeAttribute(node.getMeta())}"></span>`;
250
+ // Symbols expand to their definitions; undefined ones stay as written.
251
+ if (node instanceof SymbolNode) {
252
+ const definition = node.getDefinition();
253
+ return definition
254
+ ? inline(definition, local)
255
+ : escapeText(`@${node.getName()}`);
256
+ }
242
257
  // Editorial comments never reach readers.
243
258
  if (node instanceof CommentNode)
244
259
  return '';
@@ -1,19 +1,35 @@
1
- import { type DocumentReference } from 'firebase/firestore';
1
+ import { type DocumentReference, type FirestoreError } from 'firebase/firestore';
2
2
  import Edition from './book/Edition';
3
3
  import Book from './book/Book';
4
4
  import type { Unsubscribe } from 'firebase/auth';
5
- export declare function listenToPublishedBooks(react: (books: Book[]) => void): Unsubscribe;
6
- export declare function listenToEditableBooks(userID: string, react: (books: Book[]) => void): Unsubscribe;
7
- export declare function listenToPartiallyEditableBooks(userID: string, react: (books: Book[]) => void): Unsubscribe;
8
- export declare function listenToBooksByName(name: string, react: (book: Book[]) => void): Unsubscribe;
9
- export declare function listenToBookWithID(id: string, react: (book: Book | null) => void): Unsubscribe;
10
- export declare function listenToEdition(bookID: string, editionID: string, react: (edition: Edition | null) => void): Unsubscribe;
11
- export declare function listenToChapters(bookID: string, editionID: string, react: (chapters: [DocumentReference, string][]) => void): Unsubscribe;
5
+ /** Called when a listener fails, e.g. because the rules deny access or the
6
+ * connection is lost. Listeners stop after an error. */
7
+ export type ListenError = (error: FirestoreError) => void;
8
+ export declare function listenToPublishedBooks(react: (books: Book[]) => void, error?: ListenError): Unsubscribe;
9
+ export declare function listenToEditableBooks(userID: string, react: (books: Book[]) => void, error?: ListenError): Unsubscribe;
10
+ export declare function listenToPartiallyEditableBooks(userID: string, react: (books: Book[]) => void, error?: ListenError): Unsubscribe;
11
+ /**
12
+ * Listen to the books with the given subdomain that the current user may
13
+ * read: published ones, and drafts they collaborate on. That takes three
14
+ * queries, since rules can't prove an unconstrained domain query is safe;
15
+ * results are merged, and reported once each query has answered.
16
+ */
17
+ export declare function listenToBooksByName(name: string, react: (books: Book[]) => void, error?: ListenError): Unsubscribe;
18
+ export declare function listenToBookWithID(id: string, react: (book: Book | null) => void, error?: ListenError): Unsubscribe;
19
+ export declare function listenToEdition(bookID: string, editionID: string, react: (edition: Edition | null) => void, error?: ListenError): Unsubscribe;
20
+ export declare function listenToChapters(bookID: string, editionID: string, react: (chapters: [DocumentReference, string][]) => void, error?: ListenError): Unsubscribe;
12
21
  /** Hit the authentication database to get user emails. */
13
22
  export declare function getUserEmails(uids: string[]): Promise<Map<string, string> | null>;
14
23
  export declare function createUser(email: string): Promise<string | null>;
15
24
  export declare function createBook(userID: string): Promise<string>;
16
25
  export declare function createNewEdition(book: Book): Promise<Book>;
26
+ /**
27
+ * Take (lock) or release a lease on some content of an edition, so two
28
+ * people don't edit it at once. Only the edition's `active` field is written,
29
+ * in a transaction, so a lease can't overwrite edits made elsewhere since the
30
+ * edition was loaded, and can't be taken while someone else holds it.
31
+ * Returns whether the caller holds the lease afterwards.
32
+ */
17
33
  export declare function updateLock(edition: Edition, uid: string, content: string, lock: boolean): Promise<boolean>;
18
34
  /**
19
35
  * Persists the edition in the database, creating and deleting chapters as necessary.
@@ -21,8 +37,8 @@ export declare function updateLock(edition: Edition, uid: string, content: strin
21
37
  */
22
38
  export declare function updateEdition(book: Book, previousEdition: Edition | undefined, newEdition: Edition): Promise<Map<string, DocumentReference>>;
23
39
  export declare function updateBook(book: Book): Promise<void>;
40
+ /**
41
+ * Whether no book has claimed this subdomain yet. Drafts aren't readable by
42
+ * everyone, so this asks a function that can see every book.
43
+ */
24
44
  export declare function isSubdomainAvailable(subdomain: string): Promise<boolean>;
25
- export declare function getBookIDWithSubdomain(subdomain: string): Promise<string | null>;
26
- export declare function publish(edition: Edition): Promise<string | {
27
- url: string;
28
- }>;
@@ -0,0 +1 @@
1
+ export {};
@@ -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
+ });