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
@@ -57,7 +57,20 @@ export default class FormatNode extends Node {
57
57
  .find((b) => b !== undefined);
58
58
  }
59
59
  toText() {
60
- return this.#segments.map((segment) => segment.toText()).join(' ');
60
+ // Segments are parts of the same run of text, so they're joined directly
61
+ // ("un*believ*able" is one word, and the parser splits text at escapes,
62
+ // so a\_b is too). Atoms like footnotes are asides, so they're set apart
63
+ // with spaces so their words don't merge with their neighbors; symbols
64
+ // stand for inline text, so they aren't.
65
+ return this.#segments
66
+ .map((segment) => {
67
+ if (!(segment instanceof AtomNode) ||
68
+ segment.getType() === 'symbol')
69
+ return segment.toText();
70
+ const text = segment.toText();
71
+ return text.length > 0 ? ` ${text} ` : '';
72
+ })
73
+ .join('');
61
74
  }
62
75
  toHTML() {
63
76
  const format = this.#format;
@@ -73,11 +86,36 @@ export default class FormatNode extends Node {
73
86
  else
74
87
  return segments;
75
88
  }
76
- toBookdown() {
89
+ /**
90
+ * @param awaiting The delimiter that ends the content this format is in,
91
+ * such as the } of a footnote, which its text has to escape.
92
+ */
93
+ toBookdown(awaiting) {
94
+ let bookdown = '';
95
+ // Escape adjacent text nodes together, since whether a character needs
96
+ // escaping can depend on its neighbors (a % after a space, a : before
97
+ // a letter), and the parser splits text at every escape.
98
+ let text = undefined;
99
+ for (const segment of this.#segments) {
100
+ if (segment instanceof TextNode) {
101
+ text = (text ?? '') + segment.getText();
102
+ continue;
103
+ }
104
+ if (text !== undefined) {
105
+ bookdown += TextNode.escape(text, awaiting);
106
+ text = undefined;
107
+ }
108
+ bookdown +=
109
+ segment instanceof AtomNode
110
+ ? segment.toBookdown(this)
111
+ : segment instanceof FormatNode
112
+ ? segment.toBookdown(awaiting)
113
+ : segment.toBookdown();
114
+ }
115
+ if (text !== undefined)
116
+ bookdown += TextNode.escape(text, awaiting);
77
117
  return ((this.#format === 'v' ? '^v' : this.#format) +
78
- this.#segments
79
- .map((s) => s instanceof AtomNode ? s.toBookdown(this) : s.toBookdown())
80
- .join('') +
118
+ bookdown +
81
119
  (this.#format === 'v' ? '^' : this.#format));
82
120
  }
83
121
  getChildren() {
@@ -100,7 +138,14 @@ export default class FormatNode extends Node {
100
138
  // Get all text or atom nodes in this format, except for any inside an atom node,
101
139
  // as this is used for navigation and editing, and they should be isolated from that.
102
140
  getTextAndAtomNodes() {
103
- return this.getNodes().filter((n) => n instanceof TextNode || n instanceof AtomNode);
141
+ const nodes = [];
142
+ this.traverse((node, path) => {
143
+ if ((node instanceof TextNode || node instanceof AtomNode) &&
144
+ // The path includes the node itself, so check its ancestors.
145
+ !path.slice(0, -1).some((n) => n instanceof AtomNode))
146
+ nodes.push(node);
147
+ });
148
+ return nodes;
104
149
  }
105
150
  getAdjacentTextOrAtom(node, next) {
106
151
  // Find all of the text and atom nodes not in atom nodes in this node.
@@ -190,6 +235,8 @@ export default class FormatNode extends Node {
190
235
  return text.indexOf(node);
191
236
  }
192
237
  getSelectedText(range) {
238
+ // Selections can be backwards; read them forwards.
239
+ range = this.sortRange(range);
193
240
  if (!(range.start.node instanceof TextNode) ||
194
241
  !(range.end.node instanceof TextNode))
195
242
  return undefined;
@@ -765,20 +812,13 @@ export default class FormatNode extends Node {
765
812
  const segmentAfter = newFormat.getSegmentAfter(node);
766
813
  const newCaret = node instanceof AtomNode
767
814
  ? node.getDefaultCaret()
768
- : node instanceof FormatNode
769
- ? node.getLastCaret()
770
- : // Line break? Place the caret just after the line break, whether a text node or something else
771
- node instanceof LineBreakNode
772
- ? segmentAfter !== undefined &&
773
- segmentAfter instanceof TextNode
774
- ? { node: segmentAfter, index: 0 }
775
- : undefined
776
- : node instanceof MetadataNode
777
- ? {
778
- node: node.getText(),
779
- index: node.getText().getLength(),
780
- }
781
- : { node: node, index: node.getLength() };
815
+ : node instanceof TextNode
816
+ ? { node: node, index: node.getLength() }
817
+ : // Otherwise, place the caret just after the inserted node, so typing continues outside it.
818
+ segmentAfter !== undefined &&
819
+ segmentAfter instanceof TextNode
820
+ ? { node: segmentAfter, index: 0 }
821
+ : undefined;
782
822
  if (newCaret === undefined)
783
823
  return;
784
824
  return { root: newFormat, range: { start: newCaret, end: newCaret } };
@@ -19,8 +19,10 @@ export default class LabelNode extends AtomNode {
19
19
  toBookdown(format) {
20
20
  const id = this.getMeta();
21
21
  const nextText = format?.getNextTextOrAtom(this)?.toBookdown();
22
- // The trailing space after enables parsing. The error placeholder handles invalid empty label IDs.
23
- return `:${id === '' ? ERROR_PLACEHOLDER : id}${nextText?.startsWith(' ') ? '' : ' '}`;
22
+ // A label's ID ends at the first character that isn't a letter, so
23
+ // separate it from letters that follow with a space. The error
24
+ // placeholder handles invalid empty label IDs.
25
+ return `:${id === '' ? ERROR_PLACEHOLDER : id}${/^[a-z]/i.test(nextText ?? '') ? ' ' : ''}`;
24
26
  }
25
27
  getParentOf() {
26
28
  return undefined;
@@ -68,19 +68,17 @@ export default class ListNode extends BlockNode {
68
68
  return this.#items.map((item) => item.toText()).join(' ');
69
69
  }
70
70
  toBookdown(level = 1) {
71
- return this.isNumbered()
72
- ? this.#items
73
- .map((item, number) => (item instanceof ListNode
74
- ? ''
75
- : number + 1 + '.'.repeat(level) + ' ') +
76
- item.toBookdown(level + 1))
77
- .join('\n')
78
- : this.#items
79
- .map((item) => (item instanceof ListNode
80
- ? ''
81
- : '*'.repeat(level) + ' ') +
82
- item.toBookdown(level + 1))
83
- .join('\n');
71
+ // Number items, but not nested lists, which number their own.
72
+ let number = 0;
73
+ return this.#items
74
+ .map((item) => item instanceof ListNode
75
+ ? item.toBookdown(level + 1)
76
+ : (this.isNumbered()
77
+ ? ++number + '.'.repeat(level)
78
+ : '*'.repeat(level)) +
79
+ ' ' +
80
+ item.toBookdown())
81
+ .join('\n');
84
82
  }
85
83
  toHTML() {
86
84
  return this.isNumbered()
@@ -1,8 +1,6 @@
1
1
  import { test, expect } from 'vitest';
2
-
3
2
  import TextNode from './TextNode';
4
3
  import FormatNode from './FormatNode';
5
-
6
4
  const textOne = new TextNode('one');
7
5
  const textTwo = new TextNode('two');
8
6
  const textThree = new TextNode('three');
@@ -10,17 +8,10 @@ const textFour = new TextNode('four');
10
8
  const textFive = new TextNode('five');
11
9
  const bold = new FormatNode('*', [textThree, textFour]);
12
10
  const format = new FormatNode('', [textOne, textTwo, bold, textFive]);
13
-
14
11
  test('Replace descendants', () => {
15
- expect(
16
- format.withNodeReplaced(textThree, new TextNode('hi'))?.toBookdown(),
17
- ).toBe('onetwo*hifour*five');
18
-
19
- expect(
20
- format.withNodeReplaced(textFive, new TextNode('yo'))?.toBookdown(),
21
- ).toBe('onetwo*threefour*yo');
12
+ expect(format.withNodeReplaced(textThree, new TextNode('hi'))?.toBookdown()).toBe('onetwo*hifour*five');
13
+ expect(format.withNodeReplaced(textFive, new TextNode('yo'))?.toBookdown()).toBe('onetwo*threefour*yo');
22
14
  });
23
-
24
15
  test('Parents', () => {
25
16
  const parents = format.getParentsOf(textThree);
26
17
  expect(parents?.length).toBe(2);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,298 @@
1
+ import { describe, test, expect } from 'vitest';
2
+ import Parser from './Parser';
3
+ import ChapterNode from './ChapterNode';
4
+ import FormatNode from './FormatNode';
5
+ import TextNode from './TextNode';
6
+ import ParagraphNode from './ParagraphNode';
7
+ import ListNode from './ListNode';
8
+ import TableNode from './TableNode';
9
+ import RuleNode from './RuleNode';
10
+ import LineBreakNode from './LineBreakNode';
11
+ import FootnoteNode from './FootnoteNode';
12
+ import CodeNode from './CodeNode';
13
+ import BlocksNode from './BlocksNode';
14
+ import { LINE_BREAK } from './Symbols';
15
+ function text(root, content) {
16
+ const node = root.getTextNodes().find((t) => t.getText() === content);
17
+ if (node === undefined)
18
+ throw new Error(`No text node "${content}"`);
19
+ return node;
20
+ }
21
+ describe('BlocksNode', () => {
22
+ const one = new ParagraphNode(0, new FormatNode('', [new TextNode('one')]));
23
+ const two = new ParagraphNode(0, new FormatNode('', [new TextNode('two')]));
24
+ const blocks = new ChapterNode([one, two]);
25
+ test('withBlockInsertedBefore and After', () => {
26
+ expect(blocks.withBlockInsertedBefore(one, new RuleNode())?.toBookdown()).toBe('-\n\none\n\ntwo');
27
+ expect(blocks.withBlockInsertedAfter(one, new RuleNode())?.toBookdown()).toBe('one\n\n-\n\ntwo');
28
+ expect(blocks.withBlockInsertedAfter(two, new RuleNode())?.toBookdown()).toBe('one\n\ntwo\n\n-');
29
+ expect(blocks.withBlockInsertedAfter(new RuleNode(), new RuleNode())).toBeUndefined();
30
+ expect(blocks.toBookdown()).toBe('one\n\ntwo');
31
+ });
32
+ test('getBlocksInRange', () => {
33
+ const chapter = Parser.parseChapter(undefined, 'one\n\n* a\n* b\n\nthree\n\nfour');
34
+ const range = {
35
+ start: { node: text(chapter, 'one'), index: 1 },
36
+ end: { node: text(chapter, 'three'), index: 1 },
37
+ };
38
+ const inRange = chapter.getBlocksInRange(range);
39
+ expect(inRange?.map((b) => b.getType())).toEqual([
40
+ 'paragraph',
41
+ 'list',
42
+ 'paragraph',
43
+ ]);
44
+ const single = chapter.getBlocksInRange({
45
+ start: range.end,
46
+ end: range.end,
47
+ });
48
+ expect(single?.map((b) => b.toBookdown())).toEqual(['three']);
49
+ });
50
+ test('withNodeInserted merges a pasted paragraph at the caret', () => {
51
+ const chapter = Parser.parseChapter(undefined, 'Hello world');
52
+ const hello = text(chapter, 'Hello world');
53
+ const edit = chapter.withNodeInserted({ node: hello, index: 6 }, Parser.parseChapter(undefined, 'there '));
54
+ expect(edit?.root.toBookdown()).toBe('Hello there world');
55
+ });
56
+ test('withNodeInserted splits around pasted paragraphs', () => {
57
+ const chapter = Parser.parseChapter(undefined, 'Hello world');
58
+ const hello = text(chapter, 'Hello world');
59
+ const edit = chapter.withNodeInserted({ node: hello, index: 6 }, Parser.parseChapter(undefined, 'big\n\nwide '));
60
+ expect(edit?.root.toBookdown()).toBe('Hello big\n\nwide world');
61
+ // The caret is at the end of what was pasted.
62
+ if (edit === undefined)
63
+ return;
64
+ const caret = edit.range.start;
65
+ expect(caret.node).toBeInstanceOf(TextNode);
66
+ expect(caret.node.getText().substring(0, caret.index)).toBe('wide ');
67
+ });
68
+ test('withNodeInserted inserts non-paragraph blocks after the anchor', () => {
69
+ const chapter = Parser.parseChapter(undefined, 'one\n\ntwo');
70
+ const edit = chapter.withNodeInserted({ node: text(chapter, 'one'), index: 3 }, new RuleNode());
71
+ expect(edit?.root.toBookdown()).toBe('one\n\n-\n\n\n\ntwo');
72
+ // There's nowhere for a caret in a rule, so an empty paragraph follows it.
73
+ expect(edit?.range.start.node).toBeInstanceOf(TextNode);
74
+ });
75
+ test('withNodeInserted rejects nodes that are not blocks', () => {
76
+ const chapter = Parser.parseChapter(undefined, 'one');
77
+ expect(chapter.withNodeInserted({ node: text(chapter, 'one'), index: 0 }, new TextNode('x'))).toBeUndefined();
78
+ expect(chapter.withNodeInserted({ node: new TextNode('elsewhere'), index: 0 }, new RuleNode())).toBeUndefined();
79
+ });
80
+ });
81
+ describe('FormatNode', () => {
82
+ test('withNodeInserted inserts text and places the caret after it', () => {
83
+ const hi = new TextNode('Hi there');
84
+ const format = new FormatNode('', [hi]);
85
+ const edit = format.withNodeInserted({ node: hi, index: 2 }, new TextNode(','));
86
+ expect(edit?.root.toBookdown()).toBe('Hi, there');
87
+ expect((edit?.range.start.node).getText()).toBe(',');
88
+ expect(edit?.range.start.index).toBe(1);
89
+ });
90
+ test('withNodeInserted inserts a line break and places the caret after it', () => {
91
+ const hi = new TextNode('Hi there');
92
+ const format = new FormatNode('', [hi]);
93
+ const edit = format.withNodeInserted({ node: hi, index: 2 }, new LineBreakNode());
94
+ expect(edit?.root.toBookdown()).toBe(`Hi${LINE_BREAK} there`);
95
+ expect((edit?.range.start.node).getText()).toBe(' there');
96
+ expect(edit?.range.start.index).toBe(0);
97
+ });
98
+ test('withNodeInserted rejects blocks and foreign carets', () => {
99
+ const hi = new TextNode('Hi');
100
+ const format = new FormatNode('', [hi]);
101
+ expect(format.withNodeInserted({ node: hi, index: 0 }, new RuleNode())).toBeUndefined();
102
+ expect(format.withNodeInserted({ node: new TextNode(), index: 0 }, new TextNode('x'))).toBeUndefined();
103
+ });
104
+ test('withContentAt keeps content before or after a caret', () => {
105
+ const format = Parser.parseFormat(undefined, 'one *two* three');
106
+ const two = text(format, 'two');
107
+ expect(format.withContentAt({ node: two, index: 1 }, true)?.toBookdown()).toBe('one *t*');
108
+ expect(format.withContentAt({ node: two, index: 1 }, false)?.toBookdown()).toBe('*wo* three');
109
+ });
110
+ test('getSelectedText across nodes', () => {
111
+ const format = Parser.parseFormat(undefined, 'one *two* three');
112
+ const one = text(format, 'one ');
113
+ const three = text(format, ' three');
114
+ const forward = {
115
+ start: { node: one, index: 1 },
116
+ end: { node: three, index: 3 },
117
+ };
118
+ expect(format.getSelectedText(forward)).toBe('ne two th');
119
+ expect(format.getSelectedText({ start: forward.end, end: forward.start })).toBe('ne two th');
120
+ expect(format.getSelectedText({
121
+ start: { node: one, index: 1 },
122
+ end: { node: one, index: 3 },
123
+ })).toBe('ne');
124
+ });
125
+ test('getFormats lists enclosing formats, innermost first', () => {
126
+ const chapter = Parser.parseChapter(undefined, 'a *b _c_ d* e');
127
+ const c = text(chapter, 'c');
128
+ const italic = c.getFormat(chapter);
129
+ expect(italic?.getFormats(chapter)).toEqual(['_', '*']);
130
+ });
131
+ });
132
+ describe('ListNode', () => {
133
+ const chapter = Parser.parseChapter(undefined, '* one\n* two\n** sub');
134
+ const list = chapter.getBlocks()[0];
135
+ test('getItemContaining', () => {
136
+ expect(list.getItemContaining({ node: text(chapter, 'one'), index: 0 })).toBe(0);
137
+ expect(list.getItemContaining({ node: text(chapter, 'two'), index: 0 })).toBe(1);
138
+ // A sublist counts as one item.
139
+ expect(list.getItemContaining({ node: text(chapter, 'sub'), index: 0 })).toBe(2);
140
+ expect(list.getItemContaining({ node: new TextNode(), index: 0 })).toBeUndefined();
141
+ });
142
+ test('withoutItem', () => {
143
+ const first = list.getItem(0);
144
+ expect(list.withoutItem(first)?.toBookdown()).toBe('* two\n** sub');
145
+ expect(list.withoutItem(new FormatNode('', []))).toBeUndefined();
146
+ expect(list.toBookdown()).toBe('* one\n* two\n** sub');
147
+ });
148
+ });
149
+ describe('TableNode', () => {
150
+ const chapter = Parser.parseChapter(undefined, ',a|b\n,c|d\ncaption');
151
+ const table = chapter.getBlocks()[0];
152
+ const [[a, b], [c, d]] = table.getRows();
153
+ test('locate', () => {
154
+ expect(table.locate(a)).toEqual({ row: 0, column: 0 });
155
+ expect(table.locate(d)).toEqual({ row: 1, column: 1 });
156
+ expect(table.locate(table.getCaption())).toBeUndefined();
157
+ });
158
+ test('getNextCell walks rows in both directions', () => {
159
+ expect(table.getNextCell(a)).toBe(b);
160
+ expect(table.getNextCell(b)).toBe(c);
161
+ expect(table.getNextCell(d)).toBeUndefined();
162
+ expect(table.getNextCell(c, -1)).toBe(b);
163
+ expect(table.getNextCell(a, -1)).toBeUndefined();
164
+ });
165
+ test('toHTML closes every row', () => {
166
+ expect(table.toHTML()).toBe('<table><tbody><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></tbody></table><center>caption</center>');
167
+ });
168
+ });
169
+ describe('ParagraphNode.withLevel', () => {
170
+ test('changes the level and keeps the content', () => {
171
+ const paragraph = Parser.parseChapter(undefined, 'Some _text_').getBlocks()[0];
172
+ expect(paragraph.withLevel(2).toBookdown()).toBe('## Some _text_');
173
+ expect(paragraph.withLevel(2).withLevel(0).toBookdown()).toBe('Some _text_');
174
+ expect(paragraph.getLevel()).toBe(0);
175
+ });
176
+ });
177
+ describe('Bookdown round trips', () => {
178
+ // Text typed into the editor must come back as the same text after saving and reloading.
179
+ const literal = [
180
+ 'back\\slash',
181
+ 'under_score',
182
+ 'star*s',
183
+ 'tick`s',
184
+ '<angle>',
185
+ 'caret^',
186
+ '{brace}',
187
+ 'tilde~',
188
+ 'a %percent',
189
+ '[bracket]',
190
+ 'at@sign',
191
+ 'label:like',
192
+ 'label:Like',
193
+ '%at start',
194
+ `line${LINE_BREAK}break`,
195
+ ];
196
+ for (const content of literal) {
197
+ test(`text "${content}"`, () => {
198
+ const bookdown = new TextNode(content).toBookdown();
199
+ const format = Parser.parseFormat(undefined, bookdown);
200
+ expect(format.toText()).toBe(content);
201
+ expect(format.getSegments().every((s) => s instanceof TextNode)).toBe(true);
202
+ });
203
+ }
204
+ // Text at the start of a paragraph mustn't turn into other blocks.
205
+ const leaders = [
206
+ '# not a header',
207
+ '- not a rule',
208
+ '* not a bullet',
209
+ '1. not a number',
210
+ '| not an embed',
211
+ ', not a table',
212
+ '%not a comment',
213
+ '`',
214
+ ];
215
+ for (const content of leaders) {
216
+ test(`paragraph "${content}"`, () => {
217
+ const chapter = new ChapterNode([
218
+ new ParagraphNode(0, new FormatNode('', [new TextNode(content)])),
219
+ ]);
220
+ const reparsed = Parser.parseChapter(undefined, chapter.toBookdown());
221
+ expect(reparsed.getBlocks().length).toBe(1);
222
+ expect(reparsed.getBlocks()[0]).toBeInstanceOf(ParagraphNode);
223
+ expect(reparsed.toText()).toBe(content);
224
+ });
225
+ }
226
+ });
227
+ describe('TextNode words', () => {
228
+ const chapter = Parser.parseChapter(undefined, 'one two, three\n\nfour');
229
+ const first = text(chapter, 'one two, three');
230
+ const four = text(chapter, 'four');
231
+ test('nextWord moves to the end of the next word', () => {
232
+ expect(first.nextWord(chapter, 0)).toEqual({ node: first, index: 3 });
233
+ expect(first.nextWord(chapter, 3)).toEqual({ node: first, index: 7 });
234
+ expect(first.nextWord(chapter, 7)).toEqual({ node: first, index: 14 });
235
+ });
236
+ test('nextWord at the end of a paragraph moves to the next one', () => {
237
+ expect(first.nextWord(chapter, 14)).toEqual({ node: four, index: 0 });
238
+ expect(four.nextWord(chapter, 4)).toEqual({ node: four, index: 4 });
239
+ });
240
+ test('previousWord moves to the start of the previous word', () => {
241
+ expect(first.previousWord(chapter, 14)).toEqual({
242
+ node: first,
243
+ index: 9,
244
+ });
245
+ expect(first.previousWord(chapter, 9)).toEqual({
246
+ node: first,
247
+ index: 4,
248
+ });
249
+ expect(first.previousWord(chapter, 4)).toEqual({
250
+ node: first,
251
+ index: 0,
252
+ });
253
+ });
254
+ test('previousWord at the start of a paragraph moves to the previous one', () => {
255
+ expect(four.previousWord(chapter, 0)).toEqual({
256
+ node: first,
257
+ index: 14,
258
+ });
259
+ expect(first.previousWord(chapter, 0)).toEqual({
260
+ node: first,
261
+ index: 0,
262
+ });
263
+ });
264
+ });
265
+ describe('footnotes and code', () => {
266
+ test('footnotes round trip', () => {
267
+ const chapter = Parser.parseChapter(undefined, 'Text{A _note_}.');
268
+ expect(chapter.toBookdown()).toBe('Text{A _note_}.');
269
+ expect(chapter.getNodes().some((n) => n instanceof FootnoteNode)).toBe(true);
270
+ });
271
+ test('code blocks keep backticks', () => {
272
+ const code = new CodeNode(new TextNode('a `b` c'), 'js', '|');
273
+ const reparsed = Parser.parseChapter(undefined, code.toBookdown());
274
+ const block = reparsed.getBlocks()[0];
275
+ expect(block).toBeInstanceOf(CodeNode);
276
+ expect(block.getCodeNode().getText()).toBe('a `b` c');
277
+ });
278
+ test('BlocksNode is the base of chapters', () => {
279
+ expect(Parser.parseChapter(undefined, 'x')).toBeInstanceOf(BlocksNode);
280
+ });
281
+ });
282
+ describe('FormatNode.toText', () => {
283
+ test('joins segments without adding spaces', () => {
284
+ expect(Parser.parseFormat(undefined, 'un*believ*able').toText()).toBe('unbelievable');
285
+ expect(Parser.parseFormat(undefined, 'a\\_b').toText()).toBe('a_b');
286
+ });
287
+ test('sets footnotes apart and skips empty atoms', () => {
288
+ expect(Parser.parseFormat(undefined, 'word{note}.').toText()).toBe('word note .');
289
+ expect(Parser.parseFormat(undefined, 'a<ref>b').toText()).toBe('ab');
290
+ });
291
+ test('a percent after a space in an adjacent text node stays text', () => {
292
+ const format = new FormatNode('', [
293
+ new TextNode('a '),
294
+ new TextNode('%b'),
295
+ ]);
296
+ expect(Parser.parseFormat(undefined, format.toBookdown()).toText()).toBe('a %b');
297
+ });
298
+ });
@@ -3,6 +3,22 @@ import FormatNode from './FormatNode';
3
3
  import TextNode from './TextNode';
4
4
  import AtomNode from './AtomNode';
5
5
  import MetadataNode from './MetadataNode';
6
+ /**
7
+ * Text that happens to start a paragraph the way another block starts (a #
8
+ * header, a | embed, a , table, a numbered list, a line of dashes, an = or "
9
+ * alone on a line, or an @name: symbol declaration) would be parsed as that
10
+ * block when the chapter is next loaded, so escape it. Other block markers
11
+ * (*, `, %) are already escaped by the text itself.
12
+ */
13
+ function escapeBlockStart(bookdown) {
14
+ if (/^[#|,]/.test(bookdown) || /^[0-9]+\./.test(bookdown))
15
+ return '\\' + bookdown;
16
+ if (/^-+[ \t]*$/.test(bookdown))
17
+ return bookdown.replace(/-/g, '\\-');
18
+ if (/^[="][ \t]*$/.test(bookdown))
19
+ return '\\' + bookdown;
20
+ return bookdown.replace(/^(@[a-zA-Z0-9]+[ \t]*):/, '$1\\:');
21
+ }
6
22
  export default class ParagraphNode extends BlockNode {
7
23
  #format;
8
24
  #level;
@@ -68,9 +84,19 @@ export default class ParagraphNode extends BlockNode {
68
84
  return this.#format.toText();
69
85
  }
70
86
  toBookdown() {
71
- return this.#level === 0
72
- ? this.#format.toBookdown()
73
- : `${'#'.repeat(this.#level)} ${this.#format.toBookdown()}`;
87
+ if (this.#level > 0)
88
+ return `${'#'.repeat(this.#level)} ${this.#format.toBookdown()}`;
89
+ const bookdown = escapeBlockStart(this.#format.toBookdown());
90
+ // A line starting with % reads as a comment filling the line. If this
91
+ // paragraph only starts with a comment and goes on, start it with an
92
+ // escaped space instead, so the rest isn't read as part of the comment.
93
+ const content = this.#format
94
+ .getSegments()
95
+ .filter((s) => !(s instanceof TextNode && s.getText() === ''));
96
+ return /^\s*%/.test(bookdown) &&
97
+ !(content.length === 1 && content[0].getType() === 'comment')
98
+ ? `\\ ${bookdown.trimStart()}`
99
+ : bookdown;
74
100
  }
75
101
  toHTML() {
76
102
  const tag = this.#level === 0 ? 'p' : `h${this.#level}`;
@@ -22,6 +22,8 @@ import type Position from './Position';
22
22
  import type BlockNode from './BlockNode';
23
23
  import type Bookkeeping from './Bookkeeping';
24
24
  import LineBreakNode from './LineBreakNode';
25
+ import SymbolNode from './SymbolNode';
26
+ import SymbolBlockNode from './SymbolBlockNode';
25
27
  export declare const Reserved: RegExp;
26
28
  export default class Parser {
27
29
  book: Edition | undefined;
@@ -29,11 +31,20 @@ export default class Parser {
29
31
  index: number;
30
32
  openedDoubleQuote: boolean;
31
33
  metadata: Bookkeeping;
32
- constructor(book: Edition | undefined, text: string);
33
- static preprocessSymbols(book: Edition, text: string): string;
34
+ /** Symbols declared by an enclosing chapter, when parsing a definition. */
35
+ readonly inherited: Record<string, string>;
36
+ /** Symbols whose definitions are being parsed, to stop cycles. */
37
+ readonly resolving: ReadonlySet<string>;
38
+ constructor(book: Edition | undefined, text: string, symbols?: Record<string, string>, resolving?: ReadonlySet<string>);
34
39
  static parseChapter(book: Edition | undefined, text: string): ChapterNode;
35
- static parseFormat(book: Edition | undefined, text: string): FormatNode;
40
+ /**
41
+ * Parse inline content. Symbols resolve against the given chapter symbols,
42
+ * then the edition's.
43
+ */
44
+ static parseFormat(book: Edition | undefined, text: string, symbols?: Record<string, string>): FormatNode;
36
45
  static parseEmbed(book: Edition | undefined, text: string): EmbedNode;
46
+ /** The symbols in scope; chapter declarations shadow the edition's. */
47
+ getSymbols(): Record<string, string>;
37
48
  peek(): string | null;
38
49
  more(): boolean;
39
50
  nextIsEmptyParagraph(): boolean;
@@ -47,6 +58,7 @@ export default class Parser {
47
58
  nextIs(text: string): boolean;
48
59
  nextIsContentDelimiter(): boolean;
49
60
  nextMatches(regex: RegExp): boolean;
61
+ nextIsCommentStart(): boolean;
50
62
  isBlankLine(): boolean;
51
63
  readWhitespace(): void;
52
64
  readUntilNewLine(): string;
@@ -54,6 +66,13 @@ export default class Parser {
54
66
  parseChapter(): ChapterNode;
55
67
  parseSymbols(): void;
56
68
  parseBlock(): BlockNode;
69
+ /**
70
+ * A line starting with % is a comment, to the end of the line. It becomes a
71
+ * paragraph holding only a comment, which readers don't see, so it survives
72
+ * being saved. The comment is written back with a closing %, which is
73
+ * dropped again here, so that the line doesn't grow on every save.
74
+ */
75
+ parseBlockComment(): ParagraphNode;
57
76
  parseParagraph(): ParagraphNode;
58
77
  parseHeader(): ParagraphNode;
59
78
  parseRule(): RuleNode;
@@ -73,6 +92,32 @@ export default class Parser {
73
92
  parseCitations(): CitationsNode;
74
93
  parseFootnote(): FootnoteNode;
75
94
  parseDefinition(): DefinitionNode;
76
- parseEscaped(): TextNode | ErrorNode;
95
+ parseEscaped(): TextNode;
96
+ /**
97
+ * Parse @name. The name is the longest symbol in scope that the text
98
+ * continues with, so edition symbols whose names have other characters
99
+ * still resolve; otherwise it's the letters and numbers after the @. A
100
+ * symbol with no definition still keeps its name, so it is saved as written.
101
+ */
102
+ /**
103
+ * The longest name of a symbol in scope that the text after the @ at the
104
+ * given index continues with, ending at the end of a name.
105
+ */
106
+ matchSymbol(symbols: Record<string, string>, index: number): string | undefined;
107
+ /**
108
+ * Symbols used to be expanded into the text before parsing, so books use
109
+ * symbols as macros for blocks: a line that is a symbol can be a header,
110
+ * and consecutive lines that start with symbols can be the rows of one
111
+ * table, each line continuing its symbol's row with more cells. Parse a
112
+ * run of lines that each start with a defined symbol as the blocks they
113
+ * make when each line's first symbol is replaced by its definition,
114
+ * keeping the lines as written, so they are saved unchanged. If that only
115
+ * makes plain paragraphs, the symbols are left to parse inline, so they
116
+ * stay editable in their paragraph.
117
+ */
118
+ parseSymbolBlock(): SymbolBlockNode | undefined;
119
+ /** Parse blocks until the end of the text. */
120
+ parseBlocks(): BlockNode[];
121
+ parseSymbol(): SymbolNode | TextNode;
77
122
  parseLink(): LinkNode | ErrorNode;
78
123
  }