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
@@ -7,6 +7,7 @@ import ParagraphNode from "../../models/chapter/ParagraphNode.js";
7
7
  import QuoteNode from "../../models/chapter/QuoteNode.js";
8
8
  import RuleNode from "../../models/chapter/RuleNode.js";
9
9
  import TableNode from "../../models/chapter/TableNode.js";
10
+ import SymbolBlockNode from "../../models/chapter/SymbolBlockNode.js";
10
11
  import Callout from "./Callout.svelte";
11
12
  import CaptionedCode from "./CaptionedCode.svelte";
12
13
  import Embed from "./Embed.svelte";
@@ -16,6 +17,7 @@ import Paragraph from "./Paragraph.svelte";
16
17
  import Quote from "./Quote.svelte";
17
18
  import Rule from "./Rule.svelte";
18
19
  import Table from "./Table.svelte";
20
+ import Block from "./Block.svelte";
19
21
  import Problem from "./Problem.svelte";
20
22
  import { isChapterEditable } from "../page/Contexts";
21
23
  let { node } = $props();
@@ -31,5 +33,22 @@ let editable = isChapterEditable();
31
33
  {:else if node instanceof ErrorNode}<ErrorMessage {node} />
32
34
  {:else if node instanceof RuleNode}<Rule {node} />
33
35
  {:else if node instanceof TableNode}<Table {node} />
36
+ {:else if node instanceof SymbolBlockNode}<div
37
+ class="bookish-symbol-block"
38
+ data-nodeid={node.nodeID}
39
+ contenteditable="false"
40
+ >
41
+ {#each node.getBlocks() as block (block.nodeID)}<Block
42
+ node={block}
43
+ />{/each}
44
+ </div>
34
45
  {:else}<p><Problem>Unknown node type</Problem></p>
35
46
  {/if}
47
+
48
+ <style>
49
+ /* Lines of symbols expand to blocks that aren't the chapter's text, so
50
+ they can't be edited, but lay out as if they were the chapter's own. */
51
+ .bookish-symbol-block {
52
+ display: contents;
53
+ }
54
+ </style>
@@ -1,4 +1,5 @@
1
1
  import type BlockNode from '../../models/chapter/BlockNode.js';
2
+ import Block from './Block.svelte';
2
3
  interface Props {
3
4
  node: BlockNode;
4
5
  }
@@ -4,6 +4,7 @@ import { tick } from 'svelte';
4
4
  import { writable } from 'svelte/store';
5
5
  import Parser from '../../models/chapter/Parser.js';
6
6
  import Chapter from '../../models/book/Chapter.js';
7
+ import Edition from '../../models/book/Edition.js';
7
8
  import ChapterBody from './ChapterBody.svelte';
8
9
  import { CARET, CHAPTER, EDITION } from '../page/Contexts.js';
9
10
  // The page state only exists inside a running SvelteKit app; Contexts.ts
@@ -67,6 +68,16 @@ test('renders footnote content in a marginal', () => {
67
68
  expect(footnote).not.toBeNull();
68
69
  expect(footnote?.textContent).toContain('And this is the footnote that supports it.');
69
70
  });
71
+ // Regression (#383): inline parse errors used to fall through Format's
72
+ // branches and render as "Unknown segment type node=[object Object]".
73
+ test.each([
74
+ ['some *bold text', 'Error: Unclosed *'],
75
+ ['a [broken link here', "Error: Missing '|' in link"],
76
+ ])('shows the parser’s message for %s', (markup, message) => {
77
+ const { container } = renderChapter(markup);
78
+ expect(container.textContent).toContain(message);
79
+ expect(container.textContent).not.toContain('Unknown segment type');
80
+ });
70
81
  // This guards the marginal layout contract: every render of a marginal
71
82
  // component must request a chapter-wide layout pass, including re-renders
72
83
  // caused by content changes. (Marginal components do this in an $effect
@@ -83,3 +94,71 @@ test('lays out marginals on render and again when content changes', async () =>
83
94
  await tick();
84
95
  expect(layout.mock.calls.length).toBeGreaterThan(initialCalls);
85
96
  });
97
+ function renderWithEdition(node, edition) {
98
+ return render(ChapterBody, {
99
+ props: { node },
100
+ context: new Map([
101
+ [CHAPTER, writable(makeChapterContext(() => undefined))],
102
+ [EDITION, writable(edition)],
103
+ [CARET, writable(undefined)],
104
+ ]),
105
+ });
106
+ }
107
+ function editionWithSymbols(symbols) {
108
+ return Edition.fromJSON(undefined, {
109
+ title: 'Test',
110
+ authors: [],
111
+ number: 1,
112
+ summary: '',
113
+ published: null,
114
+ images: {},
115
+ description: '',
116
+ chapters: [],
117
+ license: '',
118
+ acknowledgements: '',
119
+ tags: [],
120
+ sources: {},
121
+ references: {},
122
+ symbols,
123
+ glossary: {},
124
+ theme: null,
125
+ uids: [],
126
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
+ });
128
+ }
129
+ test('renders symbols as their definitions', () => {
130
+ const edition = editionWithSymbols({ press: 'the *Bookish* press' });
131
+ const { container } = renderWithEdition(Parser.parseChapter(edition, '@me: Amy\n\n@me wrote for @press.'), edition);
132
+ const symbols = container.querySelectorAll('.bookish-symbol');
133
+ expect(symbols).toHaveLength(2);
134
+ expect(symbols[0].textContent).toBe('Amy');
135
+ expect(symbols[1].querySelector('strong')?.textContent).toBe('Bookish');
136
+ expect(container.textContent).not.toContain('@');
137
+ });
138
+ test('looks up symbols the parser could not resolve, such as pasted ones', () => {
139
+ const edition = editionWithSymbols({ press: 'the press' });
140
+ const { container } = renderWithEdition(Parser.parseChapter(undefined, 'For @press.'), edition);
141
+ expect(container.querySelector('.bookish-symbol')?.textContent).toBe('the press');
142
+ });
143
+ test('renders lines of block symbols as a header and a table', () => {
144
+ const edition = editionWithSymbols({
145
+ header: '# Relevant standards',
146
+ tableHeader: ',Standard| Description',
147
+ row: ',1a| Apply *practices*.',
148
+ });
149
+ const { container } = renderWithEdition(Parser.parseChapter(edition, '@header\n\n@tableHeader| Chapters\n@row| All'), edition);
150
+ // Headers render a level down, and get an id to link to.
151
+ const header = container.querySelector('h2');
152
+ expect(header?.textContent).toContain('Relevant standards');
153
+ expect(header?.id).toBe('header-0');
154
+ const table = container.querySelector('table');
155
+ expect(table).not.toBeNull();
156
+ expect(table?.querySelectorAll('tr')).toHaveLength(2);
157
+ expect(table?.querySelector('strong')?.textContent).toBe('practices');
158
+ expect(container.textContent).not.toContain('@');
159
+ expect(container.textContent).not.toContain(',1a');
160
+ });
161
+ test('renders unknown symbols as written', () => {
162
+ const { container } = renderWithEdition(Parser.parseChapter(undefined, 'An @unknown symbol.'), undefined);
163
+ expect(container.querySelector('.bookish-symbol')?.textContent).toBe('@unknown');
164
+ });
@@ -5,14 +5,18 @@ import DefinitionNode from "../../models/chapter/DefinitionNode.js";
5
5
  import FootnoteNode from "../../models/chapter/FootnoteNode.js";
6
6
  import InlineCodeNode from "../../models/chapter/InlineCodeNode.js";
7
7
  import LabelNode from "../../models/chapter/LabelNode.js";
8
+ import SymbolNode from "../../models/chapter/SymbolNode.js";
8
9
  import LinkNode from "../../models/chapter/LinkNode.js";
9
10
  import TextNode from "../../models/chapter/TextNode.js";
11
+ import ErrorNode from "../../models/chapter/ErrorNode.js";
10
12
  import Problem from "./Problem.svelte";
13
+ import ErrorMessage from "./ErrorMessage.svelte";
11
14
  import Citations from "./Citations.svelte";
12
15
  import Definition from "./Definition.svelte";
13
16
  import Footnote from "./Footnote.svelte";
14
17
  import InlineCode from "./InlineCode.svelte";
15
18
  import Label from "./Label.svelte";
19
+ import SymbolView from "./Symbol.svelte";
16
20
  import Link from "./Link.svelte";
17
21
  import Comment from "./Comment.svelte";
18
22
  import Text from "./Text.svelte";
@@ -52,9 +56,15 @@ let showPlaceholder = $derived(node.isEmptyText() && placeholder !== undefined &
52
56
  node={segment}
53
57
  />{:else if segment instanceof CommentNode}<Comment
54
58
  node={segment}
59
+ />{:else if segment instanceof SymbolNode}<SymbolView
60
+ node={segment}
55
61
  />{:else if segment instanceof FormatNode}<Format
56
62
  node={segment}
57
- />{:else}<Problem>Unknown segment type node={segment}</Problem
63
+ />{:else if segment instanceof ErrorNode}<ErrorMessage
64
+ node={segment}
65
+ />{:else}<Problem
66
+ >Unknown segment type {(segment as object).constructor
67
+ .name}</Problem
58
68
  >{/if}{/each}</svelte:element
59
69
  >
60
70
 
@@ -9,7 +9,8 @@ let editable = isChapterEditable();
9
9
  let caret = getCaret();
10
10
  // If there's no marginal selected or this is different from the current selection, this is hidden.
11
11
  let selectedMarginal = $derived($chapter?.marginal);
12
- let isHidden = $derived(editable ? !($caret?.range?.start.node === node || $caret?.range?.start.node.getAncestors($caret.root).some((ancestor) => ancestor === node)) : // If not editable, it's hidden if it's not selected.
12
+ let isHidden = $derived(editable ? !($caret?.range?.start.node === node || $caret?.range?.start.node.getAncestors($caret.root).some((ancestor) => ancestor === node)) :
13
+ // If not editable, it's hidden if it's not selected.
13
14
  $selectedMarginal !== id);
14
15
  function toggle(event, interacted) {
15
16
  if (editable) {
@@ -0,0 +1,27 @@
1
+ <script lang="ts">import Parser from "../../models/chapter/Parser.js";
2
+ import Atom from "./Atom.svelte";
3
+ import Format from "./Format.svelte";
4
+ import { getEdition, getRoot } from "../page/Contexts";
5
+ let { node } = $props();
6
+ let edition = getEdition();
7
+ let root = getRoot();
8
+ // The parser resolves the definition from the chapter's declarations, then
9
+ // the edition's symbols. A symbol in the chapter that it couldn't resolve,
10
+ // such as one pasted into the editor, is looked up again here. Symbols
11
+ // inside a definition aren't in the chapter, so a definition that refers
12
+ // to itself can't recurse forever.
13
+ let definition = $derived.by(() => {
14
+ const parsed = node.getDefinition();
15
+ if (parsed !== undefined) return parsed;
16
+ if ($root === undefined || $root.getParentOf(node) === undefined) return undefined;
17
+ const symbols = $root.getSymbols();
18
+ const text = symbols[node.getName()] ?? $edition?.getSymbols()[node.getName()];
19
+ return text === undefined ? undefined : Parser.parseFormat($edition, text, symbols);
20
+ });
21
+ </script>
22
+
23
+ <Atom {node}
24
+ ><span class="bookish-symbol" data-nodeid={node.nodeID}
25
+ >{#if definition}<Format node={definition} />{:else}@{node.getName()}{/if}</span
26
+ ></Atom
27
+ >
@@ -0,0 +1,7 @@
1
+ import type SymbolNode from '../../models/chapter/SymbolNode.js';
2
+ interface Props {
3
+ node: SymbolNode;
4
+ }
5
+ declare const Symbol: import("svelte").Component<Props, {}, "">;
6
+ type Symbol = ReturnType<typeof Symbol>;
7
+ export default Symbol;
@@ -1,24 +1,16 @@
1
1
  <script lang="ts">import BookishNode from "../../models/chapter/Node.js";
2
- import ChapterNode from "../../models/chapter/ChapterNode.js";
3
2
  import LinkNode from "../../models/chapter/LinkNode.js";
4
3
  import ParagraphNode from "../../models/chapter/ParagraphNode.js";
5
4
  import TextNode from "../../models/chapter/TextNode.js";
6
5
  import AtomNode from "../../models/chapter/AtomNode.js";
7
6
  import FormatNode from "../../models/chapter/FormatNode.js";
8
- import BlocksNode from "../../models/chapter/BlocksNode.js";
9
- import ListNode from "../../models/chapter/ListNode.js";
10
- import TableNode from "../../models/chapter/TableNode.js";
11
- import MetadataNode from "../../models/chapter/MetadataNode.js";
12
- import CodeNode from "../../models/chapter/CodeNode.js";
13
- import BlockNode from "../../models/chapter/BlockNode.js";
14
7
  import EmbedNode from "../../models/chapter/EmbedNode.js";
15
- import ErrorNode from "../../models/chapter/ErrorNode.js";
16
- import { caretRangeToIndexRange, indexRangeToCaretRange } from "../../models/chapter/Caret.js";
8
+ import { caretRangeToIndexRange } from "../../models/chapter/Caret.js";
17
9
  import commands from "./Commands";
18
10
  import { onMount, setContext, untrack } from "svelte";
19
11
  import { getCaret } from "../page/Contexts";
20
12
  import CaretView from "./CaretView.svelte";
21
- import Parser, { Reserved } from "../../models/chapter/Parser.js";
13
+ import { getCaretContext as describeCaret, commandMatches, getPasteEdit, getHistoryState, withUndoState } from "./Editing";
22
14
  const IDLE_TIME = 500;
23
15
  let { text, parser, save, chapter, autofocus = false, component, placeholder, leasee, lease, inline = false } = $props();
24
16
  let element = $state(null);
@@ -291,87 +283,30 @@ function getCaretOnLine(caret, below) {
291
283
  // If we didn't find one, just return what we were given.
292
284
  return caret;
293
285
  }
294
- function atParagraphStart() {
295
- if (caretRange === undefined || caretRange.start.node !== caretRange.end.node || caretRange.start.index !== caretRange.end.index || !(caretRange.start.node instanceof TextNode)) return false;
296
- const firstCaret = caretRange.start.node.getFormatRoot(editedNode)?.getFirstCaret();
297
- return firstCaret !== undefined && firstCaret.node === caretRange.start.node && firstCaret.index === caretRange.start.index;
298
- }
299
286
  function undo() {
300
- // Grab the next state
301
- let undoState = undoStack[undoPosition + 1];
302
- // Restore the content of the chapter.
303
- let node = parser(undoState.bookdown);
304
- if (node === undefined || node instanceof ErrorNode) return;
305
- // Restore the view
306
- updateRoot(node);
307
- // Save the undo.
308
- save(node);
309
- // Move the undo state down a position.
310
- if (undoPosition < undoStack.length) undoPosition = undoPosition + 1;
311
- // Return the original caret.
312
- const range = indexRangeToCaretRange(node, undoState.range);
313
- if (range === undefined) return;
314
- return {
315
- root: node,
316
- range
317
- };
287
+ return restore(true);
318
288
  }
319
289
  function redo() {
320
- // Grab the next state
321
- let undoState = undoStack[undoPosition - 1];
322
- // Restore the content of the chapter.
323
- let node = parser(undoState.bookdown);
324
- if (node === undefined) return;
325
- updateRoot(node);
326
- // Move the undo state down a position.
327
- if (undoPosition > 0) undoPosition = undoPosition - 1;
328
- // Return the original caret.
329
- const range = indexRangeToCaretRange(node, undoState.range);
330
- if (range === undefined) return;
290
+ return restore(false);
291
+ }
292
+ /** Restore the previous (undo) or next (redo) state in the history, saving it. */
293
+ function restore(undo) {
294
+ const restored = getHistoryState(undoStack, undoPosition, undo, parser);
295
+ if (restored === undefined) return;
296
+ // Restore the view
297
+ updateRoot(restored.root);
298
+ // Save the restored state.
299
+ save(restored.root);
300
+ // Move to the restored position in the history.
301
+ undoPosition = restored.position;
331
302
  return {
332
- root: node,
333
- range
303
+ root: restored.root,
304
+ range: restored.range
334
305
  };
335
306
  }
336
307
  function getCaretContext() {
337
308
  if (caretRange === undefined) return undefined;
338
- // Determine whether the range contains a list
339
- const nodes = editedNode.getNodes();
340
- let inside = false;
341
- let includesList = false;
342
- nodes.forEach((n) => {
343
- if (caretRange === undefined) return;
344
- if (n === caretRange.start.node) inside = true;
345
- if (inside && n.getClosestParentMatching(editedNode, (p) => p instanceof ListNode) !== undefined) includesList = true;
346
- if (n === caretRange.end.node) inside = false;
347
- });
348
- const parents = editedNode.getParentsOf(caretRange.start.node)?.reverse();
349
- return {
350
- // We make a new range so that setCaretRange always causes a re-render
351
- chapter,
352
- range: {
353
- start: caretRange.start,
354
- end: caretRange.end
355
- },
356
- start: caretRange.start,
357
- end: caretRange.end,
358
- isSelection: caretRange.start.node !== caretRange.end.node || caretRange.start.index !== caretRange.end.index,
359
- root: editedNode,
360
- blocks: parents?.find((n) => n instanceof BlocksNode),
361
- paragraph: parents?.find((n) => n instanceof ParagraphNode),
362
- block: parents?.find((n) => n instanceof BlockNode),
363
- code: parents?.find((n) => n instanceof CodeNode),
364
- list: parents?.find((n) => n instanceof ListNode),
365
- atom: parents?.find((n) => n instanceof AtomNode),
366
- meta: parents?.find((n) => n instanceof MetadataNode),
367
- includesList,
368
- table: parents?.find((n) => n instanceof TableNode),
369
- formatRoot: caretRange.end.node instanceof TextNode || caretRange.end.node instanceof AtomNode ? caretRange.end.node.getFormatRoot(editedNode) : undefined,
370
- startIsText: caretRange.start.node instanceof TextNode,
371
- endIsText: caretRange.end.node instanceof TextNode,
372
- startIsTextOrAtom: caretRange.start.node instanceof TextNode || caretRange.start.node instanceof AtomNode || caretRange.start.node instanceof EmbedNode,
373
- endIsTextOrAtom: caretRange.end.node instanceof TextNode || caretRange.end.node instanceof AtomNode || caretRange.start.node instanceof EmbedNode,
374
- atParagraphStart: atParagraphStart(),
309
+ return describeCaret(editedNode, caretRange, chapter, {
375
310
  undoStack,
376
311
  undoPosition,
377
312
  undo,
@@ -381,7 +316,7 @@ function getCaretContext() {
381
316
  handlePaste,
382
317
  setAccent,
383
318
  getAccent
384
- };
319
+ });
385
320
  }
386
321
  function setAccent(newAccent) {
387
322
  accent = newAccent;
@@ -409,7 +344,7 @@ function handleKey(event, press = false) {
409
344
  // Find a command that handles the event.
410
345
  const command = commands.find((command) => {
411
346
  // If the keystroke and caret position matches the command signature, execute the command and update the caret range.
412
- if ((command.press === undefined || command.press === press) && (command.shift === undefined || command.shift === event.shiftKey) && (command.alt === undefined || command.alt === event.altKey) && (command.control === undefined || command.control === (event.ctrlKey || event.metaKey)) && (command.key === undefined || Array.isArray(command.key) && command.key.includes(event.key) || command.key instanceof Function && command.key(event.key) || command.key === event.key) && (command.code === undefined || command.code === event.code) && (command.active === true || command.active instanceof Function && command.active.call(undefined, context, event.key))) {
347
+ if (commandMatches(command, context, event, press)) {
413
348
  // See if the command is handled
414
349
  if (executeCommand(command, event.key, event.code)) {
415
350
  event.preventDefault();
@@ -482,12 +417,13 @@ function executeCommand(command, key, code) {
482
417
  end: range.end
483
418
  };
484
419
  if (root === editedNode && command.mutates) console.error(`Warning: immutability violation on ${command.description}`);
485
- // Set the range to force a rerender, assuming something in the document changed.
486
- caretRange = newRange;
487
420
  // Save the copy in the undo stack if this isn't a navigation or selection state.
488
- if (command.category !== "navigation" && command.category !== "selection" && command.category !== "history") {
421
+ // Do this before updating the range, so the history remembers where the caret was before the edit.
422
+ if (command.category !== "navigation" && command.category !== "selection" && command.category !== "history" && root !== editedNode) {
489
423
  saveEdit(root, newRange, command);
490
424
  }
425
+ // Set the range to force a rerender, assuming something in the document changed.
426
+ caretRange = newRange;
491
427
  return true;
492
428
  } else {
493
429
  ignoredInput = true;
@@ -501,26 +437,20 @@ async function saveEdit(newRoot, newRange, command) {
501
437
  if (locked) return;
502
438
  // Call the save callback.
503
439
  save(newRoot);
504
- // Initialize a new history if we don't have one.
505
- let newStack = undoStack.length > 0 ? undoStack : [];
506
- // If there's nothing on the stack, save the initial state before we add something to the stack.
507
- if (undoStack.length === 0 && caretRange !== undefined) {
508
- const currentRange = caretRangeToIndexRange(editedNode, caretRange);
509
- if (currentRange !== undefined) newStack = [{
510
- bookdown: editedNode.toBookdown(),
511
- command: undefined,
512
- range: currentRange
513
- }];
514
- }
440
+ // Remember the state before the edit and after it.
441
+ const before = {
442
+ bookdown: editedNode.toBookdown(),
443
+ range: caretRange === undefined ? undefined : caretRangeToIndexRange(editedNode, caretRange)
444
+ };
445
+ const newTextRange = caretRangeToIndexRange(newRoot, newRange);
515
446
  // Change the chapter's AST.
516
447
  updateRoot(newRoot);
517
- // Set the new undo stack, pre-pending the new command to the front.
518
- const newTextRange = caretRangeToIndexRange(newRoot, newRange);
519
- if (newTextRange !== undefined) undoStack = [{
448
+ // Add the new state to the front of the history.
449
+ if (newTextRange !== undefined) undoStack = withUndoState(undoStack, undoPosition, before, {
520
450
  bookdown: newRoot.toBookdown(),
521
451
  command,
522
452
  range: newTextRange
523
- }, ...undoPosition > 0 ? newStack.slice(undoPosition) : newStack];
453
+ });
524
454
  // Set the undo position to the last index.
525
455
  undoPosition = 0;
526
456
  // Focus the editor on the new caret location, unless the toolbar is focused.
@@ -591,56 +521,14 @@ function handleCopy(node) {
591
521
  })]);
592
522
  } else window.alert("Your browser doesn't support copying to the clipboard :(");
593
523
  }
594
- function handlePaste(context, text, save) {
595
- // If we're pasting a node, see what will accept it.
596
- if (text instanceof BookishNode) return handlePasteNode(context, text, save);
597
- if (text.plain === undefined) return undefined;
598
- // Escape all reserved Bookdown characters.
599
- const escaped = text.plain.replaceAll(Reserved, "\\$1");
600
- const chapter = context.block instanceof ParagraphNode && context.atom === undefined ? Parser.parseChapter(undefined, escaped) : // Otherwise parse as just a format node, replacing all text newlines with a space.
601
- Parser.parseFormat(undefined, escaped.replaceAll("\n", " "));
602
- const edit = handlePasteNode(context, chapter, save);
603
- if (edit) return edit;
604
- return undefined;
605
- }
606
- function handlePasteNode(context, node, save) {
607
- // Track revisions in these two variables.
608
- let newRoot = context.root;
609
- let newCaret = context.start;
610
- // Is there any text to remove? Remove it first.
611
- if (context.isSelection) {
612
- const edit = newRoot.withRangeFormatted(context.range, undefined);
613
- if (edit === undefined || !(edit.root instanceof ChapterNode)) return;
614
- newRoot = edit.root;
615
- newCaret = edit.range.start;
616
- }
617
- // Find the parents of the caret node, from nearest to furthest
618
- const parents = context.root.getParentsOf(newCaret.node);
619
- if (parents === undefined) return;
620
- // Pop parents, nearest to farthest, searching for one that handles an insertion.
621
- let edit = undefined;
622
- let parent = undefined;
623
- while (parents.length > 0) {
624
- parent = parents.pop();
625
- if (parent === undefined) break;
626
- // 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.
627
- edit = parent.withNodeInserted(newCaret, node.copy());
628
- if (edit !== undefined) break;
629
- }
630
- // Insert the node at the caret.
631
- if (parent !== undefined && edit !== undefined) {
632
- const newChapter = context.root.withNodeReplaced(parent, edit.root);
633
- if (newChapter === undefined) return;
634
- if (save) {
635
- // Set the range to force a rerender, assuming something in the document changed.
636
- caretRange = edit.range;
637
- // Save the copy in the undo stack if this isn't a navigation or selection state.
638
- saveEdit(newChapter, edit.range);
639
- } else return {
640
- root: newChapter,
641
- range: edit.range
642
- };
643
- }
524
+ function handlePaste(context, content, save) {
525
+ const edit = getPasteEdit(context, content);
526
+ if (edit === undefined) return;
527
+ if (!save) return edit;
528
+ // Save before updating the range, so the history remembers where the caret was before the paste.
529
+ saveEdit(edit.root, edit.range);
530
+ // Set the range to force a rerender, assuming something in the document changed.
531
+ caretRange = edit.range;
644
532
  }
645
533
  function toolbarIsFocused() {
646
534
  const toolbar = document.querySelector(".bookish-editor-toolbar");
@@ -289,8 +289,11 @@ const commands = [
289
289
  if (context.end.node instanceof TextNode ||
290
290
  context.end.node instanceof AtomNode ||
291
291
  context.end.node instanceof EmbedNode) {
292
- const nextCaret = context.root.getAdjacentCaret(context.end, false);
293
292
  const sortedRange = context.root.sortRange(context.range);
293
+ // With a selection, collapse it to its start, as other editors do.
294
+ const nextCaret = context.isSelection
295
+ ? undefined
296
+ : context.root.getAdjacentCaret(context.end, false);
294
297
  return {
295
298
  root: context.root,
296
299
  range: nextCaret === undefined
@@ -437,8 +440,11 @@ const commands = [
437
440
  if (context.end.node instanceof TextNode ||
438
441
  context.end.node instanceof AtomNode ||
439
442
  context.end.node instanceof EmbedNode) {
440
- const nextCaret = context.root.getAdjacentCaret(context.end, true);
441
443
  const sortedRange = context.root.sortRange(context.range);
444
+ // With a selection, collapse it to its end, as other editors do.
445
+ const nextCaret = context.isSelection
446
+ ? undefined
447
+ : context.root.getAdjacentCaret(context.end, true);
442
448
  // If there is no next caret, move the caret to the largest of the current start and end.
443
449
  return {
444
450
  root: context.root,
@@ -667,8 +673,8 @@ const commands = [
667
673
  },
668
674
  },
669
675
  {
670
- icon: 'select ↓ line',
671
- description: 'move up down line',
676
+ icon: '↓ line',
677
+ description: 'move down one line',
672
678
  category: 'navigation',
673
679
  mutates: false,
674
680
  control: false,
@@ -705,7 +711,7 @@ const commands = [
705
711
  icon: 'delete ←',
706
712
  description: 'delete previous character',
707
713
  category: 'text',
708
- mutates: false,
714
+ mutates: true,
709
715
  control: false,
710
716
  alt: false,
711
717
  shift: false,
@@ -1200,7 +1206,7 @@ const commands = [
1200
1206
  },
1201
1207
  {
1202
1208
  icon: Header4Icon,
1203
- description: 'format as 4rd level header',
1209
+ description: 'format as 4th level header',
1204
1210
  category: 'level',
1205
1211
  mutates: true,
1206
1212
  control: true,
@@ -1489,42 +1495,37 @@ const commands = [
1489
1495
  handler: (context) => {
1490
1496
  if (context.root === undefined)
1491
1497
  return undefined;
1492
- // See if there's something on the clipboard.
1493
- if (navigator.clipboard) {
1494
- navigator.clipboard.read().then((items) => {
1495
- // If there's nothing, paste whatever is on the editor clipboard, if there is something.
1496
- if (items.length === 0 && context.clipboard !== undefined)
1497
- context.handlePaste(context, context.clipboard, true);
1498
- else {
1499
- // See if there's data we can handle. Just look at the first.
1500
- const item = items[0];
1501
- // If there's something, try pasting that.
1502
- if (item) {
1503
- async function gatherClipboard() {
1504
- // Eventually we should add HTML support.
1505
- const contents = {
1506
- plain: undefined,
1507
- };
1508
- try {
1509
- {
1510
- const blob = await item.getType('text/plain');
1511
- const text = await blob.text();
1512
- contents.plain = text;
1513
- }
1514
- return context.handlePaste(context, contents, true);
1515
- }
1516
- catch (err) { }
1517
- }
1518
- gatherClipboard();
1519
- }
1520
- // Otherwise, try pasting what's on the app clipboard.
1521
- else if (context.clipboard !== undefined)
1522
- return context.handlePaste(context, context.clipboard, false);
1523
- }
1524
- });
1498
+ // Paste what was copied in the editor, if anything.
1499
+ const pasteEditorClipboard = () => {
1500
+ if (context.clipboard !== undefined)
1501
+ context.handlePaste(context, context.clipboard, true);
1502
+ };
1503
+ // See if there's something on the system clipboard.
1504
+ if (navigator.clipboard?.read) {
1505
+ navigator.clipboard
1506
+ .read()
1507
+ .then(async (items) => {
1508
+ // Eventually we should add HTML support. Just look at the first item.
1509
+ const item = items[0];
1510
+ if (item === undefined ||
1511
+ !item.types.includes('text/plain'))
1512
+ return pasteEditorClipboard();
1513
+ const text = await (await item.getType('text/plain')).text();
1514
+ // If the system clipboard has what was copied in the editor, paste that instead, to keep its formatting.
1515
+ if (context.clipboard !== undefined &&
1516
+ context.clipboard.toText() === text)
1517
+ pasteEditorClipboard();
1518
+ else
1519
+ context.handlePaste(context, { plain: text }, true);
1520
+ })
1521
+ // If we can't read the system clipboard (say, permission was denied), fall back to the editor's.
1522
+ .catch(pasteEditorClipboard);
1525
1523
  }
1526
- // Return the current caret to avoid unhandled command feedback.
1527
- return { root: context.root, range: context.range };
1524
+ else
1525
+ pasteEditorClipboard();
1526
+ // Report that we handled it, to avoid unhandled command feedback. The paste itself saves its edit,
1527
+ // so we return no edit here; returning the current root would overwrite a paste that already happened.
1528
+ return true;
1528
1529
  },
1529
1530
  },
1530
1531
  // Windows grave
@@ -1534,7 +1535,7 @@ const commands = [
1534
1535
  // Windows apostrophe
1535
1536
  createAccentCommand("'", 'Quote', true, false, false, 'insert an apostrophe accent'),
1536
1537
  // Mac apostrophe
1537
- createAccentCommand('`', 'KeyE', false, true, false, 'insert an apostrophe accent'),
1538
+ createAccentCommand("'", 'KeyE', false, true, false, 'insert an apostrophe accent'),
1538
1539
  // Windows caret
1539
1540
  createAccentCommand('^', 'Digit6', true, false, true, 'insert a caret accent'),
1540
1541
  // Mac caret
@@ -1544,9 +1545,9 @@ const commands = [
1544
1545
  // Mac tilde
1545
1546
  createAccentCommand('~', 'KeyN', false, true, false, 'insert a tilde accent'),
1546
1547
  // Windows umlaut
1547
- createAccentCommand(':', 'Semicolon', true, false, true, 'insert a tilde accent'),
1548
+ createAccentCommand(':', 'Semicolon', true, false, true, 'insert an umlaut accent'),
1548
1549
  // Mac umlaut
1549
- createAccentCommand(':', 'KeyU', false, true, false, 'insert a grave accent'),
1550
+ createAccentCommand(':', 'KeyU', false, true, false, 'insert an umlaut accent'),
1550
1551
  {
1551
1552
  icon: 'insert symbol',
1552
1553
  description: 'insert character',
@@ -0,0 +1 @@
1
+ export {};