@folijs/core 0.2.0 → 0.3.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 (115) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +10 -16
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +22 -22
  6. package/dist/document.js.map +1 -1
  7. package/dist/index.d.ts +3 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/model/fragment.d.ts +5 -2
  12. package/dist/model/fragment.d.ts.map +1 -1
  13. package/dist/model/fragment.js +5 -2
  14. package/dist/model/fragment.js.map +1 -1
  15. package/dist/model/node.d.ts +1 -1
  16. package/dist/model/node.d.ts.map +1 -1
  17. package/dist/model/node.js.map +1 -1
  18. package/dist/schema.d.ts +10 -1
  19. package/dist/schema.d.ts.map +1 -1
  20. package/dist/schema.js +11 -1
  21. package/dist/schema.js.map +1 -1
  22. package/dist/state/commands.d.ts +7 -6
  23. package/dist/state/commands.d.ts.map +1 -1
  24. package/dist/state/commands.js +134 -97
  25. package/dist/state/commands.js.map +1 -1
  26. package/dist/state/editor.d.ts +25 -15
  27. package/dist/state/editor.d.ts.map +1 -1
  28. package/dist/state/editor.js +44 -16
  29. package/dist/state/editor.js.map +1 -1
  30. package/dist/state/format.d.ts +8 -22
  31. package/dist/state/format.d.ts.map +1 -1
  32. package/dist/state/format.js +16 -140
  33. package/dist/state/format.js.map +1 -1
  34. package/dist/state/index.d.ts +8 -4
  35. package/dist/state/index.d.ts.map +1 -1
  36. package/dist/state/index.js +8 -4
  37. package/dist/state/index.js.map +1 -1
  38. package/dist/state/links.d.ts.map +1 -1
  39. package/dist/state/links.js +10 -2
  40. package/dist/state/links.js.map +1 -1
  41. package/dist/state/lists.d.ts +19 -32
  42. package/dist/state/lists.d.ts.map +1 -1
  43. package/dist/state/lists.js +23 -372
  44. package/dist/state/lists.js.map +1 -1
  45. package/dist/state/mark.d.ts +25 -0
  46. package/dist/state/mark.d.ts.map +1 -0
  47. package/dist/state/mark.js +40 -0
  48. package/dist/state/mark.js.map +1 -0
  49. package/dist/state/state.d.ts.map +1 -1
  50. package/dist/state/state.js +11 -0
  51. package/dist/state/state.js.map +1 -1
  52. package/dist/state/word.d.ts +72 -0
  53. package/dist/state/word.d.ts.map +1 -0
  54. package/dist/state/word.js +173 -0
  55. package/dist/state/word.js.map +1 -0
  56. package/dist/state/wordclip.d.ts +43 -0
  57. package/dist/state/wordclip.d.ts.map +1 -0
  58. package/dist/state/wordclip.js +412 -0
  59. package/dist/state/wordclip.js.map +1 -0
  60. package/dist/state/wordformat.d.ts +136 -0
  61. package/dist/state/wordformat.d.ts.map +1 -0
  62. package/dist/state/wordformat.js +846 -0
  63. package/dist/state/wordformat.js.map +1 -0
  64. package/dist/v3/check.d.ts +33 -0
  65. package/dist/v3/check.d.ts.map +1 -0
  66. package/dist/v3/check.js +90 -0
  67. package/dist/v3/check.js.map +1 -0
  68. package/dist/v3/document.d.ts +217 -0
  69. package/dist/v3/document.d.ts.map +1 -0
  70. package/dist/v3/document.js +225 -0
  71. package/dist/v3/document.js.map +1 -0
  72. package/dist/v3/index.d.ts +6 -0
  73. package/dist/v3/index.d.ts.map +1 -0
  74. package/dist/v3/index.js +6 -0
  75. package/dist/v3/index.js.map +1 -0
  76. package/dist/v3/migrate.d.ts +19 -0
  77. package/dist/v3/migrate.d.ts.map +1 -0
  78. package/dist/v3/migrate.js +227 -0
  79. package/dist/v3/migrate.js.map +1 -0
  80. package/dist/v3/resolve.d.ts +129 -0
  81. package/dist/v3/resolve.d.ts.map +1 -0
  82. package/dist/v3/resolve.js +534 -0
  83. package/dist/v3/resolve.js.map +1 -0
  84. package/dist/v3/schema.d.ts +27 -0
  85. package/dist/v3/schema.d.ts.map +1 -0
  86. package/dist/v3/schema.js +429 -0
  87. package/dist/v3/schema.js.map +1 -0
  88. package/dist/v3/units.d.ts +16 -0
  89. package/dist/v3/units.d.ts.map +1 -0
  90. package/dist/v3/units.js +28 -0
  91. package/dist/v3/units.js.map +1 -0
  92. package/package.json +1 -1
  93. package/src/document.ts +26 -26
  94. package/src/index.ts +3 -6
  95. package/src/model/fragment.ts +11 -3
  96. package/src/model/node.ts +6 -1
  97. package/src/schema.ts +13 -1
  98. package/src/state/commands.ts +147 -91
  99. package/src/state/editor.ts +81 -35
  100. package/src/state/format.ts +24 -122
  101. package/src/state/index.ts +34 -3
  102. package/src/state/links.ts +10 -2
  103. package/src/state/lists.ts +31 -408
  104. package/src/state/mark.ts +47 -0
  105. package/src/state/state.ts +11 -0
  106. package/src/state/word.ts +245 -0
  107. package/src/state/wordclip.ts +445 -0
  108. package/src/state/wordformat.ts +982 -0
  109. package/src/v3/check.ts +119 -0
  110. package/src/v3/document.ts +456 -0
  111. package/src/v3/index.ts +33 -0
  112. package/src/v3/migrate.ts +267 -0
  113. package/src/v3/resolve.ts +646 -0
  114. package/src/v3/schema.ts +479 -0
  115. package/src/v3/units.ts +34 -0
@@ -97,8 +97,16 @@ export class Fragment {
97
97
  }
98
98
  }
99
99
 
100
- /** Text between two positions; `blockSeparator` goes between textblocks, `leafText` for leaves. */
101
- textBetween(from: number, to: number, blockSeparator = "", leafText = ""): string {
100
+ /**
101
+ * Text between two positions; `blockSeparator` goes between textblocks, `leafText` for leaves
102
+ * (a string, or one per leaf).
103
+ */
104
+ textBetween(
105
+ from: number,
106
+ to: number,
107
+ blockSeparator = "",
108
+ leafText: string | ((leaf: Node) => string) = "",
109
+ ): string {
102
110
  let text = "";
103
111
  let first = true;
104
112
  this.nodesBetween(from, to, (node, pos) => {
@@ -108,7 +116,7 @@ export class Fragment {
108
116
  } else if (node.isText) {
109
117
  text += node.textContent.slice(Math.max(from, pos) - pos, to - pos);
110
118
  } else if (node.isLeaf) {
111
- text += leafText;
119
+ text += typeof leafText === "string" ? leafText : leafText(node);
112
120
  }
113
121
  return undefined;
114
122
  });
package/src/model/node.ts CHANGED
@@ -115,7 +115,12 @@ export class Node {
115
115
  this.nodesBetween(0, this.content.size, f);
116
116
  }
117
117
 
118
- textBetween(from: number, to: number, blockSeparator?: string, leafText?: string): string {
118
+ textBetween(
119
+ from: number,
120
+ to: number,
121
+ blockSeparator?: string,
122
+ leafText?: string | ((leaf: Node) => string),
123
+ ): string {
119
124
  return this.content.textBetween(from, to, blockSeparator, leafText);
120
125
  }
121
126
 
package/src/schema.ts CHANGED
@@ -41,6 +41,18 @@ export function isSafeHref(href: unknown): href is string {
41
41
  return (SAFE_LINK_PROTOCOLS as readonly string[]).includes(`${scheme[1]?.toLowerCase()}:`);
42
42
  }
43
43
 
44
+ /**
45
+ * Whether a link's attributes may come in from outside the document (a command, a paste from
46
+ * elsewhere): a safe `href`, or none with a bookmark (`anchor`, schema v3: Word's table of
47
+ * contents and cross-references).
48
+ */
49
+ export function isSafeLink(
50
+ attrs: { href?: unknown; anchor?: unknown } | null | undefined,
51
+ ): boolean {
52
+ if (attrs?.href === null || attrs?.href === undefined) return typeof attrs?.anchor === "string";
53
+ return isSafeHref(attrs.href);
54
+ }
55
+
44
56
  /** Whether `color` is a canonical color value: `#rrggbb`, lowercase. */
45
57
  export function isColor(color: unknown): color is string {
46
58
  return typeof color === "string" && /^#[0-9a-f]{6}$/.test(color);
@@ -59,7 +71,7 @@ const color = {
59
71
  isColor(value) ? undefined : "color must be a lowercase #rrggbb value",
60
72
  };
61
73
 
62
- export const schema = new Schema({
74
+ export const schemaV2 = new Schema({
63
75
  nodes: {
64
76
  doc: { content: "block+" },
65
77
  paragraph: { group: "block", content: "inline*", attrs: { align } },
@@ -9,9 +9,11 @@ import {
9
9
  type ResolvedPos,
10
10
  Slice,
11
11
  } from "../model/index.js";
12
+ import { isSafeLink } from "../schema.js";
12
13
  import { attempt } from "./attempt.js";
13
14
  import { redo, undo } from "./history.js";
14
15
  import { openLinkEditor } from "./links.js";
16
+ import { keepLastMark, typedMarks } from "./mark.js";
15
17
  import { AllSelection, marksAt, NodeSelection, Selection, TextSelection } from "./selection.js";
16
18
  import {
17
19
  type Command,
@@ -20,6 +22,18 @@ import {
20
22
  Plugin,
21
23
  type Transaction,
22
24
  } from "./state.js";
25
+ import {
26
+ isMarker,
27
+ isOpaque,
28
+ isWordToggle,
29
+ selectionAt,
30
+ splitAttrs,
31
+ toggledCaretMarks,
32
+ toggleRanges,
33
+ wordContext,
34
+ wordToggleActive,
35
+ } from "./word.js";
36
+ import { defaultParagraphStyleOf, setParagraphStyle, setStyleNamed } from "./wordformat.js";
23
37
 
24
38
  export type DeleteUnit = "char" | "word";
25
39
 
@@ -31,6 +45,13 @@ const LEAF = "\n";
31
45
  const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
32
46
  const words = new Intl.Segmenter(undefined, { granularity: "word" });
33
47
 
48
+ /** `state` with a caret at `pos` (a command then runs as if the caret were there). */
49
+ function at(state: EditorState, pos: number): EditorState {
50
+ return pos === state.selection.head
51
+ ? state
52
+ : state.apply(state.tr.setSelection(TextSelection.create(state.doc, pos)));
53
+ }
54
+
34
55
  function caret(state: EditorState): ResolvedPos | null {
35
56
  const { selection } = state;
36
57
  return selection.empty && selection instanceof TextSelection ? selection.$head : null;
@@ -62,16 +83,28 @@ export function insertText(text: string): Command {
62
83
  (selection.empty ? marksAt($from) : ($from.nodeAfter?.marks ?? marksAt($from)));
63
84
  tr.deleteSelection();
64
85
  const $pos = tr.selection.$from;
65
- const allowed = marks.filter((mark) => $pos.parent.type.allowsMarkType(mark.type));
86
+ const allowed = typedMarks(marks).filter((mark) =>
87
+ $pos.parent.type.allowsMarkType(mark.type),
88
+ );
66
89
  tr.insertText(text, $pos.pos, $pos.pos, allowed);
67
90
  tr.setSelection(TextSelection.create(tr.doc, $pos.pos + text.length));
68
91
  });
69
92
  };
70
93
  }
71
94
 
72
- /** Length (in positions) of the last grapheme or word before `$pos` in its textblock. */
73
- function backwardExtent($pos: ResolvedPos, unit: DeleteUnit): number {
74
- const text = $pos.parent.textBetween(0, $pos.parentOffset, "", LEAF);
95
+ /**
96
+ * Length (in positions) of the last grapheme or word before `$pos` in its textblock. With
97
+ * `textOnly` (schema v3) a word stops at the inline node before it (a tab, a break, a field, a
98
+ * marker): those go one per key, as Word deletes them; the node itself counts as one position.
99
+ */
100
+ function backwardExtent($pos: ResolvedPos, unit: DeleteUnit, textOnly = false): number {
101
+ let from = 0;
102
+ if (textOnly && unit === "word")
103
+ $pos.parent.forEach((child, offset) => {
104
+ if (!child.isText && offset < $pos.parentOffset) from = offset + child.nodeSize;
105
+ });
106
+ if (from === $pos.parentOffset && from > 0) return 1;
107
+ const text = $pos.parent.textBetween(from, $pos.parentOffset, "", LEAF);
75
108
  if (unit === "char") return [...graphemes.segment(text)].pop()?.segment.length ?? 0;
76
109
  const segments = [...words.segment(text)];
77
110
  let length = 0;
@@ -80,9 +113,15 @@ function backwardExtent($pos: ResolvedPos, unit: DeleteUnit): number {
80
113
  return length + (segments.pop()?.segment.length ?? 0);
81
114
  }
82
115
 
83
- /** Length of the first grapheme or word after `$pos` in its textblock. */
84
- function forwardExtent($pos: ResolvedPos, unit: DeleteUnit): number {
85
- const text = $pos.parent.textBetween($pos.parentOffset, $pos.parent.content.size, "", LEAF);
116
+ /** Length of the first grapheme or word after `$pos` in its textblock (`textOnly`: as backward). */
117
+ function forwardExtent($pos: ResolvedPos, unit: DeleteUnit, textOnly = false): number {
118
+ let to = $pos.parent.content.size;
119
+ if (textOnly && unit === "word")
120
+ $pos.parent.forEach((child, offset) => {
121
+ if (!child.isText && offset >= $pos.parentOffset && offset < to) to = offset;
122
+ });
123
+ if (to === $pos.parentOffset && to < $pos.parent.content.size) return 1;
124
+ const text = $pos.parent.textBetween($pos.parentOffset, to, "", LEAF);
86
125
  const segments = [...(unit === "char" ? graphemes : words).segment(text)];
87
126
  if (unit === "char") return segments[0]?.segment.length ?? 0;
88
127
  let length = 0;
@@ -95,10 +134,20 @@ function forwardExtent($pos: ResolvedPos, unit: DeleteUnit): number {
95
134
  export function deleteBackward(unit: DeleteUnit = "char"): Command {
96
135
  return (state, dispatch) => {
97
136
  if (!state.selection.empty) return deleteSelection(state, dispatch);
98
- const $pos = caret(state);
99
- if (!$pos) return false;
100
- if ($pos.parentOffset === 0) return joinBackward(state, dispatch);
101
- const size = backwardExtent($pos, unit);
137
+ const found = caret(state);
138
+ if (!found) return false;
139
+ // Invisible markers (a bookmark, a comment's range) stay: the character before them goes.
140
+ const word = wordContext(state);
141
+ let $pos = found;
142
+ while ($pos.parentOffset > 0 && isMarker(word, $pos.nodeBefore))
143
+ $pos = state.doc.resolve($pos.pos - 1);
144
+ if ($pos.parentOffset === 0) return joinBackward(at(state, $pos.pos), dispatch);
145
+ if (isOpaque(word, $pos.nodeBefore)) {
146
+ const node = $pos.nodeBefore as Node;
147
+ dispatch?.(state.tr.setSelection(selectionAt(state, $pos.pos - node.nodeSize)));
148
+ return true;
149
+ }
150
+ const size = backwardExtent($pos, unit, word !== null);
102
151
  return attempt(state, dispatch, (tr) => tr.delete($pos.pos - size, $pos.pos));
103
152
  };
104
153
  }
@@ -107,17 +156,26 @@ export function deleteBackward(unit: DeleteUnit = "char"): Command {
107
156
  export function deleteForward(unit: DeleteUnit = "char"): Command {
108
157
  return (state, dispatch) => {
109
158
  if (!state.selection.empty) return deleteSelection(state, dispatch);
110
- const $pos = caret(state);
111
- if (!$pos) return false;
112
- if ($pos.parentOffset === $pos.parent.content.size) return joinForward(state, dispatch);
113
- const size = forwardExtent($pos, unit);
159
+ const found = caret(state);
160
+ if (!found) return false;
161
+ const word = wordContext(state);
162
+ let $pos = found;
163
+ while ($pos.parentOffset < $pos.parent.content.size && isMarker(word, $pos.nodeAfter))
164
+ $pos = state.doc.resolve($pos.pos + 1);
165
+ if ($pos.parentOffset === $pos.parent.content.size)
166
+ return joinForward(at(state, $pos.pos), dispatch);
167
+ if (isOpaque(word, $pos.nodeAfter)) {
168
+ dispatch?.(state.tr.setSelection(selectionAt(state, $pos.pos)));
169
+ return true;
170
+ }
171
+ const size = forwardExtent($pos, unit, word !== null);
114
172
  return attempt(state, dispatch, (tr) => tr.delete($pos.pos, $pos.pos + size));
115
173
  };
116
174
  }
117
175
 
118
176
  /**
119
- * At the start of a textblock: merges it into the previous textblock, or deletes a previous leaf
120
- * block. Does nothing at the start of the first block.
177
+ * At the start of a textblock: merges it into the previous textblock, or selects a previous
178
+ * opaque block (a table), as Word does. Does nothing at the start of the first block.
121
179
  */
122
180
  export const joinBackward: Command = (state, dispatch) => {
123
181
  const $pos = caret(state);
@@ -126,83 +184,41 @@ export const joinBackward: Command = (state, dispatch) => {
126
184
  if (index === 0) return false;
127
185
  const before = $pos.node($pos.depth - 1).child(index - 1);
128
186
  const boundary = $pos.before();
129
- if (before.isTextblock) return attempt(state, dispatch, (tr) => tr.join(boundary));
130
- if (before.isLeaf)
131
- return attempt(state, dispatch, (tr) => tr.delete(boundary - before.nodeSize, boundary));
132
- // After a container (a list): into its last textblock, at any depth.
133
- let levels = 1;
134
- let target: Node | null = before;
135
- while (target && !target.isTextblock && !target.isLeaf) {
136
- target = target.lastChild;
137
- levels++;
138
- }
139
- if (target?.isLeaf) {
140
- // A container ending in a leaf block (a rule): delete the leaf.
141
- const end = boundary - (levels - 1);
142
- const leaf = target;
143
- return attempt(state, dispatch, (tr) => tr.delete(end - leaf.nodeSize, end));
187
+ if (before.isTextblock)
188
+ return attempt(state, dispatch, (tr) => {
189
+ tr.join(boundary);
190
+ // The merged paragraph ends with this one's mark (schema v3: its section break).
191
+ keepLastMark(tr, boundary - before.nodeSize, $pos.parent);
192
+ });
193
+ if (before.isLeaf && isOpaque(wordContext(state), before)) {
194
+ dispatch?.(state.tr.setSelection(selectionAt(state, boundary - before.nodeSize)));
195
+ return true;
144
196
  }
145
- if (!target?.isTextblock) return false;
146
- const parent = $pos.node($pos.depth - 1);
147
- if (!parent.canReplace(index, index + 1)) return false;
148
- const joinAt = boundary - levels;
149
- const content = $pos.parent.content;
150
- return attempt(state, dispatch, (tr) => {
151
- tr.insert(joinAt, content);
152
- const start = tr.mapping.map(boundary);
153
- tr.delete(start, start + $pos.parent.nodeSize);
154
- tr.setSelection(TextSelection.create(tr.doc, joinAt));
155
- });
197
+ return false;
156
198
  };
157
199
 
158
200
  /**
159
- * At the end of a textblock: merges the next textblock into it, or deletes a next leaf block. At
160
- * the end of a container's last block (a list item), what follows the container comes in.
201
+ * At the end of a textblock: merges the next textblock into it, or selects a next opaque block.
161
202
  */
162
203
  export const joinForward: Command = (state, dispatch) => {
163
204
  const $pos = caret(state);
164
205
  if (!$pos?.parent.isTextblock || $pos.parentOffset < $pos.parent.content.size || $pos.depth < 1) {
165
206
  return false;
166
207
  }
167
- // The innermost container in which something follows the caret's block.
168
- let base = $pos.depth - 1;
169
- while (base > 0 && $pos.index(base) === $pos.node(base).childCount - 1) base--;
170
- const after = $pos.node(base).maybeChild($pos.index(base) + 1);
208
+ const after = $pos.node($pos.depth - 1).maybeChild($pos.index($pos.depth - 1) + 1);
171
209
  if (!after) return false;
172
- const boundary = $pos.after(base + 1);
173
- if (after.isTextblock && base === $pos.depth - 1) {
174
- return attempt(state, dispatch, (tr) => tr.join(boundary));
175
- }
176
- if (after.isLeaf) {
177
- return attempt(state, dispatch, (tr) => tr.delete(boundary, boundary + after.nodeSize));
178
- }
179
- // Before a container (a list): its first textblock joins this one; the containers it leaves
180
- // empty go too (a list item, a list). Not when its container must keep it (a list item that
181
- // goes on with a nested list): that needs a lift first.
182
- let levels = 1;
183
- let target: Node | null = after;
184
- while (target && !target.isTextblock && !target.isLeaf) {
185
- target = target.firstChild;
186
- levels++;
210
+ const boundary = $pos.after();
211
+ if (after.isTextblock) {
212
+ return attempt(state, dispatch, (tr) => {
213
+ tr.join(boundary);
214
+ keepLastMark(tr, $pos.before(), after);
215
+ });
187
216
  }
188
- if (!target?.isTextblock) return false;
189
- const $target = state.doc.resolve(boundary + levels);
190
- let depth = $target.depth;
191
- while (depth > base + 1) {
192
- const holder = $target.node(depth - 1);
193
- const at = $target.index(depth - 1);
194
- if (holder.canReplace(at, at + 1)) break;
195
- if (holder.childCount !== 1) return false;
196
- depth--;
217
+ if (after.isLeaf && isOpaque(wordContext(state), after)) {
218
+ dispatch?.(state.tr.setSelection(selectionAt(state, boundary)));
219
+ return true;
197
220
  }
198
- const from = $target.before(depth);
199
- const to = $target.after(depth);
200
- const content = target.content;
201
- return attempt(state, dispatch, (tr) => {
202
- tr.delete(from, to);
203
- tr.insert($pos.pos, content);
204
- tr.setSelection(TextSelection.create(tr.doc, $pos.pos));
205
- });
221
+ return false;
206
222
  };
207
223
 
208
224
  /**
@@ -225,8 +241,16 @@ export const splitBlock: Command = (state, dispatch) => {
225
241
  tr.deleteSelection();
226
242
  const $pos = tr.selection.$from;
227
243
  const atEnd = $pos.parentOffset === $pos.parent.content.size;
228
- const normal = defaultTextblockType(state.schema);
229
- tr.split($pos.pos, 1, atEnd && $pos.parent.type !== normal ? [{ type: normal }] : undefined);
244
+ const word = wordContext(state);
245
+ if (word && $pos.parent.type.name === "paragraph") {
246
+ // Word: the first paragraph gets a new mark, the second keeps the original one.
247
+ const { before, after } = splitAttrs(word, $pos.parent, atEnd);
248
+ tr.split($pos.pos, 1, [{ type: $pos.parent.type, attrs: after }]);
249
+ if (before) tr.setNodeMarkup($pos.before(), $pos.parent.type, before);
250
+ } else {
251
+ const normal = defaultTextblockType(state.schema);
252
+ tr.split($pos.pos, 1, atEnd && $pos.parent.type !== normal ? [{ type: normal }] : undefined);
253
+ }
230
254
  tr.setSelection(TextSelection.create(tr.doc, $pos.pos + 2));
231
255
  if (marks.length) tr.setStoredMarks(marks);
232
256
  });
@@ -315,6 +339,9 @@ export function arrowAcrossLeaf(dir: -1 | 1, from: "char" | "line" | "none"): Co
315
339
  };
316
340
  }
317
341
 
342
+ /** Inserts a tab (schema v3) in place of the selection; does not apply where there is none. */
343
+ export const insertTab: Command = (state, dispatch) => insertLeaf("tab", state, dispatch);
344
+
318
345
  /** Inserts a hard break (a line break inside the block) in place of the selection. */
319
346
  export const insertHardBreak: Command = (state, dispatch) =>
320
347
  insertLeaf("hardBreak", state, dispatch);
@@ -339,7 +366,7 @@ function insertLeaf(name: string, ...[state, dispatch]: Parameters<Command>): bo
339
366
  type.create(
340
367
  null,
341
368
  null,
342
- marks.filter((m) => tr.doc.resolve(pos).parent.type.allowsMarkType(m.type)),
369
+ typedMarks(marks).filter((m) => tr.doc.resolve(pos).parent.type.allowsMarkType(m.type)),
343
370
  ),
344
371
  );
345
372
  tr.setSelection(TextSelection.create(tr.doc, pos + 1));
@@ -381,6 +408,11 @@ export function toggleMark(type: string | MarkType, attrs?: Attrs | null): Comma
381
408
  if ($caret) {
382
409
  if (!$caret.parent.type.allowsMarkType(mark)) return false;
383
410
  const marks = state.storedMarks ?? marksAt($caret);
411
+ const word = wordContext(state);
412
+ if (word && isWordToggle(word, mark)) {
413
+ dispatch?.(state.tr.setStoredMarks(toggledCaretMarks(word, $caret.parent, marks, mark)));
414
+ return true;
415
+ }
384
416
  const existing = mark.isInSet(marks);
385
417
  const created = existing ? null : createMark(mark, attrs);
386
418
  if (!existing && !created) return false;
@@ -397,6 +429,16 @@ export function toggleMark(type: string | MarkType, attrs?: Attrs | null): Comma
397
429
  return !applicable;
398
430
  });
399
431
  if (!applicable) return false;
432
+ const word = wordContext(state);
433
+ if (word && isWordToggle(word, mark)) {
434
+ const on = !wordToggleActive(word, state, mark, null);
435
+ return attempt(state, dispatch, (tr) => {
436
+ for (const range of toggleRanges(word, state, selection.from, selection.to, mark, on)) {
437
+ tr.removeMark(range.from, range.to, mark);
438
+ if (range.mark) tr.addMark(range.from, range.to, range.mark);
439
+ }
440
+ });
441
+ }
400
442
  const remove = rangeHasMark(state, selection.from, selection.to, mark);
401
443
  const created = remove ? null : createMark(mark, attrs);
402
444
  if (!remove && !created) return false;
@@ -409,6 +451,8 @@ export function toggleMark(type: string | MarkType, attrs?: Attrs | null): Comma
409
451
 
410
452
  /** The mark, or null when `attrs` are invalid for it (e.g. a link with an unsafe href). */
411
453
  function createMark(type: MarkType, attrs?: Attrs | null): Mark | null {
454
+ // Schema v3 keeps any link target a file has (`file:`…); a command adds only safe ones.
455
+ if (type.name === "link" && !isSafeLink(attrs)) return null;
412
456
  try {
413
457
  return type.create(attrs);
414
458
  } catch (error) {
@@ -422,21 +466,31 @@ export function isMarkActive(state: EditorState, type: string | MarkType): boole
422
466
  const mark = markType(state, type);
423
467
  if (!mark) return false;
424
468
  const $caret = caret(state);
469
+ const word = wordContext(state);
470
+ if (word && isWordToggle(word, mark))
471
+ return wordToggleActive(
472
+ word,
473
+ state,
474
+ mark,
475
+ $caret ? (state.storedMarks ?? marksAt($caret)) : null,
476
+ );
425
477
  if ($caret) return mark.isInSet(state.storedMarks ?? marksAt($caret)) !== undefined;
426
478
  return rangeHasMark(state, state.selection.from, state.selection.to, mark);
427
479
  }
428
480
 
429
481
  /**
430
- * Changes the textblocks in the selection to `type` (e.g. heading level 2, or paragraph),
431
- * keeping attributes both types have (alignment). Does not apply when nothing would change.
482
+ * Gives the selected paragraphs a block type as Word does: `heading` (with its `level`) is
483
+ * Word's heading style of that level, `paragraph` the document's default paragraph style.
432
484
  */
433
485
  export function setBlockType(type: string | NodeType, attrs: Attrs | null = null): Command {
434
486
  return (state, dispatch) => {
435
- const nodeType = typeof type === "string" ? state.schema.nodes[type] : type;
436
- if (!nodeType?.isTextblock) return false;
437
- const { from, to } = state.selection;
438
- // A transaction with no step (every block already like that) does not apply.
439
- return attempt(state, dispatch, (tr) => tr.setBlockType(from, to, nodeType, attrs));
487
+ const word = wordContext(state);
488
+ if (!word) return false;
489
+ const name = typeof type === "string" ? type : type.name;
490
+ if (name === "heading")
491
+ return setStyleNamed(`heading ${String(attrs?.level ?? 1)}`)(state, dispatch);
492
+ const style = name === "paragraph" ? defaultParagraphStyleOf(word) : null;
493
+ return style !== null && setParagraphStyle(style)(state, dispatch);
440
494
  };
441
495
  }
442
496
 
@@ -451,6 +505,8 @@ export function baseKeymap(): Plugin {
451
505
  Enter: splitBlock,
452
506
  "Shift-Enter": insertHardBreak,
453
507
  "Mod-Enter": insertPageBreak,
508
+ // Types a tab (a list's Tab runs first); Escape then Tab leaves the editor (the view).
509
+ Tab: insertTab,
454
510
  Backspace: deleteBackward(),
455
511
  Delete: deleteForward(),
456
512
  "Mod-b": toggleMark("bold"),
@@ -1,12 +1,14 @@
1
+ import type { DocumentSettings, FoliDocumentV2 } from "../document.js";
2
+ import type { Attrs, Node } from "../model/index.js";
3
+ import type { Alignment } from "../schema.js";
1
4
  import {
2
5
  createDocument,
3
- type DocumentSettings,
4
6
  type FoliDocument,
5
7
  parseContent,
6
- SCHEMA_VERSION,
7
- } from "../document.js";
8
- import type { Attrs } from "../model/index.js";
9
- import type { Alignment, DocJSON } from "../schema.js";
8
+ parseDocument,
9
+ type SectionJSON,
10
+ } from "../v3/document.js";
11
+ import { twipsToMm as mm } from "../v3/units.js";
10
12
  import {
11
13
  baseKeymap,
12
14
  type DeleteUnit,
@@ -24,16 +26,24 @@ import {
24
26
  splitBlock,
25
27
  toggleMark,
26
28
  } from "./commands.js";
27
- import { insertHorizontalRule, setAlign, setHighlight, setTextColor } from "./format.js";
29
+ import { setAlign, setHighlight, setTextColor } from "./format.js";
28
30
  import { history, redo, undo } from "./history.js";
29
31
  import { removeLink, setLink } from "./links.js";
30
32
  import { liftListItem, listKeymap, sinkListItem, toggleList, wrapInList } from "./lists.js";
31
33
  import { TextSelection } from "./selection.js";
32
34
  import { type Command, EditorState, type Plugin, type Transaction } from "./state.js";
35
+ import { type WordEnvelope, wordContext, wordPlugin } from "./word.js";
36
+ import type { ListKind } from "./wordformat.js";
37
+
38
+ /**
39
+ * A document an editor loads: schema v3 (Word's model), or one saved by 0.1.0 or 0.2.0, migrated
40
+ * to v3 when loaded (`parseDocument`).
41
+ */
42
+ export type EditorDocument = FoliDocument | FoliDocumentV2;
33
43
 
34
44
  export interface EditorOptions {
35
- /** Trusted or not, it is validated (`parseContent`) before use. Defaults to an empty document. */
36
- document?: FoliDocument;
45
+ /** Trusted or not, it is validated (and migrated: `parseDocument`). Default: an empty one. */
46
+ document?: EditorDocument;
37
47
  /** Run before the built-in plugins, so their keymaps take precedence. */
38
48
  plugins?: readonly Plugin[];
39
49
  }
@@ -43,7 +53,10 @@ export type EditorListener = (state: EditorState, transactions: readonly Transac
43
53
  /** A headless editor: state, commands, history and change notifications, no DOM. */
44
54
  export interface Editor {
45
55
  readonly state: EditorState;
46
- /** Page size and margins of the current document. */
56
+ /**
57
+ * Page size and margins of the current document. For a schema v3 document, its last
58
+ * section's (the view lays each section out with its own).
59
+ */
47
60
  readonly settings: DocumentSettings;
48
61
  dispatch(tr: Transaction): void;
49
62
  /** Runs a command; returns whether it applied. */
@@ -69,13 +82,13 @@ export interface Editor {
69
82
  selectAll(): boolean;
70
83
  undo(): boolean;
71
84
  redo(): boolean;
72
- /** Wraps the selected blocks in a list ("bulletList" or "orderedList"). */
73
- wrapInList(type: string, attrs?: Attrs | null): boolean;
74
- /** The list buttons: removes the list, changes its type, or wraps in a new one. */
75
- toggleList(type: string, attrs?: Attrs | null): boolean;
76
- /** Tab in a list: nests the selected items in the item before them. */
85
+ /** Numbers the selected paragraphs as a list ("bulletList" or "orderedList"). */
86
+ wrapInList(kind: ListKind): boolean;
87
+ /** The list buttons: removes the selection's numbering when it is a list of `kind`, else numbers it. */
88
+ toggleList(kind: ListKind): boolean;
89
+ /** Tab in a list: one level deeper. */
77
90
  indentListItem(): boolean;
78
- /** Shift+Tab in a list: lifts the selected items one level (out of the list at the top). */
91
+ /** Shift+Tab in a list: one level up (out of the list at the top). */
79
92
  outdentListItem(): boolean;
80
93
  /**
81
94
  * Links the selection to `href` (normalized, then validated: unsafe hrefs do not apply); at
@@ -90,24 +103,60 @@ export interface Editor {
90
103
  setTextColor(color: string | null): boolean;
91
104
  /** Highlight (`#rrggbb`) of the selected or next typed text; null removes it. */
92
105
  setHighlight(color: string | null): boolean;
93
- /** Inserts a horizontal rule at the selection (the caret goes to the text after it). */
94
- insertHorizontalRule(): boolean;
95
106
  };
96
107
  isMarkActive(type: string): boolean;
97
- /** The current document as a persisted FoliDocument. */
108
+ /** The current document (schema v3). */
98
109
  getDocument(): FoliDocument;
99
- /** Replaces the whole document and resets history. */
100
- setDocument(document: FoliDocument): void;
110
+ /** Replaces the whole document (an older one migrated) and resets history. */
111
+ setDocument(document: EditorDocument): void;
101
112
  subscribe(listener: EditorListener): () => void;
102
113
  }
103
114
 
115
+ /** Word's page when a section leaves it out: Letter, 1 inch margins. */
116
+ const LETTER = { width: 12240, height: 15840, margin: 1440 };
117
+
118
+ /** A section's page setup as page settings (mm; the gutter added to the left margin, as Word does). */
119
+ export function sectionSettings(section: SectionJSON): DocumentSettings {
120
+ const m = section.margins ?? {};
121
+ return {
122
+ pageSize: {
123
+ width: mm(section.pageSize?.width ?? LETTER.width),
124
+ height: mm(section.pageSize?.height ?? LETTER.height),
125
+ },
126
+ margins: {
127
+ top: mm(Math.abs(m.top ?? LETTER.margin)),
128
+ right: mm(m.right ?? LETTER.margin),
129
+ bottom: mm(Math.abs(m.bottom ?? LETTER.margin)),
130
+ left: mm((m.left ?? LETTER.margin) + (m.gutter ?? 0)),
131
+ },
132
+ };
133
+ }
134
+
135
+ interface Loaded {
136
+ doc: Node;
137
+ settings: DocumentSettings;
138
+ envelope: WordEnvelope;
139
+ }
140
+
141
+ /** Validates (and migrates) a document and reads what the editor keeps of it. */
142
+ function load(document: EditorDocument): Loaded {
143
+ const { content, ...envelope } = parseDocument(document);
144
+ return { doc: parseContent(content), settings: sectionSettings(envelope.section), envelope };
145
+ }
146
+
104
147
  export function createEditor({
105
148
  document = createDocument(),
106
149
  plugins = [],
107
150
  }: EditorOptions = {}): Editor {
108
- let settings = document.settings;
109
- const allPlugins = [...plugins, history(), listKeymap(), baseKeymap()];
110
- let state = EditorState.create({ doc: parseContent(document.content), plugins: allPlugins });
151
+ let loaded = load(document);
152
+ const pluginsFor = ({ envelope }: Loaded) => [
153
+ ...plugins,
154
+ history(),
155
+ wordPlugin(envelope),
156
+ listKeymap(),
157
+ baseKeymap(),
158
+ ];
159
+ let state = EditorState.create({ doc: loaded.doc, plugins: pluginsFor(loaded) });
111
160
  const listeners = new Set<EditorListener>();
112
161
 
113
162
  const notify = (transactions: readonly Transaction[]) => {
@@ -122,7 +171,7 @@ export function createEditor({
122
171
 
123
172
  return {
124
173
  get settings() {
125
- return settings;
174
+ return loaded.settings;
126
175
  },
127
176
  get state() {
128
177
  return state;
@@ -156,27 +205,24 @@ export function createEditor({
156
205
  selectAll: () => run(selectAll),
157
206
  undo: () => run(undo),
158
207
  redo: () => run(redo),
159
- wrapInList: (type, attrs) => run(wrapInList(type, attrs)),
160
- toggleList: (type, attrs) => run(toggleList(type, attrs)),
161
- indentListItem: () => run(sinkListItem()),
162
- outdentListItem: () => run(liftListItem()),
208
+ wrapInList: (kind) => run(wrapInList(kind)),
209
+ toggleList: (kind) => run(toggleList(kind)),
210
+ indentListItem: () => run(sinkListItem),
211
+ outdentListItem: () => run(liftListItem),
163
212
  setLink: (href) => run(setLink(href)),
164
213
  removeLink: () => run(removeLink),
165
214
  setAlign: (align) => run(setAlign(align)),
166
215
  setTextColor: (color) => run(setTextColor(color)),
167
216
  setHighlight: (color) => run(setHighlight(color)),
168
- insertHorizontalRule: () => run(insertHorizontalRule),
169
217
  },
170
218
  isMarkActive: (type) => isMarkActive(state, type),
171
219
  getDocument: () => ({
172
- schemaVersion: SCHEMA_VERSION,
173
- settings,
174
- content: state.doc.toJSON() as DocJSON,
220
+ ...structuredClone(wordContext(state)?.envelope ?? loaded.envelope),
221
+ content: state.doc.toJSON(),
175
222
  }),
176
223
  setDocument(next) {
177
- const doc = parseContent(next.content);
178
- settings = next.settings;
179
- state = EditorState.create({ doc, plugins: allPlugins });
224
+ loaded = load(next);
225
+ state = EditorState.create({ doc: loaded.doc, plugins: pluginsFor(loaded) });
180
226
  notify([]);
181
227
  },
182
228
  subscribe(listener) {