@folijs/core 0.1.0 → 0.2.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 (133) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/document.d.ts +5 -4
  3. package/dist/document.d.ts.map +1 -1
  4. package/dist/document.js +30 -8
  5. package/dist/document.js.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/model/attrs.d.ts +5 -0
  11. package/dist/model/attrs.d.ts.map +1 -1
  12. package/dist/model/attrs.js +17 -0
  13. package/dist/model/attrs.js.map +1 -1
  14. package/dist/model/content.d.ts +10 -0
  15. package/dist/model/content.d.ts.map +1 -1
  16. package/dist/model/content.js +44 -0
  17. package/dist/model/content.js.map +1 -1
  18. package/dist/model/fragment.d.ts +2 -0
  19. package/dist/model/fragment.d.ts.map +1 -1
  20. package/dist/model/fragment.js +8 -0
  21. package/dist/model/fragment.js.map +1 -1
  22. package/dist/model/index.d.ts +1 -1
  23. package/dist/model/index.d.ts.map +1 -1
  24. package/dist/model/index.js +1 -1
  25. package/dist/model/index.js.map +1 -1
  26. package/dist/model/mark.d.ts.map +1 -1
  27. package/dist/model/mark.js +4 -3
  28. package/dist/model/mark.js.map +1 -1
  29. package/dist/model/node.d.ts +12 -0
  30. package/dist/model/node.d.ts.map +1 -1
  31. package/dist/model/node.js +35 -3
  32. package/dist/model/node.js.map +1 -1
  33. package/dist/model/resolvedpos.d.ts +26 -2
  34. package/dist/model/resolvedpos.d.ts.map +1 -1
  35. package/dist/model/resolvedpos.js +54 -2
  36. package/dist/model/resolvedpos.js.map +1 -1
  37. package/dist/model/schema.d.ts +25 -0
  38. package/dist/model/schema.d.ts.map +1 -1
  39. package/dist/model/schema.js +23 -0
  40. package/dist/model/schema.js.map +1 -1
  41. package/dist/model/slice.d.ts +7 -0
  42. package/dist/model/slice.d.ts.map +1 -1
  43. package/dist/model/slice.js +53 -0
  44. package/dist/model/slice.js.map +1 -1
  45. package/dist/schema.d.ts +62 -7
  46. package/dist/schema.d.ts.map +1 -1
  47. package/dist/schema.js +82 -8
  48. package/dist/schema.js.map +1 -1
  49. package/dist/state/attempt.d.ts +4 -0
  50. package/dist/state/attempt.d.ts.map +1 -0
  51. package/dist/state/attempt.js +19 -0
  52. package/dist/state/attempt.js.map +1 -0
  53. package/dist/state/commands.d.ts +18 -3
  54. package/dist/state/commands.d.ts.map +1 -1
  55. package/dist/state/commands.js +199 -44
  56. package/dist/state/commands.js.map +1 -1
  57. package/dist/state/editor.d.ts +24 -0
  58. package/dist/state/editor.d.ts.map +1 -1
  59. package/dist/state/editor.js +14 -1
  60. package/dist/state/editor.js.map +1 -1
  61. package/dist/state/format.d.ts +27 -0
  62. package/dist/state/format.d.ts.map +1 -0
  63. package/dist/state/format.js +144 -0
  64. package/dist/state/format.js.map +1 -0
  65. package/dist/state/history.js +2 -2
  66. package/dist/state/history.js.map +1 -1
  67. package/dist/state/index.d.ts +5 -2
  68. package/dist/state/index.d.ts.map +1 -1
  69. package/dist/state/index.js +5 -2
  70. package/dist/state/index.js.map +1 -1
  71. package/dist/state/links.d.ts +42 -0
  72. package/dist/state/links.d.ts.map +1 -0
  73. package/dist/state/links.js +186 -0
  74. package/dist/state/links.js.map +1 -0
  75. package/dist/state/lists.d.ts +36 -0
  76. package/dist/state/lists.d.ts.map +1 -0
  77. package/dist/state/lists.js +383 -0
  78. package/dist/state/lists.js.map +1 -0
  79. package/dist/state/selection.d.ts +18 -2
  80. package/dist/state/selection.d.ts.map +1 -1
  81. package/dist/state/selection.js +63 -2
  82. package/dist/state/selection.js.map +1 -1
  83. package/dist/state/state.d.ts.map +1 -1
  84. package/dist/state/state.js +12 -2
  85. package/dist/state/state.js.map +1 -1
  86. package/dist/transform/index.d.ts +2 -1
  87. package/dist/transform/index.d.ts.map +1 -1
  88. package/dist/transform/index.js +2 -1
  89. package/dist/transform/index.js.map +1 -1
  90. package/dist/transform/stepmap.d.ts +8 -6
  91. package/dist/transform/stepmap.d.ts.map +1 -1
  92. package/dist/transform/stepmap.js +18 -15
  93. package/dist/transform/stepmap.js.map +1 -1
  94. package/dist/transform/steps.d.ts +27 -2
  95. package/dist/transform/steps.d.ts.map +1 -1
  96. package/dist/transform/steps.js +115 -4
  97. package/dist/transform/steps.js.map +1 -1
  98. package/dist/transform/structure.d.ts +26 -0
  99. package/dist/transform/structure.d.ts.map +1 -0
  100. package/dist/transform/structure.js +116 -0
  101. package/dist/transform/structure.js.map +1 -0
  102. package/dist/transform/transform.d.ts +34 -11
  103. package/dist/transform/transform.d.ts.map +1 -1
  104. package/dist/transform/transform.js +145 -18
  105. package/dist/transform/transform.js.map +1 -1
  106. package/package.json +1 -1
  107. package/src/document.ts +34 -8
  108. package/src/index.ts +14 -0
  109. package/src/model/attrs.ts +19 -0
  110. package/src/model/content.ts +56 -0
  111. package/src/model/fragment.ts +7 -0
  112. package/src/model/index.ts +1 -1
  113. package/src/model/mark.ts +3 -2
  114. package/src/model/node.ts +42 -2
  115. package/src/model/resolvedpos.ts +55 -2
  116. package/src/model/schema.ts +43 -0
  117. package/src/model/slice.ts +81 -1
  118. package/src/schema.ts +135 -12
  119. package/src/state/attempt.ts +22 -0
  120. package/src/state/commands.ts +209 -47
  121. package/src/state/editor.ts +38 -2
  122. package/src/state/format.ts +133 -0
  123. package/src/state/history.ts +3 -3
  124. package/src/state/index.ts +31 -0
  125. package/src/state/links.ts +185 -0
  126. package/src/state/lists.ts +427 -0
  127. package/src/state/selection.ts +72 -3
  128. package/src/state/state.ts +11 -2
  129. package/src/transform/index.ts +8 -0
  130. package/src/transform/stepmap.ts +18 -12
  131. package/src/transform/steps.ts +126 -3
  132. package/src/transform/structure.ts +135 -0
  133. package/src/transform/transform.ts +165 -16
@@ -1,8 +1,18 @@
1
- import { deepEqual } from "../model/attrs.js";
2
- import type { Attrs, MarkType, NodeType, ResolvedPos } from "../model/index.js";
3
- import { TransformError } from "../transform/transform.js";
1
+ import {
2
+ type Attrs,
3
+ FoliDocumentError,
4
+ Fragment,
5
+ type Mark,
6
+ type MarkType,
7
+ type Node,
8
+ type NodeType,
9
+ type ResolvedPos,
10
+ Slice,
11
+ } from "../model/index.js";
12
+ import { attempt } from "./attempt.js";
4
13
  import { redo, undo } from "./history.js";
5
- import { AllSelection, marksAt, TextSelection } from "./selection.js";
14
+ import { openLinkEditor } from "./links.js";
15
+ import { AllSelection, marksAt, NodeSelection, Selection, TextSelection } from "./selection.js";
6
16
  import {
7
17
  type Command,
8
18
  defaultTextblockType,
@@ -21,26 +31,6 @@ const LEAF = "\n";
21
31
  const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
22
32
  const words = new Intl.Segmenter(undefined, { granularity: "word" });
23
33
 
24
- /** Runs `build`; a TransformError means the command does not apply. */
25
- function attempt(
26
- state: EditorState,
27
- dispatch: ((tr: Transaction) => void) | undefined,
28
- build: (tr: Transaction) => void,
29
- ): boolean {
30
- const tr = state.tr;
31
- try {
32
- build(tr);
33
- } catch (error) {
34
- if (error instanceof TransformError) return false;
35
- throw error;
36
- }
37
- if (!tr.docChanged && tr.selection.eq(state.selection) && tr.storedMarks === state.storedMarks) {
38
- return false;
39
- }
40
- dispatch?.(tr);
41
- return true;
42
- }
43
-
44
34
  function caret(state: EditorState): ResolvedPos | null {
45
35
  const { selection } = state;
46
36
  return selection.empty && selection instanceof TextSelection ? selection.$head : null;
@@ -56,6 +46,14 @@ export function insertText(text: string): Command {
56
46
  return (state, dispatch) => {
57
47
  if (!text) return false;
58
48
  const { selection } = state;
49
+ if (selectedBlock(state)) {
50
+ // Typing over a selected block (a rule) replaces it with a paragraph of the text.
51
+ return replaceSelectedBlock(
52
+ state,
53
+ dispatch,
54
+ state.schema.text(text, state.storedMarks ?? []),
55
+ );
56
+ }
59
57
  if (!(selection instanceof AllSelection) && !selection.$from.parent.inlineContent) return false;
60
58
  return attempt(state, dispatch, (tr) => {
61
59
  const $from = selection.$from;
@@ -131,22 +129,80 @@ export const joinBackward: Command = (state, dispatch) => {
131
129
  if (before.isTextblock) return attempt(state, dispatch, (tr) => tr.join(boundary));
132
130
  if (before.isLeaf)
133
131
  return attempt(state, dispatch, (tr) => tr.delete(boundary - before.nodeSize, boundary));
134
- return false;
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));
144
+ }
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
+ });
135
156
  };
136
157
 
137
- /** At the end of a textblock: merges the next textblock into it, or deletes a next leaf block. */
158
+ /**
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.
161
+ */
138
162
  export const joinForward: Command = (state, dispatch) => {
139
163
  const $pos = caret(state);
140
164
  if (!$pos?.parent.isTextblock || $pos.parentOffset < $pos.parent.content.size || $pos.depth < 1) {
141
165
  return false;
142
166
  }
143
- const parent = $pos.node($pos.depth - 1);
144
- const after = parent.maybeChild($pos.index($pos.depth - 1) + 1);
145
- const boundary = $pos.after();
146
- if (after?.isTextblock) return attempt(state, dispatch, (tr) => tr.join(boundary));
147
- if (after?.isLeaf)
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);
171
+ 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) {
148
177
  return attempt(state, dispatch, (tr) => tr.delete(boundary, boundary + after.nodeSize));
149
- return false;
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++;
187
+ }
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--;
197
+ }
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
+ });
150
206
  };
151
207
 
152
208
  /**
@@ -155,6 +211,14 @@ export const joinForward: Command = (state, dispatch) => {
155
211
  */
156
212
  export const splitBlock: Command = (state, dispatch) => {
157
213
  const { selection } = state;
214
+ const block = selectedBlock(state);
215
+ if (block) {
216
+ // Enter on a selected block (a rule): a new paragraph after it.
217
+ return attempt(state, dispatch, (tr) => {
218
+ tr.insert(selection.to, defaultTextblockType(state.schema).create());
219
+ tr.setSelection(TextSelection.create(tr.doc, selection.to + 1));
220
+ });
221
+ }
158
222
  if (!(selection instanceof AllSelection) && !selection.$from.parent.isTextblock) return false;
159
223
  return attempt(state, dispatch, (tr) => {
160
224
  const marks = state.storedMarks ?? marksAt(selection.$from);
@@ -162,12 +226,95 @@ export const splitBlock: Command = (state, dispatch) => {
162
226
  const $pos = tr.selection.$from;
163
227
  const atEnd = $pos.parentOffset === $pos.parent.content.size;
164
228
  const normal = defaultTextblockType(state.schema);
165
- tr.split($pos.pos, atEnd && $pos.parent.type !== normal ? { type: normal } : undefined);
229
+ tr.split($pos.pos, 1, atEnd && $pos.parent.type !== normal ? [{ type: normal }] : undefined);
166
230
  tr.setSelection(TextSelection.create(tr.doc, $pos.pos + 2));
167
231
  if (marks.length) tr.setStoredMarks(marks);
168
232
  });
169
233
  };
170
234
 
235
+ /** The selected block node (a rule), when the selection is a node selection of a block. */
236
+ function selectedBlock(state: EditorState): Node | null {
237
+ const { selection } = state;
238
+ return selection instanceof NodeSelection && selection.node.isBlock ? selection.node : null;
239
+ }
240
+
241
+ /** Replaces the selected block with a default textblock holding `content` (caret at its end). */
242
+ function replaceSelectedBlock(
243
+ state: EditorState,
244
+ dispatch: ((tr: Transaction) => void) | undefined,
245
+ content: Node,
246
+ ): boolean {
247
+ const { from, to } = state.selection;
248
+ const block = defaultTextblockType(state.schema).create(null, content);
249
+ return attempt(state, dispatch, (tr) => {
250
+ tr.replace(from, to, new Slice(Fragment.from(block), 0, 0));
251
+ tr.setSelection(TextSelection.create(tr.doc, from + 1 + content.nodeSize));
252
+ });
253
+ }
254
+
255
+ /**
256
+ * The leaf block or textblock next to `pos` (a position between blocks) in direction `dir`,
257
+ * through container boundaries (the rule ending the list item before), or null at the end.
258
+ */
259
+ function blockBeside(doc: Node, pos: number, dir: -1 | 1): { node: Node; pos: number } | null {
260
+ let $pos = doc.resolve(pos);
261
+ for (;;) {
262
+ let node = dir < 0 ? $pos.nodeBefore : $pos.nodeAfter;
263
+ if (node) {
264
+ let start = dir < 0 ? $pos.pos - node.nodeSize : $pos.pos;
265
+ while (!node.isTextblock && !node.isLeaf) {
266
+ const child: Node | null = dir < 0 ? node.lastChild : node.firstChild;
267
+ if (!child) return null;
268
+ start = dir < 0 ? start + node.nodeSize - 1 - child.nodeSize : start + 1;
269
+ node = child;
270
+ }
271
+ return { node, pos: start };
272
+ }
273
+ if ($pos.depth === 0) return null;
274
+ $pos = doc.resolve(dir < 0 ? $pos.before() : $pos.after());
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Arrow keys around a block leaf (a rule, which has no caret stop). From a selected leaf: to the
280
+ * text beside it (the end of the text before, the start of the text after), or the next leaf.
281
+ * From a caret: selects the leaf beside the caret's textblock, when the caret is at its edge
282
+ * (`"char"`: Left/Right at the textblock's first or last position) or the view found it on the
283
+ * first or last line (`"line"`: Up/Down). `"none"` only moves from a selected leaf. `dir` -1 is
284
+ * back (left, up), 1 forward.
285
+ */
286
+ export function arrowAcrossLeaf(dir: -1 | 1, from: "char" | "line" | "none"): Command {
287
+ return (state, dispatch) => {
288
+ const { selection, doc } = state;
289
+ if (selectedBlock(state)) {
290
+ const beside = blockBeside(doc, dir < 0 ? selection.from : selection.to, dir);
291
+ // At the document's edge: stay (a native arrow would leave a broken DOM range).
292
+ if (!beside) return true;
293
+ const next = beside.node.isTextblock
294
+ ? TextSelection.create(
295
+ doc,
296
+ dir < 0 ? beside.pos + beside.node.nodeSize - 1 : beside.pos + 1,
297
+ )
298
+ : NodeSelection.isSelectable(beside.node)
299
+ ? NodeSelection.create(doc, beside.pos)
300
+ : Selection.near(doc.resolve(beside.pos), dir);
301
+ dispatch?.(state.tr.setSelection(next));
302
+ return true;
303
+ }
304
+ if (from === "none" || !selection.empty || !(selection instanceof TextSelection)) return false;
305
+ const { $from } = selection;
306
+ if (!$from.parent.isTextblock || $from.depth < 1) return false;
307
+ const atEdge =
308
+ dir < 0 ? $from.parentOffset === 0 : $from.parentOffset === $from.parent.content.size;
309
+ if (from === "char" && !atEdge) return false;
310
+ const beside = blockBeside(doc, dir < 0 ? $from.before() : $from.after(), dir);
311
+ if (!beside || beside.node.isTextblock || !NodeSelection.isSelectable(beside.node))
312
+ return false;
313
+ dispatch?.(state.tr.setSelection(NodeSelection.create(doc, beside.pos)));
314
+ return true;
315
+ };
316
+ }
317
+
171
318
  /** Inserts a hard break (a line break inside the block) in place of the selection. */
172
319
  export const insertHardBreak: Command = (state, dispatch) =>
173
320
  insertLeaf("hardBreak", state, dispatch);
@@ -235,9 +382,11 @@ export function toggleMark(type: string | MarkType, attrs?: Attrs | null): Comma
235
382
  if (!$caret.parent.type.allowsMarkType(mark)) return false;
236
383
  const marks = state.storedMarks ?? marksAt($caret);
237
384
  const existing = mark.isInSet(marks);
385
+ const created = existing ? null : createMark(mark, attrs);
386
+ if (!existing && !created) return false;
238
387
  dispatch?.(
239
388
  state.tr.setStoredMarks(
240
- existing ? existing.removeFromSet(marks) : mark.create(attrs).addToSet(marks),
389
+ existing ? existing.removeFromSet(marks) : (created as Mark).addToSet(marks),
241
390
  ),
242
391
  );
243
392
  return true;
@@ -248,16 +397,26 @@ export function toggleMark(type: string | MarkType, attrs?: Attrs | null): Comma
248
397
  return !applicable;
249
398
  });
250
399
  if (!applicable) return false;
400
+ const remove = rangeHasMark(state, selection.from, selection.to, mark);
401
+ const created = remove ? null : createMark(mark, attrs);
402
+ if (!remove && !created) return false;
251
403
  return attempt(state, dispatch, (tr) => {
252
- if (rangeHasMark(state, selection.from, selection.to, mark)) {
253
- tr.removeMark(selection.from, selection.to, mark);
254
- } else {
255
- tr.addMark(selection.from, selection.to, mark.create(attrs));
256
- }
404
+ if (remove) tr.removeMark(selection.from, selection.to, mark);
405
+ else tr.addMark(selection.from, selection.to, created as Mark);
257
406
  });
258
407
  };
259
408
  }
260
409
 
410
+ /** The mark, or null when `attrs` are invalid for it (e.g. a link with an unsafe href). */
411
+ function createMark(type: MarkType, attrs?: Attrs | null): Mark | null {
412
+ try {
413
+ return type.create(attrs);
414
+ } catch (error) {
415
+ if (error instanceof FoliDocumentError) return null;
416
+ throw error;
417
+ }
418
+ }
419
+
261
420
  /** Whether the mark is active: in stored marks at a caret, or on all selected text. */
262
421
  export function isMarkActive(state: EditorState, type: string | MarkType): boolean {
263
422
  const mark = markType(state, type);
@@ -267,19 +426,16 @@ export function isMarkActive(state: EditorState, type: string | MarkType): boole
267
426
  return rangeHasMark(state, state.selection.from, state.selection.to, mark);
268
427
  }
269
428
 
270
- /** Changes the textblocks in the selection to `type` (e.g. heading level 2, or paragraph). */
429
+ /**
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.
432
+ */
271
433
  export function setBlockType(type: string | NodeType, attrs: Attrs | null = null): Command {
272
434
  return (state, dispatch) => {
273
435
  const nodeType = typeof type === "string" ? state.schema.nodes[type] : type;
274
436
  if (!nodeType?.isTextblock) return false;
275
437
  const { from, to } = state.selection;
276
- let changes = false;
277
- state.doc.nodesBetween(from, to, (node) => {
278
- if (node.isTextblock && (node.type !== nodeType || !deepEqual(node.attrs, attrs ?? {})))
279
- changes = true;
280
- return !node.isTextblock;
281
- });
282
- if (!changes) return false;
438
+ // A transaction with no step (every block already like that) does not apply.
283
439
  return attempt(state, dispatch, (tr) => tr.setBlockType(from, to, nodeType, attrs));
284
440
  };
285
441
  }
@@ -300,7 +456,13 @@ export function baseKeymap(): Plugin {
300
456
  "Mod-b": toggleMark("bold"),
301
457
  "Mod-i": toggleMark("italic"),
302
458
  "Mod-u": toggleMark("underline"),
459
+ "Mod-k": openLinkEditor,
303
460
  "Mod-a": selectAll,
461
+ // Up/Down from a caret need the view's line geometry: it runs arrowAcrossLeaf(dir, "line").
462
+ ArrowLeft: arrowAcrossLeaf(-1, "char"),
463
+ ArrowRight: arrowAcrossLeaf(1, "char"),
464
+ ArrowUp: arrowAcrossLeaf(-1, "none"),
465
+ ArrowDown: arrowAcrossLeaf(1, "none"),
304
466
  "Mod-z": undo,
305
467
  "Mod-Shift-z": redo,
306
468
  "Mod-y": redo,
@@ -6,7 +6,7 @@ import {
6
6
  SCHEMA_VERSION,
7
7
  } from "../document.js";
8
8
  import type { Attrs } from "../model/index.js";
9
- import type { DocJSON } from "../schema.js";
9
+ import type { Alignment, DocJSON } from "../schema.js";
10
10
  import {
11
11
  baseKeymap,
12
12
  type DeleteUnit,
@@ -24,7 +24,10 @@ import {
24
24
  splitBlock,
25
25
  toggleMark,
26
26
  } from "./commands.js";
27
+ import { insertHorizontalRule, setAlign, setHighlight, setTextColor } from "./format.js";
27
28
  import { history, redo, undo } from "./history.js";
29
+ import { removeLink, setLink } from "./links.js";
30
+ import { liftListItem, listKeymap, sinkListItem, toggleList, wrapInList } from "./lists.js";
28
31
  import { TextSelection } from "./selection.js";
29
32
  import { type Command, EditorState, type Plugin, type Transaction } from "./state.js";
30
33
 
@@ -66,6 +69,29 @@ export interface Editor {
66
69
  selectAll(): boolean;
67
70
  undo(): boolean;
68
71
  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. */
77
+ indentListItem(): boolean;
78
+ /** Shift+Tab in a list: lifts the selected items one level (out of the list at the top). */
79
+ outdentListItem(): boolean;
80
+ /**
81
+ * Links the selection to `href` (normalized, then validated: unsafe hrefs do not apply); at
82
+ * a caret in a link, changes it; elsewhere inserts the href as linked text.
83
+ */
84
+ setLink(href: string): boolean;
85
+ /** Removes the links in the selection, or the link around the caret. */
86
+ removeLink(): boolean;
87
+ /** Aligns the selected paragraphs and headings ("start", "center", "end", "justify"). */
88
+ setAlign(align: Alignment): boolean;
89
+ /** Text color (lowercase `#rrggbb`) of the selected or next typed text; null removes it. */
90
+ setTextColor(color: string | null): boolean;
91
+ /** Highlight (`#rrggbb`) of the selected or next typed text; null removes it. */
92
+ setHighlight(color: string | null): boolean;
93
+ /** Inserts a horizontal rule at the selection (the caret goes to the text after it). */
94
+ insertHorizontalRule(): boolean;
69
95
  };
70
96
  isMarkActive(type: string): boolean;
71
97
  /** The current document as a persisted FoliDocument. */
@@ -80,7 +106,7 @@ export function createEditor({
80
106
  plugins = [],
81
107
  }: EditorOptions = {}): Editor {
82
108
  let settings = document.settings;
83
- const allPlugins = [...plugins, history(), baseKeymap()];
109
+ const allPlugins = [...plugins, history(), listKeymap(), baseKeymap()];
84
110
  let state = EditorState.create({ doc: parseContent(document.content), plugins: allPlugins });
85
111
  const listeners = new Set<EditorListener>();
86
112
 
@@ -130,6 +156,16 @@ export function createEditor({
130
156
  selectAll: () => run(selectAll),
131
157
  undo: () => run(undo),
132
158
  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()),
163
+ setLink: (href) => run(setLink(href)),
164
+ removeLink: () => run(removeLink),
165
+ setAlign: (align) => run(setAlign(align)),
166
+ setTextColor: (color) => run(setTextColor(color)),
167
+ setHighlight: (color) => run(setHighlight(color)),
168
+ insertHorizontalRule: () => run(insertHorizontalRule),
133
169
  },
134
170
  isMarkActive: (type) => isMarkActive(state, type),
135
171
  getDocument: () => ({
@@ -0,0 +1,133 @@
1
+ import { Fragment, type MarkType, type Node, Slice } from "../model/index.js";
2
+ import { type Alignment, isColor } from "../schema.js";
3
+ import { TransformError } from "../transform/transform.js";
4
+ import { attempt } from "./attempt.js";
5
+ import { marksAt, NodeSelection, TextSelection } from "./selection.js";
6
+ import { type Command, defaultTextblockType, type EditorState } from "./state.js";
7
+
8
+ /** The alignment all textblocks in the selection share, or null (mixed, or no textblock). */
9
+ export function alignAt(state: EditorState): Alignment | null {
10
+ let align: Alignment | null | undefined;
11
+ const { from, to } = state.selection;
12
+ state.doc.nodesBetween(from, to, (node) => {
13
+ if (align === null) return false;
14
+ if (!node.isTextblock) return undefined;
15
+ const value = typeof node.attrs.align === "string" ? (node.attrs.align as Alignment) : null;
16
+ align = align === undefined || align === value ? value : null;
17
+ return false;
18
+ });
19
+ return align ?? null;
20
+ }
21
+
22
+ /**
23
+ * Aligns the textblocks in the selection (`start` is the default: it removes the alignment).
24
+ * An unknown value does not apply (the schema rejects it).
25
+ */
26
+ export function setAlign(align: Alignment): Command {
27
+ return (state, dispatch) => {
28
+ const { from, to } = state.selection;
29
+ return attempt(state, dispatch, (tr) => tr.setBlockAttrs(from, to, { align }));
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Colors the selected text with a color mark (`textColor`, `highlight`), replacing the one it
35
+ * has; `null` removes it. At a caret, sets the mark for the text typed next. Colors are
36
+ * lowercase `#rrggbb` (an uppercase one is lowered); others do not apply.
37
+ */
38
+ function setColorMark(name: string, color: string | null): Command {
39
+ return (state, dispatch) => {
40
+ const type: MarkType | undefined = state.schema.marks[name];
41
+ const value = color?.toLowerCase() ?? null;
42
+ if (!type || (value !== null && !isColor(value))) return false;
43
+ const mark = value === null ? null : type.create({ color: value });
44
+ const { selection } = state;
45
+ if (selection.empty && selection instanceof TextSelection) {
46
+ const { $from } = selection;
47
+ if (!$from.parent.type.allowsMarkType(type)) return false;
48
+ const marks = state.storedMarks ?? marksAt($from);
49
+ const next = mark ? mark.addToSet(marks) : type.removeFromSet(marks);
50
+ if (next === marks) return false;
51
+ dispatch?.(state.tr.setStoredMarks(next));
52
+ return true;
53
+ }
54
+ const { from, to } = selection;
55
+ return attempt(state, dispatch, (tr) => {
56
+ if (mark) tr.addMark(from, to, mark);
57
+ else tr.removeMark(from, to, type);
58
+ });
59
+ };
60
+ }
61
+
62
+ /** Text color (`#rrggbb`) for the selected or next typed text; `null` removes it. */
63
+ export const setTextColor = (color: string | null): Command => setColorMark("textColor", color);
64
+
65
+ /** Highlight (background color, `#rrggbb`) for the selected or next typed text; `null` removes it. */
66
+ export const setHighlight = (color: string | null): Command => setColorMark("highlight", color);
67
+
68
+ /**
69
+ * The color of `name` (`textColor`, `highlight`) at the selection: the one all selected text
70
+ * has (at a caret, the one typing gets), or null (none, or mixed).
71
+ */
72
+ export function colorAt(state: EditorState, name: "textColor" | "highlight"): string | null {
73
+ const type = state.schema.marks[name];
74
+ if (!type) return null;
75
+ const read = (marks: Parameters<MarkType["isInSet"]>[0]) =>
76
+ (type.isInSet(marks)?.attrs.color as string | undefined) ?? null;
77
+ const { selection } = state;
78
+ if (selection.empty) return read(state.storedMarks ?? marksAt(selection.$from));
79
+ let color: string | null | undefined;
80
+ state.doc.nodesBetween(selection.from, selection.to, (node, _pos, parent) => {
81
+ if (color === null) return false;
82
+ if (!node.isInline || !parent?.type.allowsMarkType(type)) return undefined;
83
+ const value = read(node.marks);
84
+ color = color === undefined || color === value ? value : null;
85
+ return false;
86
+ });
87
+ return color ?? null;
88
+ }
89
+
90
+ /**
91
+ * Inserts a horizontal rule at the selection: at the start of a textblock, before it; at its
92
+ * end, after it, with a new empty paragraph for the caret; inside it, splitting it. Where a
93
+ * rule cannot go before the textblock (a list item's first paragraph), an empty one is treated
94
+ * as its end and a non-empty one is split at its start. With a block selected (a rule), after
95
+ * that block. The caret goes to the text after the rule, keeping the marks typing had.
96
+ */
97
+ export const insertHorizontalRule: Command = (state, dispatch) => {
98
+ const rule = state.schema.nodes.horizontalRule;
99
+ if (!rule) return false;
100
+ const paragraph = defaultTextblockType(state.schema);
101
+ const { selection } = state;
102
+ return attempt(state, dispatch, (tr) => {
103
+ const marks = state.storedMarks ?? marksAt(selection.$from);
104
+ let at: number;
105
+ let newParagraph: boolean;
106
+ if (selection instanceof NodeSelection && selection.node.isBlock) {
107
+ at = selection.to;
108
+ newParagraph = !tr.doc.resolve(at).nodeAfter?.isTextblock;
109
+ } else {
110
+ tr.deleteSelection();
111
+ const $pos = tr.selection.$from;
112
+ if (!$pos.parent.isTextblock) throw new TransformError("No rule here");
113
+ const index = $pos.index(-1);
114
+ const before = $pos.node(-1).canReplaceWith(index, index, rule);
115
+ if ($pos.parentOffset === 0 && before) {
116
+ at = $pos.before();
117
+ newParagraph = false;
118
+ } else if ($pos.parentOffset === $pos.parent.content.size) {
119
+ at = $pos.after();
120
+ newParagraph = true;
121
+ } else {
122
+ tr.split($pos.pos);
123
+ at = $pos.pos + 1;
124
+ newParagraph = false;
125
+ }
126
+ }
127
+ const content: Node[] = [rule.create()];
128
+ if (newParagraph) content.push(paragraph.create());
129
+ tr.replace(at, at, new Slice(Fragment.from(content), 0, 0));
130
+ tr.setSelection(TextSelection.create(tr.doc, at + 2));
131
+ if (marks.length) tr.setStoredMarks(marks);
132
+ });
133
+ };
@@ -172,9 +172,9 @@ class RebaseMapping implements Mappable {
172
172
  // Which side of each original step's changed range the position was on. Content deleted
173
173
  // outside history can collapse that distinction; the rebased step's map must restore it, or a
174
174
  // position left of re-inserted content ends up right of it (and vice versa).
175
- const sides: number[] = [];
175
+ const sides: number[][] = [];
176
176
  for (let i = this.inverted.length - 1; i >= 0; i--) {
177
- sides[i] = (this.inverted[i] as StepMap).side(pos);
177
+ sides[i] = (this.inverted[i] as StepMap).sides(pos);
178
178
  const result = (this.inverted[i] as StepMap).mapResult(pos, assoc);
179
179
  const mirror = this.rebased[i];
180
180
  if (result.recover !== null && mirror) {
@@ -192,7 +192,7 @@ class RebaseMapping implements Mappable {
192
192
  pos = result.pos;
193
193
  }
194
194
  for (let i = from; i < this.rebased.length; i++) {
195
- const result = this.rebased[i]?.mapResult(pos, sides[i] || assoc);
195
+ const result = this.rebased[i]?.mapResult(pos, assoc, sides[i]);
196
196
  if (!result) continue;
197
197
  deleted ||= result.deleted;
198
198
  pos = result.pos;
@@ -1,4 +1,5 @@
1
1
  export {
2
+ arrowAcrossLeaf,
2
3
  baseKeymap,
3
4
  type DeleteUnit,
4
5
  deleteBackward,
@@ -16,6 +17,14 @@ export {
16
17
  toggleMark,
17
18
  } from "./commands.js";
18
19
  export { createEditor, type Editor, type EditorListener, type EditorOptions } from "./editor.js";
20
+ export {
21
+ alignAt,
22
+ colorAt,
23
+ insertHorizontalRule,
24
+ setAlign,
25
+ setHighlight,
26
+ setTextColor,
27
+ } from "./format.js";
19
28
  export {
20
29
  closeHistory,
21
30
  type HistoryOptions,
@@ -25,9 +34,31 @@ export {
25
34
  undo,
26
35
  undoDepth,
27
36
  } from "./history.js";
37
+ export {
38
+ autolinkHref,
39
+ insertLink,
40
+ linkAt,
41
+ linkEditorRequest,
42
+ normalizeHref,
43
+ openLinkEditor,
44
+ removeLink,
45
+ requestsLinkEditor,
46
+ setLink,
47
+ } from "./links.js";
48
+ export {
49
+ liftListItem,
50
+ liftListItemAtStart,
51
+ listKeymap,
52
+ listTypeAt,
53
+ sinkListItem,
54
+ splitListItem,
55
+ toggleList,
56
+ wrapInList,
57
+ } from "./lists.js";
28
58
  export {
29
59
  AllSelection,
30
60
  marksAt,
61
+ NodeSelection,
31
62
  Selection,
32
63
  type SelectionJSON,
33
64
  TextSelection,