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,51 @@
1
+ /**
2
+ * The parts of BookishEditor that don't depend on the DOM: what's around the caret,
3
+ * which command a keystroke invokes, pasting, and undo history. Kept here so they can be tested headlessly.
4
+ */
5
+ import type { CaretRange, IndexRange } from '../../models/chapter/Caret.js';
6
+ import type RootNode from '../../models/chapter/RootNode.js';
7
+ import type Edit from '../../models/chapter/Edit.js';
8
+ import Node from '../../models/chapter/Node.js';
9
+ import type CaretContext from './CaretContext';
10
+ import type { PasteContent } from './CaretContext';
11
+ import type Command from './Command';
12
+ import type UndoState from './UndoState';
13
+ /** The parts of the caret context that the editor provides, rather than the document. */
14
+ export type CaretServices = Pick<CaretContext, 'undoStack' | 'undoPosition' | 'undo' | 'redo' | 'clipboard' | 'handleCopy' | 'handlePaste' | 'setAccent' | 'getAccent'>;
15
+ /** True if the range is a caret at the very start of the format it's in. */
16
+ export declare function isAtParagraphStart(root: RootNode, range: CaretRange): boolean;
17
+ /** Describe what's around the given range in the given root, for commands to decide what to do. */
18
+ export declare function getCaretContext(root: RootNode, range: CaretRange, chapter: boolean, services: CaretServices): CaretContext;
19
+ /** The parts of a keyboard event that select a command. */
20
+ export type Keystroke = Pick<KeyboardEvent, 'key' | 'code' | 'shiftKey' | 'altKey' | 'ctrlKey' | 'metaKey'>;
21
+ /** True if the command's signature matches the keystroke and it's active in the context. */
22
+ export declare function commandMatches(command: Command, context: CaretContext, event: Keystroke, press: boolean): boolean;
23
+ /**
24
+ * Escape plain text so that it parses as exactly that text, and not as Bookdown markup.
25
+ * Escaping any character with a backslash makes it literal, so we escape
26
+ * every character that could start markup inside a paragraph, and the characters
27
+ * at the start of a line that could start another kind of block or be skipped as whitespace.
28
+ */
29
+ export declare function escapePlainText(text: string): string;
30
+ /** Parse plain text to paste in the given context. */
31
+ export declare function parsePlainText(context: CaretContext, text: string): Node;
32
+ /** Compute the edit that pastes the given content at the context's caret, replacing any selection. */
33
+ export declare function getPasteEdit(context: CaretContext, content: PasteContent | Node): Edit;
34
+ /**
35
+ * Add an edit to the undo history, which is ordered from newest to oldest, with the given position marking the current state.
36
+ * If the history is empty, the state before the edit is saved first, so it can be undone to.
37
+ * Any states that were undone are discarded, since the edit changes history.
38
+ */
39
+ export declare function withUndoState(stack: UndoState[], position: number, before: {
40
+ bookdown: string;
41
+ range: IndexRange | undefined;
42
+ }, after: UndoState): UndoState[];
43
+ /**
44
+ * Restore the state one step back (undo) or forward (redo) in the undo history, if there is one.
45
+ * If the saved range can't be restored, the caret goes to the start, so it's never left in a stale tree.
46
+ */
47
+ export declare function getHistoryState(stack: UndoState[], position: number, undo: boolean, parse: (bookdown: string) => RootNode | undefined): {
48
+ root: RootNode;
49
+ range: CaretRange;
50
+ position: number;
51
+ } | undefined;
@@ -0,0 +1,201 @@
1
+ import { indexRangeToCaretRange } from '../../models/chapter/Caret.js';
2
+ import ErrorNode from '../../models/chapter/ErrorNode.js';
3
+ import Node from '../../models/chapter/Node.js';
4
+ import ChapterNode from '../../models/chapter/ChapterNode.js';
5
+ import ParagraphNode from '../../models/chapter/ParagraphNode.js';
6
+ import TextNode from '../../models/chapter/TextNode.js';
7
+ import AtomNode from '../../models/chapter/AtomNode.js';
8
+ import FormatNode from '../../models/chapter/FormatNode.js';
9
+ import BlocksNode from '../../models/chapter/BlocksNode.js';
10
+ import BlockNode from '../../models/chapter/BlockNode.js';
11
+ import ListNode from '../../models/chapter/ListNode.js';
12
+ import TableNode from '../../models/chapter/TableNode.js';
13
+ import MetadataNode from '../../models/chapter/MetadataNode.js';
14
+ import CodeNode from '../../models/chapter/CodeNode.js';
15
+ import EmbedNode from '../../models/chapter/EmbedNode.js';
16
+ import Parser from '../../models/chapter/Parser.js';
17
+ import { LINE_BREAK } from '../../models/chapter/Symbols.js';
18
+ /** True if the range is a caret at the very start of the format it's in. */
19
+ export function isAtParagraphStart(root, range) {
20
+ if (range.start.node !== range.end.node ||
21
+ range.start.index !== range.end.index ||
22
+ !(range.start.node instanceof TextNode))
23
+ return false;
24
+ const firstCaret = range.start.node.getFormatRoot(root)?.getFirstCaret();
25
+ return (firstCaret !== undefined &&
26
+ firstCaret.node === range.start.node &&
27
+ firstCaret.index === range.start.index);
28
+ }
29
+ /** Describe what's around the given range in the given root, for commands to decide what to do. */
30
+ export function getCaretContext(root, range, chapter, services) {
31
+ // Determine whether the range contains a list
32
+ let inside = false;
33
+ let includesList = false;
34
+ for (const n of root.getNodes()) {
35
+ if (n === range.start.node)
36
+ inside = true;
37
+ if (inside &&
38
+ n.getClosestParentMatching(root, (p) => p instanceof ListNode) !==
39
+ undefined)
40
+ includesList = true;
41
+ if (n === range.end.node)
42
+ inside = false;
43
+ }
44
+ // Nearest parents first.
45
+ const parents = (root.getParentsOf(range.start.node) ?? []).reverse();
46
+ const find = (kind) => parents.find((n) => n instanceof kind);
47
+ const isTextOrAtom = (node) => node instanceof TextNode ||
48
+ node instanceof AtomNode ||
49
+ node instanceof EmbedNode;
50
+ return {
51
+ chapter,
52
+ // We make a new range so that setting it always causes a re-render
53
+ range: { start: range.start, end: range.end },
54
+ start: range.start,
55
+ end: range.end,
56
+ isSelection: range.start.node !== range.end.node ||
57
+ range.start.index !== range.end.index,
58
+ root,
59
+ blocks: find(BlocksNode),
60
+ paragraph: find(ParagraphNode),
61
+ block: find(BlockNode),
62
+ code: find(CodeNode),
63
+ list: find(ListNode),
64
+ atom: find(AtomNode),
65
+ meta: find(MetadataNode),
66
+ includesList,
67
+ table: find(TableNode),
68
+ formatRoot: range.end.node instanceof TextNode ||
69
+ range.end.node instanceof AtomNode
70
+ ? range.end.node.getFormatRoot(root)
71
+ : undefined,
72
+ startIsText: range.start.node instanceof TextNode,
73
+ endIsText: range.end.node instanceof TextNode,
74
+ startIsTextOrAtom: isTextOrAtom(range.start.node),
75
+ endIsTextOrAtom: isTextOrAtom(range.end.node),
76
+ atParagraphStart: isAtParagraphStart(root, range),
77
+ ...services,
78
+ };
79
+ }
80
+ /** True if the command's signature matches the keystroke and it's active in the context. */
81
+ export function commandMatches(command, context, event, press) {
82
+ return ((command.press === undefined || command.press === press) &&
83
+ (command.shift === undefined || command.shift === event.shiftKey) &&
84
+ (command.alt === undefined || command.alt === event.altKey) &&
85
+ (command.control === undefined ||
86
+ command.control === (event.ctrlKey || event.metaKey)) &&
87
+ (command.key === undefined ||
88
+ (Array.isArray(command.key) && command.key.includes(event.key)) ||
89
+ (command.key instanceof Function && command.key(event.key)) ||
90
+ command.key === event.key) &&
91
+ (command.code === undefined || command.code === event.code) &&
92
+ (command.active === true ||
93
+ (command.active instanceof Function &&
94
+ command.active.call(undefined, context, event.key))));
95
+ }
96
+ /**
97
+ * Escape plain text so that it parses as exactly that text, and not as Bookdown markup.
98
+ * Escaping any character with a backslash makes it literal, so we escape
99
+ * every character that could start markup inside a paragraph, and the characters
100
+ * at the start of a line that could start another kind of block or be skipped as whitespace.
101
+ */
102
+ export function escapePlainText(text) {
103
+ return (text
104
+ // Normalize Windows and old Mac line endings.
105
+ .replace(/\r\n?/g, '\n')
106
+ // Backslashes first, so we don't escape the escapes added below.
107
+ .replace(/([\\_*`@~:^<>{}[\]%])/g, '\\$1')
108
+ .replace(new RegExp(LINE_BREAK, 'g'), `\\${LINE_BREAK}`)
109
+ // Block markers and whitespace at the start of each line.
110
+ .replace(/^([#\-|,"=\s]|[0-9]+\.)/gm, (match) =>
111
+ // Don't escape the newlines that separate lines.
112
+ match === '\n' ? match : `\\${match}`));
113
+ }
114
+ /** Parse plain text to paste in the given context. */
115
+ export function parsePlainText(context, text) {
116
+ const escaped = escapePlainText(text);
117
+ // If we're pasting text into a paragraph node, then we parse it as a series of paragraphs.
118
+ return context.block instanceof ParagraphNode && context.atom === undefined
119
+ ? Parser.parseChapter(undefined, escaped)
120
+ : // Otherwise parse as just a format node, replacing all text newlines with a space.
121
+ Parser.parseFormat(undefined, escaped.replaceAll('\n', ' '));
122
+ }
123
+ /** Compute the edit that pastes the given content at the context's caret, replacing any selection. */
124
+ export function getPasteEdit(context, content) {
125
+ const node = content instanceof Node
126
+ ? content
127
+ : content.plain === undefined
128
+ ? undefined
129
+ : parsePlainText(context, content.plain);
130
+ if (node === undefined)
131
+ return;
132
+ // Track revisions in these two variables.
133
+ let newRoot = context.root;
134
+ let newCaret = context.start;
135
+ // Is there any text to remove? Remove it first.
136
+ if (context.isSelection) {
137
+ const edit = newRoot.withRangeFormatted(context.range, undefined);
138
+ if (edit === undefined ||
139
+ !(edit.root instanceof ChapterNode ||
140
+ edit.root instanceof FormatNode))
141
+ return;
142
+ newRoot = edit.root;
143
+ newCaret = edit.range.start;
144
+ }
145
+ // Find the parents of the caret node in the revised root, from furthest to nearest.
146
+ const parents = newRoot.getParentsOf(newCaret.node);
147
+ if (parents === undefined)
148
+ return;
149
+ // Pop parents, nearest to farthest, searching for one that handles an insertion.
150
+ while (parents.length > 0) {
151
+ const parent = parents.pop();
152
+ if (parent === undefined)
153
+ break;
154
+ // It's critical that we insert a copy and not the node in case people copy multiple times. A node can only appear once in a tree.
155
+ const edit = parent.withNodeInserted(newCaret, node.copy());
156
+ if (edit === undefined)
157
+ continue;
158
+ const revisedRoot = parent === newRoot
159
+ ? edit.root
160
+ : newRoot.withNodeReplaced(parent, edit.root);
161
+ if (revisedRoot === undefined)
162
+ return;
163
+ return { root: revisedRoot, range: edit.range };
164
+ }
165
+ }
166
+ /**
167
+ * Add an edit to the undo history, which is ordered from newest to oldest, with the given position marking the current state.
168
+ * If the history is empty, the state before the edit is saved first, so it can be undone to.
169
+ * Any states that were undone are discarded, since the edit changes history.
170
+ */
171
+ export function withUndoState(stack, position, before, after) {
172
+ let history = stack;
173
+ if (history.length === 0 && before.range !== undefined)
174
+ history = [
175
+ {
176
+ bookdown: before.bookdown,
177
+ command: undefined,
178
+ range: before.range,
179
+ },
180
+ ];
181
+ return [after, ...(position > 0 ? history.slice(position) : history)];
182
+ }
183
+ /**
184
+ * Restore the state one step back (undo) or forward (redo) in the undo history, if there is one.
185
+ * If the saved range can't be restored, the caret goes to the start, so it's never left in a stale tree.
186
+ */
187
+ export function getHistoryState(stack, position, undo, parse) {
188
+ const newPosition = position + (undo ? 1 : -1);
189
+ const state = stack[newPosition];
190
+ if (state === undefined)
191
+ return;
192
+ const root = parse(state.bookdown);
193
+ if (root === undefined || root instanceof ErrorNode)
194
+ return;
195
+ const first = root.getFirstCaret();
196
+ const range = indexRangeToCaretRange(root, state.range) ??
197
+ (first === undefined ? undefined : { start: first, end: first });
198
+ if (range === undefined)
199
+ return;
200
+ return { root, range, position: newPosition };
201
+ }
@@ -2,6 +2,7 @@
2
2
  import TextInput from "../app/TextInput.svelte";
3
3
  import { getEditors } from "../page/Contexts";
4
4
  import Note from "./Note.svelte";
5
+ import Feedback from "../app/Feedback.svelte";
5
6
  let { uids, inheriteduids, writable, atleastone, change } = $props();
6
7
  let emails = getEditors();
7
8
  let newEditor = $state("");
@@ -11,10 +12,12 @@ async function addEditor() {
11
12
  const email = newEditor;
12
13
  newEditor = "";
13
14
  loading = email;
15
+ newEditorError = null;
16
+ const couldnt = `Couldn’t add ${email}. Check the email address and try again.`;
14
17
  try {
15
18
  const { createUser } = await import("../../models/CRUD");
16
19
  const uid = await createUser(email);
17
- if (uid === null) newEditorError = "couldn't add editor";
20
+ if (uid === null) newEditorError = couldnt;
18
21
  else {
19
22
  // The server only reveals the emails of people who already
20
23
  // share a saved book, and this one isn't saved yet. We know
@@ -22,6 +25,9 @@ async function addEditor() {
22
25
  emails.update((known) => new Map(known).set(uid, email));
23
26
  change([...uids, uid]);
24
27
  }
28
+ } catch (error) {
29
+ console.error(error);
30
+ newEditorError = couldnt;
25
31
  } finally {
26
32
  loading = undefined;
27
33
  }
@@ -58,7 +64,9 @@ function hasEditor(email) {
58
64
  command={addEditor}>+ editor</Button
59
65
  >
60
66
  {#if hasEditor(newEditor)}<Note>already added</Note>{/if}
61
- {#if newEditorError !== null}{newEditorError}{/if}
67
+ {#if newEditorError !== null}<Feedback error
68
+ >{newEditorError}</Feedback
69
+ >{/if}
62
70
  </form>
63
71
  {/if}
64
72
 
@@ -1,5 +1,6 @@
1
1
  <script lang="ts">import Loading from "./Loading.svelte";
2
- import Feedback from "../app/Feedback.svelte";
2
+ import TitlePage from "./TitlePage.svelte";
3
+ import Link from "../Link.svelte";
3
4
  import { onDestroy } from "svelte";
4
5
  import { page } from "$app/state";
5
6
  import { getBook, getUser } from "./Contexts.js";
@@ -27,15 +28,36 @@ function unsub() {
27
28
  if (nameUnsub) nameUnsub();
28
29
  if (idUnsub) idUnsub();
29
30
  }
30
- // Keep track of any errors.
31
+ // Keep track of any errors, and whether the book is a draft this person
32
+ // can't open (as opposed to missing).
31
33
  let error = $state();
34
+ let isPrivate = $state(false);
32
35
  function listen() {
33
36
  unsub();
34
37
  const bookid = page.params.bookid;
35
38
  if (bookid === undefined) return;
36
39
  try {
37
- nameUnsub = listenToBooksWithName(bookid, (books) => booksByName = books);
38
- idUnsub = listenToBooksWithID(bookid, (book) => bookByID = book);
40
+ nameUnsub = listenToBooksWithName(
41
+ bookid,
42
+ (books) => booksByName = books,
43
+ // No access by name is the same as no match by name, unless
44
+ // the book already loaded: then access was just revoked, and
45
+ // the page keeps it so unsaved edits can still be copied.
46
+ () => {
47
+ if (!booksByName?.length) booksByName = [];
48
+ }
49
+ );
50
+ idUnsub = listenToBooksWithID(bookid, (book) => bookByID = book, (e) => {
51
+ // Already loaded? Access was revoked; keep showing it.
52
+ if (bookByID) return;
53
+ // A draft this person can't open: say so, rather than
54
+ // claim it doesn't exist. (Firestore already distinguishes
55
+ // the two, so this reveals nothing new.)
56
+ if (e.code === "permission-denied") {
57
+ isPrivate = true;
58
+ bookByID = null;
59
+ } else error = e.code;
60
+ });
39
61
  } catch (err) {
40
62
  error = "" + err;
41
63
  }
@@ -52,8 +74,23 @@ onDestroy(() => {
52
74
  });
53
75
  </script>
54
76
 
55
- {#if error || currentBook === null}
56
- <Feedback error>Unable to load book.</Feedback>
77
+ {#if error}
78
+ <TitlePage title="Couldn’t load this book" error>
79
+ Bookish couldn’t reach this book ({error}). Check your connection and
80
+ reload the page.
81
+ </TitlePage>
82
+ {:else if currentBook === null && isPrivate}
83
+ <TitlePage title="A private draft">
84
+ This book is a draft that only its authors can open. If you should be
85
+ one of them, ask its owner to add you as an editor.
86
+ {#snippet actions()}<Link to="/write">Go to your books</Link>{/snippet}
87
+ </TitlePage>
88
+ {:else if currentBook === null}
89
+ <TitlePage title="No book here">
90
+ There’s no book at this address. Check the link, or find yours on your
91
+ Write page.
92
+ {#snippet actions()}<Link to="/write">Go to your books</Link>{/snippet}
93
+ </TitlePage>
57
94
  {:else if currentBook === undefined}
58
95
  <Loading />
59
96
  {:else}
@@ -1,11 +1,11 @@
1
1
  <script lang="ts">import Instructions from "./Instructions.svelte";
2
2
  import { getUniqueReferenceID, mineReference } from "../../util/mineReference.js";
3
3
  import Reference from "../../models/book/Reference.js";
4
- import { getEdition, isEditionEditable, isEditionPartiallyEditable } from "./Contexts";
4
+ import { getEdition, canEditReferences } from "./Contexts";
5
5
  import Button from "../app/Button.svelte";
6
6
  let edition = getEdition();
7
7
  let text = $state("");
8
- let editable = isEditionEditable() || isEditionPartiallyEditable();
8
+ let editable = canEditReferences();
9
9
  function handleBulkAdd() {
10
10
  // Split by lines, skipping empty lines.
11
11
  const chunks = text.split(/\n+/);
@@ -189,7 +189,9 @@ let editable = $derived(!print && (isBookEditable() || isEditionEditable() || is
189
189
  {#if $edition}
190
190
  <Page
191
191
  afterLoaded={scrollToLastLocation}
192
- title={print ? undefined : `${$edition.getTitle()} - ${chapter.getTitle()}`}
192
+ title={print
193
+ ? undefined
194
+ : `${$edition.getTitle()} - ${chapter.getTitle()}`}
193
195
  >
194
196
  <Header
195
197
  {editable}
@@ -206,10 +208,12 @@ let editable = $derived(!print && (isBookEditable() || isEditionEditable() || is
206
208
  >
207
209
  <!-- Collapse the outline if a marginal is selected. -->
208
210
  {#snippet outline()}
209
- <Outline
210
-
211
+ <Outline
211
212
  collapse={$marginal !== undefined}
212
- previous={$edition.getPreviousChapterID(chapterID, editable)}
213
+ previous={$edition.getPreviousChapterID(
214
+ chapterID,
215
+ editable,
216
+ )}
213
217
  next={$edition.getNextChapterID(chapterID, editable)}
214
218
  listener={(expanded) => {
215
219
  // If the outline is being expanded, hide the marginal, otherwise leave it alone.
@@ -219,76 +223,74 @@ let editable = $derived(!print && (isBookEditable() || isEditionEditable() || is
219
223
  hideOutlineIfObscured();
220
224
  }}
221
225
  />
222
- {/snippet}
226
+ {/snippet}
223
227
  <!-- Add an editable chapter ID if in editor mode -->
224
228
  {#snippet before()}
225
-
226
- {#if editable && $book}
227
- <Muted>
228
- <em>bookish.press/book/</em><TextEditor
229
- text={chapter.getID()}
230
- label="Chapter URL ID editor"
231
- save={// After the ID is edited, reload the page with the new URL.
232
- async (newChapterID) => {
233
- if ($book) {
234
- setChapter(
235
- edition,
236
- chapter,
237
- chapter.withChapterID(newChapterID),
238
- );
239
- // Navigate to the new ID
240
- goto(
241
- `/write/${$book.getID()}/${editionNumber}/${newChapterID}`,
242
- {
243
- reset: false,
244
- },
245
- );
246
- }
247
- }}
248
- placeholder="chapter name"
249
- valid={(newChapterID) =>
250
- !/^[a-zA-Z0-9]+$/.test(newChapterID)
251
- ? 'Chapter IDs must be one or more letters or numbers'
252
- : chapter.getID() !== newChapterID &&
253
- $edition?.hasChapter(newChapterID)
254
- ? "There's already a chapter that has this ID."
255
- : undefined}
256
- saveOnExit={true}
257
- />
258
- </Muted>
259
- {/if}
260
- {#if editable}
261
- <Toggle
262
- on={chapter.isNumbered()}
263
- save={(on) =>
264
- setChapter(
265
- edition,
266
- chapter,
267
- chapter.asNumbered(on),
268
- )}
229
+ {#if editable && $book}
230
+ <Muted>
231
+ <em>bookish.press/book/</em><TextEditor
232
+ text={chapter.getID()}
233
+ label="Chapter URL ID editor"
234
+ save={// After the ID is edited, reload the page with the new URL.
235
+ async (newChapterID) => {
236
+ if ($book) {
237
+ setChapter(
238
+ edition,
239
+ chapter,
240
+ chapter.withChapterID(newChapterID),
241
+ );
242
+ // Navigate to the new ID
243
+ goto(
244
+ `/write/${$book.getID()}/${editionNumber}/${newChapterID}`,
245
+ {
246
+ reset: false,
247
+ },
248
+ );
249
+ }
250
+ }}
251
+ placeholder="chapter name"
252
+ valid={(newChapterID) =>
253
+ !/^[a-zA-Z0-9]+$/.test(newChapterID)
254
+ ? 'Chapter IDs must be one or more letters or numbers'
255
+ : chapter.getID() !== newChapterID &&
256
+ $edition?.hasChapter(newChapterID)
257
+ ? "There's already a chapter that has this ID."
258
+ : undefined}
259
+ saveOnExit={true}
260
+ />
261
+ </Muted>
262
+ {/if}
263
+ {#if editable}
264
+ <Toggle
265
+ on={chapter.isNumbered()}
266
+ save={(on) =>
267
+ setChapter(
268
+ edition,
269
+ chapter,
270
+ chapter.asNumbered(on),
271
+ )}
272
+ >
273
+ <ChapterNumber
274
+ >{#if chapterNumber !== undefined}Chapter {chapterNumber}{:else}<Muted
275
+ >Unnumbered</Muted
276
+ >{/if}</ChapterNumber
269
277
  >
270
- <ChapterNumber
271
- >{#if chapterNumber !== undefined}Chapter {chapterNumber}{:else}<Muted
272
- >Unnumbered</Muted
273
- >{/if}</ChapterNumber
274
- >
275
- </Toggle>
276
- {:else if chapterNumber !== undefined}
277
- <ChapterNumber>Chapter {chapterNumber}</ChapterNumber>
278
- {/if}
279
- {#if chapterSection !== undefined && chapterSection.length > 0}
280
- <span class="section-name">{chapterSection}</span>
281
- {/if}
282
-
283
- {/snippet}
278
+ </Toggle>
279
+ {:else if chapterNumber !== undefined}
280
+ <ChapterNumber>Chapter {chapterNumber}</ChapterNumber>
281
+ {/if}
282
+ {#if chapterSection !== undefined && chapterSection.length > 0}
283
+ <span class="section-name">{chapterSection}</span>
284
+ {/if}
285
+ {/snippet}
284
286
  <!-- If there are chapter authors, render those, otherwise use the book authors -->
285
287
  {#snippet after()}
286
- <Authors
288
+ <Authors
287
289
  editable={isChapterEditable()}
288
-
289
290
  authors={chapter.getAuthors()}
290
291
  inheritedAuthors={$edition.getAuthors()}
291
- add={() => setChapter(edition, chapter, chapter.withAuthor(''))}
292
+ add={() =>
293
+ setChapter(edition, chapter, chapter.withAuthor(''))}
292
294
  edit={(index, text) =>
293
295
  setChapter(
294
296
  edition,
@@ -296,9 +298,13 @@ let editable = $derived(!print && (isBookEditable() || isEditionEditable() || is
296
298
  chapter.withRenamedAuthor(index, text),
297
299
  )}
298
300
  remove={(index) =>
299
- setChapter(edition, chapter, chapter.withoutAuthor(index))}
301
+ setChapter(
302
+ edition,
303
+ chapter,
304
+ chapter.withoutAuthor(index),
305
+ )}
300
306
  />
301
- {/snippet}
307
+ {/snippet}
302
308
  </Header>
303
309
 
304
310
  <Instructions {editable}>
@@ -335,8 +341,9 @@ let editable = $derived(!print && (isBookEditable() || isEditionEditable() || is
335
341
  {:else}
336
342
  <ChapterBody node={chapterAST} />
337
343
  {/if}
338
- {:else if $edition === undefined}Loading...{:else}Unable to load
339
- chapter text{/if}
344
+ <!-- No text yet: it streams in after the page loads, so show
345
+ nothing rather than an error while it does. -->
346
+ {/if}
340
347
  </section>
341
348
 
342
349
  {#if citations && citations.size > 0}
@@ -37,6 +37,9 @@ export declare function getRoot(): RootStore;
37
37
  export declare function setChapter(store: EditionStore, previous: Chapter, revised: Chapter): void;
38
38
  export declare function isChapterEditable(): boolean;
39
39
  export declare function isEditionEditable(): boolean;
40
+ /** References are shared by every chapter, so chapter editors may edit them
41
+ * too, along with edition and book editors. */
42
+ export declare function canEditReferences(): boolean;
40
43
  export declare function isEditionPartiallyEditable(): boolean;
41
44
  export declare function isBookEditable(): boolean;
42
45
  export declare const BASE: unique symbol;
@@ -47,6 +50,17 @@ export declare function getCaret(): Writable<CaretState | undefined>;
47
50
  export declare const STATUS: unique symbol;
48
51
  export type StatusStore = Writable<BookSaveStatus>;
49
52
  export declare function getStatus(): StatusStore;
53
+ /** Text whose save was refused (for example, because access was revoked),
54
+ * kept so the author can copy it before leaving. */
55
+ export type UnsavedChanges = {
56
+ chapters: {
57
+ title: string;
58
+ text: string;
59
+ }[];
60
+ };
61
+ export declare const UNSAVED: unique symbol;
62
+ export type UnsavedStore = Writable<UnsavedChanges | undefined>;
63
+ export declare function getUnsaved(): UnsavedStore | undefined;
50
64
  export declare const EDITORS: unique symbol;
51
65
  export type EditorsStore = Writable<Map<string, string>>;
52
66
  export declare function getEditors(): EditorsStore;
@@ -74,9 +74,12 @@ export function isEditionEditable() {
74
74
  book !== undefined &&
75
75
  auth !== undefined &&
76
76
  auth.user !== null &&
77
- (edition.isEditor(auth.user.uid) ||
78
- book.isEditor(auth.user.uid) ||
79
- edition.isChapterEditor(auth.user.uid)));
77
+ (edition.isEditor(auth.user.uid) || book.isEditor(auth.user.uid)));
78
+ }
79
+ /** References are shared by every chapter, so chapter editors may edit them
80
+ * too, along with edition and book editors. */
81
+ export function canEditReferences() {
82
+ return isEditionEditable() || isEditionPartiallyEditable();
80
83
  }
81
84
  export function isEditionPartiallyEditable() {
82
85
  if (!isRouteWrite())
@@ -110,6 +113,10 @@ export const STATUS = Symbol('status');
110
113
  export function getStatus() {
111
114
  return getContext(STATUS);
112
115
  }
116
+ export const UNSAVED = Symbol('unsaved');
117
+ export function getUnsaved() {
118
+ return getContext(UNSAVED);
119
+ }
113
120
  export const EDITORS = Symbol('editors');
114
121
  export function getEditors() {
115
122
  return getContext(EDITORS);
@@ -121,7 +128,10 @@ export async function lease(authStore, editionStore, contentID, lock) {
121
128
  // Loaded here rather than at the top so bound books, which never
122
129
  // lease, don't load Firebase. See FirebaseAvailable.ts.
123
130
  const { updateLock } = await import('../../models/CRUD');
124
- await updateLock(edition, auth.user.uid, contentID, lock);
131
+ // Someone else may hold the lease; only record it locally if we got it.
132
+ const held = await updateLock(edition, auth.user.uid, contentID, lock);
133
+ if (lock && !held)
134
+ return false;
125
135
  const latestEdition = get(editionStore);
126
136
  const latestAuth = get(authStore);
127
137
  if (latestEdition && latestAuth && latestAuth.user) {