@folijs/core 0.1.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 (189) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +10 -15
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +41 -19
  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/attrs.d.ts +5 -0
  12. package/dist/model/attrs.d.ts.map +1 -1
  13. package/dist/model/attrs.js +17 -0
  14. package/dist/model/attrs.js.map +1 -1
  15. package/dist/model/content.d.ts +10 -0
  16. package/dist/model/content.d.ts.map +1 -1
  17. package/dist/model/content.js +44 -0
  18. package/dist/model/content.js.map +1 -1
  19. package/dist/model/fragment.d.ts +7 -2
  20. package/dist/model/fragment.d.ts.map +1 -1
  21. package/dist/model/fragment.js +13 -2
  22. package/dist/model/fragment.js.map +1 -1
  23. package/dist/model/index.d.ts +1 -1
  24. package/dist/model/index.d.ts.map +1 -1
  25. package/dist/model/index.js +1 -1
  26. package/dist/model/index.js.map +1 -1
  27. package/dist/model/mark.d.ts.map +1 -1
  28. package/dist/model/mark.js +4 -3
  29. package/dist/model/mark.js.map +1 -1
  30. package/dist/model/node.d.ts +13 -1
  31. package/dist/model/node.d.ts.map +1 -1
  32. package/dist/model/node.js +35 -3
  33. package/dist/model/node.js.map +1 -1
  34. package/dist/model/resolvedpos.d.ts +26 -2
  35. package/dist/model/resolvedpos.d.ts.map +1 -1
  36. package/dist/model/resolvedpos.js +54 -2
  37. package/dist/model/resolvedpos.js.map +1 -1
  38. package/dist/model/schema.d.ts +25 -0
  39. package/dist/model/schema.d.ts.map +1 -1
  40. package/dist/model/schema.js +23 -0
  41. package/dist/model/schema.js.map +1 -1
  42. package/dist/model/slice.d.ts +7 -0
  43. package/dist/model/slice.d.ts.map +1 -1
  44. package/dist/model/slice.js +53 -0
  45. package/dist/model/slice.js.map +1 -1
  46. package/dist/schema.d.ts +72 -8
  47. package/dist/schema.d.ts.map +1 -1
  48. package/dist/schema.js +93 -9
  49. package/dist/schema.js.map +1 -1
  50. package/dist/state/attempt.d.ts +4 -0
  51. package/dist/state/attempt.d.ts.map +1 -0
  52. package/dist/state/attempt.js +19 -0
  53. package/dist/state/attempt.js.map +1 -0
  54. package/dist/state/commands.d.ts +21 -5
  55. package/dist/state/commands.d.ts.map +1 -1
  56. package/dist/state/commands.js +260 -68
  57. package/dist/state/commands.js.map +1 -1
  58. package/dist/state/editor.d.ts +41 -7
  59. package/dist/state/editor.d.ts.map +1 -1
  60. package/dist/state/editor.js +51 -10
  61. package/dist/state/editor.js.map +1 -1
  62. package/dist/state/format.d.ts +13 -0
  63. package/dist/state/format.d.ts.map +1 -0
  64. package/dist/state/format.js +20 -0
  65. package/dist/state/format.js.map +1 -0
  66. package/dist/state/history.js +2 -2
  67. package/dist/state/history.js.map +1 -1
  68. package/dist/state/index.d.ts +10 -3
  69. package/dist/state/index.d.ts.map +1 -1
  70. package/dist/state/index.js +10 -3
  71. package/dist/state/index.js.map +1 -1
  72. package/dist/state/links.d.ts +42 -0
  73. package/dist/state/links.d.ts.map +1 -0
  74. package/dist/state/links.js +194 -0
  75. package/dist/state/links.js.map +1 -0
  76. package/dist/state/lists.d.ts +23 -0
  77. package/dist/state/lists.d.ts.map +1 -0
  78. package/dist/state/lists.js +34 -0
  79. package/dist/state/lists.js.map +1 -0
  80. package/dist/state/mark.d.ts +25 -0
  81. package/dist/state/mark.d.ts.map +1 -0
  82. package/dist/state/mark.js +40 -0
  83. package/dist/state/mark.js.map +1 -0
  84. package/dist/state/selection.d.ts +18 -2
  85. package/dist/state/selection.d.ts.map +1 -1
  86. package/dist/state/selection.js +63 -2
  87. package/dist/state/selection.js.map +1 -1
  88. package/dist/state/state.d.ts.map +1 -1
  89. package/dist/state/state.js +23 -2
  90. package/dist/state/state.js.map +1 -1
  91. package/dist/state/word.d.ts +72 -0
  92. package/dist/state/word.d.ts.map +1 -0
  93. package/dist/state/word.js +173 -0
  94. package/dist/state/word.js.map +1 -0
  95. package/dist/state/wordclip.d.ts +43 -0
  96. package/dist/state/wordclip.d.ts.map +1 -0
  97. package/dist/state/wordclip.js +412 -0
  98. package/dist/state/wordclip.js.map +1 -0
  99. package/dist/state/wordformat.d.ts +136 -0
  100. package/dist/state/wordformat.d.ts.map +1 -0
  101. package/dist/state/wordformat.js +846 -0
  102. package/dist/state/wordformat.js.map +1 -0
  103. package/dist/transform/index.d.ts +2 -1
  104. package/dist/transform/index.d.ts.map +1 -1
  105. package/dist/transform/index.js +2 -1
  106. package/dist/transform/index.js.map +1 -1
  107. package/dist/transform/stepmap.d.ts +8 -6
  108. package/dist/transform/stepmap.d.ts.map +1 -1
  109. package/dist/transform/stepmap.js +18 -15
  110. package/dist/transform/stepmap.js.map +1 -1
  111. package/dist/transform/steps.d.ts +27 -2
  112. package/dist/transform/steps.d.ts.map +1 -1
  113. package/dist/transform/steps.js +115 -4
  114. package/dist/transform/steps.js.map +1 -1
  115. package/dist/transform/structure.d.ts +26 -0
  116. package/dist/transform/structure.d.ts.map +1 -0
  117. package/dist/transform/structure.js +116 -0
  118. package/dist/transform/structure.js.map +1 -0
  119. package/dist/transform/transform.d.ts +34 -11
  120. package/dist/transform/transform.d.ts.map +1 -1
  121. package/dist/transform/transform.js +145 -18
  122. package/dist/transform/transform.js.map +1 -1
  123. package/dist/v3/check.d.ts +33 -0
  124. package/dist/v3/check.d.ts.map +1 -0
  125. package/dist/v3/check.js +90 -0
  126. package/dist/v3/check.js.map +1 -0
  127. package/dist/v3/document.d.ts +217 -0
  128. package/dist/v3/document.d.ts.map +1 -0
  129. package/dist/v3/document.js +225 -0
  130. package/dist/v3/document.js.map +1 -0
  131. package/dist/v3/index.d.ts +6 -0
  132. package/dist/v3/index.d.ts.map +1 -0
  133. package/dist/v3/index.js +6 -0
  134. package/dist/v3/index.js.map +1 -0
  135. package/dist/v3/migrate.d.ts +19 -0
  136. package/dist/v3/migrate.d.ts.map +1 -0
  137. package/dist/v3/migrate.js +227 -0
  138. package/dist/v3/migrate.js.map +1 -0
  139. package/dist/v3/resolve.d.ts +129 -0
  140. package/dist/v3/resolve.d.ts.map +1 -0
  141. package/dist/v3/resolve.js +534 -0
  142. package/dist/v3/resolve.js.map +1 -0
  143. package/dist/v3/schema.d.ts +27 -0
  144. package/dist/v3/schema.d.ts.map +1 -0
  145. package/dist/v3/schema.js +429 -0
  146. package/dist/v3/schema.js.map +1 -0
  147. package/dist/v3/units.d.ts +16 -0
  148. package/dist/v3/units.d.ts.map +1 -0
  149. package/dist/v3/units.js +28 -0
  150. package/dist/v3/units.js.map +1 -0
  151. package/package.json +1 -1
  152. package/src/document.ts +49 -23
  153. package/src/index.ts +17 -6
  154. package/src/model/attrs.ts +19 -0
  155. package/src/model/content.ts +56 -0
  156. package/src/model/fragment.ts +18 -3
  157. package/src/model/index.ts +1 -1
  158. package/src/model/mark.ts +3 -2
  159. package/src/model/node.ts +48 -3
  160. package/src/model/resolvedpos.ts +55 -2
  161. package/src/model/schema.ts +43 -0
  162. package/src/model/slice.ts +81 -1
  163. package/src/schema.ts +148 -13
  164. package/src/state/attempt.ts +22 -0
  165. package/src/state/commands.ts +287 -69
  166. package/src/state/editor.ts +103 -21
  167. package/src/state/format.ts +35 -0
  168. package/src/state/history.ts +3 -3
  169. package/src/state/index.ts +63 -1
  170. package/src/state/links.ts +193 -0
  171. package/src/state/lists.ts +50 -0
  172. package/src/state/mark.ts +47 -0
  173. package/src/state/selection.ts +72 -3
  174. package/src/state/state.ts +22 -2
  175. package/src/state/word.ts +245 -0
  176. package/src/state/wordclip.ts +445 -0
  177. package/src/state/wordformat.ts +982 -0
  178. package/src/transform/index.ts +8 -0
  179. package/src/transform/stepmap.ts +18 -12
  180. package/src/transform/steps.ts +126 -3
  181. package/src/transform/structure.ts +135 -0
  182. package/src/transform/transform.ts +165 -16
  183. package/src/v3/check.ts +119 -0
  184. package/src/v3/document.ts +456 -0
  185. package/src/v3/index.ts +33 -0
  186. package/src/v3/migrate.ts +267 -0
  187. package/src/v3/resolve.ts +646 -0
  188. package/src/v3/schema.ts +479 -0
  189. package/src/v3/units.ts +34 -0
@@ -4,8 +4,16 @@ export {
4
4
  NodeMarkupBatchStep,
5
5
  NodeMarkupStep,
6
6
  RemoveMarkStep,
7
+ ReplaceAroundStep,
7
8
  ReplaceStep,
8
9
  Step,
9
10
  StepResult,
10
11
  } from "./steps.js";
12
+ export {
13
+ canJoin,
14
+ canSplit,
15
+ findWrapping,
16
+ liftTarget,
17
+ type NodeTypeWithAttrs,
18
+ } from "./structure.js";
11
19
  export { Transform, TransformError } from "./transform.js";
@@ -33,7 +33,11 @@ export class StepMap implements Mappable {
33
33
  readonly inverted = false,
34
34
  ) {}
35
35
 
36
- mapResult(pos: number, assoc = 1): MapResult {
36
+ /**
37
+ * Maps `pos`. `sides` (from `sides()` of a map with the same ranges) overrides `assoc` per
38
+ * range at pure insertions, where the side decides which side of the new content `pos` ends up.
39
+ */
40
+ mapResult(pos: number, assoc = 1, sides?: readonly number[]): MapResult {
37
41
  let diff = 0;
38
42
  const oldIndex = this.inverted ? 2 : 1;
39
43
  const newIndex = this.inverted ? 1 : 2;
@@ -44,7 +48,13 @@ export class StepMap implements Mappable {
44
48
  const newSize = this.ranges[i + newIndex] as number;
45
49
  const end = start + oldSize;
46
50
  if (pos <= end) {
47
- const side = !oldSize ? assoc : pos === start ? -1 : pos === end ? 1 : assoc;
51
+ const side = !oldSize
52
+ ? sides?.[i / 3] || assoc
53
+ : pos === start
54
+ ? -1
55
+ : pos === end
56
+ ? 1
57
+ : assoc;
48
58
  // Recoverable unless the position sits on the range edge it associates with; a start edge
49
59
  // with right association must be recoverable, or it drifts past re-inserted content.
50
60
  const recoverable = pos !== (assoc < 0 ? start : end);
@@ -91,19 +101,15 @@ export class StepMap implements Mappable {
91
101
  }
92
102
 
93
103
  /**
94
- * Which side of the changed ranges `pos` (in input coordinates) lies on: -1 at or before the
95
- * nearest range ahead of it, 1 at or after the last range behind it, 0 for an empty map.
96
- * shortcut: one side for the whole map, exact only for single-range maps (every step today);
97
- * record a side per range when multi-range steps (ReplaceAroundStep, Phase 7) arrive.
104
+ * Which side of each changed range `pos` (in input coordinates) lies on: -1 at or before the
105
+ * range, 1 at or after it, 0 strictly inside. One entry per range, in order.
98
106
  */
99
- side(pos: number): -1 | 0 | 1 {
100
- let side: -1 | 0 | 1 = 0;
107
+ sides(pos: number): (-1 | 0 | 1)[] {
108
+ const sides: (-1 | 0 | 1)[] = [];
101
109
  this.forEach((oldStart, oldEnd) => {
102
- if (side === -1) return;
103
- if (pos <= oldStart) side = -1;
104
- else if (pos >= oldEnd) side = 1;
110
+ sides.push(pos <= oldStart ? -1 : pos >= oldEnd ? 1 : 0);
105
111
  });
106
- return side;
112
+ return sides;
107
113
  }
108
114
 
109
115
  invert(): StepMap {
@@ -59,17 +59,25 @@ export abstract class Step {
59
59
  abstract map(mapping: Mappable): Step | null;
60
60
  }
61
61
 
62
- /** Replaces `from..to` with a slice. */
62
+ /**
63
+ * Replaces `from..to` with a slice. A `structure` step only moves node boundaries (split, join):
64
+ * it fails instead of deleting content that, after mapping through other changes, now sits in
65
+ * its range.
66
+ */
63
67
  export class ReplaceStep extends Step {
64
68
  constructor(
65
69
  readonly from: number,
66
70
  readonly to: number,
67
71
  readonly slice: Slice,
72
+ readonly structure = false,
68
73
  ) {
69
74
  super();
70
75
  }
71
76
 
72
77
  apply(doc: Node): StepResult {
78
+ if (this.structure && contentBetween(doc, this.from, this.to)) {
79
+ return StepResult.fail("Structure replace would overwrite content");
80
+ }
73
81
  return StepResult.fromReplace(doc, this.from, this.to, this.slice);
74
82
  }
75
83
 
@@ -85,7 +93,7 @@ export class ReplaceStep extends Step {
85
93
  const from = mapping.mapResult(this.from, 1);
86
94
  const to = mapping.mapResult(this.to, -1);
87
95
  if (from.deleted && to.deleted) return null;
88
- return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);
96
+ return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);
89
97
  }
90
98
 
91
99
  /**
@@ -93,7 +101,7 @@ export class ReplaceStep extends Step {
93
101
  * (e.g. consecutive keystrokes); null otherwise. Keeps typing history to one step per run.
94
102
  */
95
103
  merge(next: Step): ReplaceStep | null {
96
- if (!(next instanceof ReplaceStep)) return null;
104
+ if (!(next instanceof ReplaceStep) || next.structure || this.structure) return null;
97
105
  const join = (a: Slice, b: Slice) =>
98
106
  a.size + b.size === 0
99
107
  ? Slice.empty
@@ -112,6 +120,121 @@ export class ReplaceStep extends Step {
112
120
  }
113
121
  }
114
122
 
123
+ /**
124
+ * Replaces `from..to` with a slice while keeping the content between `gapFrom` and `gapTo`,
125
+ * which is inserted into the slice at `insert`. Wrapping blocks in a list (the slice holds the
126
+ * empty wrappers) and lifting them out (the slice holds the split ancestors) are such steps:
127
+ * the moved content is not deleted and re-inserted, so positions inside it map through.
128
+ */
129
+ export class ReplaceAroundStep extends Step {
130
+ constructor(
131
+ readonly from: number,
132
+ readonly to: number,
133
+ readonly gapFrom: number,
134
+ readonly gapTo: number,
135
+ readonly slice: Slice,
136
+ readonly insert: number,
137
+ readonly structure = false,
138
+ ) {
139
+ super();
140
+ }
141
+
142
+ apply(doc: Node): StepResult {
143
+ if (
144
+ this.from < 0 ||
145
+ this.from > this.gapFrom ||
146
+ this.gapFrom > this.gapTo ||
147
+ this.gapTo > this.to ||
148
+ this.to > doc.content.size
149
+ ) {
150
+ return StepResult.fail(`Invalid gap range ${this.from}..${this.to}`);
151
+ }
152
+ if (
153
+ this.structure &&
154
+ (contentBetween(doc, this.from, this.gapFrom) || contentBetween(doc, this.gapTo, this.to))
155
+ ) {
156
+ return StepResult.fail("Structure gap-replace would overwrite content");
157
+ }
158
+ const gap = doc.slice(this.gapFrom, this.gapTo);
159
+ if (gap.openStart || gap.openEnd) return StepResult.fail("Gap is not a flat range");
160
+ let inserted: Slice | null;
161
+ try {
162
+ inserted = this.slice.insertAt(this.insert, gap.content);
163
+ } catch (error) {
164
+ if (error instanceof RangeError) return StepResult.fail(error.message);
165
+ throw error;
166
+ }
167
+ if (!inserted) return StepResult.fail("Content does not fit in gap");
168
+ return StepResult.fromReplace(doc, this.from, this.to, inserted);
169
+ }
170
+
171
+ override getMap(): StepMap {
172
+ return new StepMap([
173
+ this.from,
174
+ this.gapFrom - this.from,
175
+ this.insert,
176
+ this.gapTo,
177
+ this.to - this.gapTo,
178
+ this.slice.size - this.insert,
179
+ ]);
180
+ }
181
+
182
+ invert(doc: Node): Step {
183
+ const gap = this.gapTo - this.gapFrom;
184
+ return new ReplaceAroundStep(
185
+ this.from,
186
+ this.from + this.slice.size + gap,
187
+ this.from + this.insert,
188
+ this.from + this.insert + gap,
189
+ doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from),
190
+ this.gapFrom - this.from,
191
+ this.structure,
192
+ );
193
+ }
194
+
195
+ map(mapping: Mappable): Step | null {
196
+ const from = mapping.mapResult(this.from, 1);
197
+ const to = mapping.mapResult(this.to, -1);
198
+ const gapFrom = this.from === this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);
199
+ const gapTo = this.to === this.gapTo ? to.pos : mapping.map(this.gapTo, 1);
200
+ if ((from.deleted && to.deleted) || gapFrom < from.pos || gapTo > to.pos) return null;
201
+ // The content it moves is gone: a lift would only split its ancestors around nothing.
202
+ if (this.gapTo > this.gapFrom && gapTo <= gapFrom) return null;
203
+ return new ReplaceAroundStep(
204
+ from.pos,
205
+ to.pos,
206
+ gapFrom,
207
+ gapTo,
208
+ this.slice,
209
+ this.insert,
210
+ this.structure,
211
+ );
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Whether `from..to` holds anything but node boundaries: text, a leaf, or a node that is not
217
+ * the first or last along the path. Used by structure steps.
218
+ */
219
+ function contentBetween(doc: Node, from: number, to: number): boolean {
220
+ const $from = doc.resolve(from);
221
+ let dist = to - from;
222
+ let depth = $from.depth;
223
+ while (dist > 0 && depth > 0 && $from.indexAfter(depth) === $from.node(depth).childCount) {
224
+ depth--;
225
+ dist--;
226
+ }
227
+ if (dist > 0) {
228
+ let next = $from.node(depth).maybeChild($from.indexAfter(depth));
229
+ while (dist > 0) {
230
+ if (!next || next.isLeaf) return true;
231
+ next = next.firstChild;
232
+ dist--;
233
+ }
234
+ }
235
+ return false;
236
+ }
237
+
115
238
  /** Rebuilds inline nodes of a fragment with `f`, descending into block content. */
116
239
  function mapInline(
117
240
  fragment: Fragment,
@@ -0,0 +1,135 @@
1
+ // The structure helpers follow the design of prosemirror-transform's structure.ts (MIT, see
2
+ // THIRD_PARTY_NOTICES.md); independent implementation on Foli's model.
3
+ import type { Attrs, Node, NodeRange, NodeType } from "../model/index.js";
4
+
5
+ /** A node type with attributes, as `findWrapping` returns and `Transform.wrap`/`split` take. */
6
+ export interface NodeTypeWithAttrs {
7
+ type: NodeType;
8
+ attrs?: Attrs | null;
9
+ }
10
+
11
+ /** Whether the children of `node` before `start` and from `end` on are valid on their own. */
12
+ function canCut(node: Node, start: number, end: number): boolean {
13
+ return (
14
+ (start === 0 || node.canReplace(start, node.childCount)) &&
15
+ (end === node.childCount || node.canReplace(0, end))
16
+ );
17
+ }
18
+
19
+ /**
20
+ * The depth the blocks of `range` can be lifted to (out of their parent, e.g. out of a list
21
+ * item), or null when they cannot be lifted. Ancestors are split around the range as needed.
22
+ */
23
+ export function liftTarget(range: NodeRange): number | null {
24
+ const content = range.parent.content.cutByIndex(range.startIndex, range.endIndex);
25
+ for (let depth = range.depth; ; depth--) {
26
+ const node = range.$from.node(depth);
27
+ const index = range.$from.index(depth);
28
+ const endIndex = range.$to.indexAfter(depth);
29
+ if (depth < range.depth && node.canReplace(index, endIndex, content)) return depth;
30
+ if (depth === 0 || !canCut(node, index, endIndex)) return null;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * The wrappers (outermost first) that put the blocks of `range` inside a node of `type`: any
36
+ * wrappers its parent needs around `type`, `type` itself, then any wrappers needed between
37
+ * `type` and the blocks (for a list: the list, then a list item). Null when impossible.
38
+ */
39
+ export function findWrapping(
40
+ range: NodeRange,
41
+ type: NodeType,
42
+ attrs: Attrs | null = null,
43
+ ): NodeTypeWithAttrs[] | null {
44
+ const around = wrappingOutside(range, type);
45
+ const inner = around && wrappingInside(range, type);
46
+ if (!around || !inner) return null;
47
+ return [
48
+ ...around.map((t) => ({ type: t, attrs: null })),
49
+ { type, attrs },
50
+ ...inner.map((t) => ({ type: t, attrs: null })),
51
+ ];
52
+ }
53
+
54
+ function wrappingOutside(range: NodeRange, type: NodeType): readonly NodeType[] | null {
55
+ const { parent, startIndex, endIndex } = range;
56
+ const around = parent.contentMatchAt(startIndex).findWrapping(type);
57
+ if (!around) return null;
58
+ const outer = around[0] ?? type;
59
+ return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
60
+ }
61
+
62
+ function wrappingInside(range: NodeRange, type: NodeType): readonly NodeType[] | null {
63
+ const { parent, startIndex, endIndex } = range;
64
+ const inside = type.contentMatch.findWrapping(parent.child(startIndex).type);
65
+ if (!inside) return null;
66
+ let match = (inside[inside.length - 1] ?? type).contentMatch;
67
+ for (let i = startIndex; i < endIndex; i++) {
68
+ const next = match.matchType(parent.child(i).type);
69
+ if (!next) return null;
70
+ match = next;
71
+ }
72
+ return match.validEnd ? inside : null;
73
+ }
74
+
75
+ /**
76
+ * Whether splitting at `pos` through `depth` ancestors is valid, giving the new nodes after the
77
+ * split the types in `typesAfter`: entry 0 for the outermost split node, entry `depth - 1` for
78
+ * the innermost (the one holding `pos`); missing or null entries keep the original type.
79
+ */
80
+ export function canSplit(
81
+ doc: Node,
82
+ pos: number,
83
+ depth = 1,
84
+ typesAfter?: readonly (NodeTypeWithAttrs | null | undefined)[],
85
+ ): boolean {
86
+ const $pos = doc.resolve(pos);
87
+ const base = $pos.depth - depth;
88
+ if (base < 0) return false;
89
+ if (typesAfter?.some((entry) => entry && !attrsValid(entry))) return false;
90
+ const innerType = typesAfter?.[depth - 1]?.type ?? $pos.parent.type;
91
+ if (
92
+ !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||
93
+ !innerType.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))
94
+ ) {
95
+ return false;
96
+ }
97
+ for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {
98
+ const node = $pos.node(d);
99
+ const index = $pos.index(d);
100
+ let rest = node.content.cutByIndex(index, node.childCount);
101
+ const override = typesAfter?.[i + 1];
102
+ if (override) {
103
+ rest = rest.replaceChild(0, override.type.createOpen(override.attrs));
104
+ }
105
+ const after = typesAfter?.[i]?.type ?? node.type;
106
+ if (!node.canReplace(index + 1, node.childCount) || !after.validContent(rest)) return false;
107
+ }
108
+ const index = $pos.indexAfter(base);
109
+ const baseType = typesAfter?.[0]?.type ?? $pos.node(base + 1).type;
110
+ return $pos.node(base).canReplaceWith(index, index, baseType);
111
+ }
112
+
113
+ function attrsValid({ type, attrs }: NodeTypeWithAttrs): boolean {
114
+ try {
115
+ type.createOpen(attrs);
116
+ return true;
117
+ } catch {
118
+ return false;
119
+ }
120
+ }
121
+
122
+ /** Whether the nodes on either side of `pos` can be joined into one. */
123
+ export function canJoin(doc: Node, pos: number): boolean {
124
+ if (pos <= 0 || pos >= doc.content.size) return false;
125
+ const $pos = doc.resolve(pos);
126
+ const before = $pos.nodeBefore;
127
+ const after = $pos.nodeAfter;
128
+ // A leaf after the boundary has no content to join: "joining" would delete it.
129
+ if (!before || !after || before.isLeaf || after.isLeaf) return false;
130
+ const index = $pos.index();
131
+ return (
132
+ before.canReplace(before.childCount, before.childCount, after.content) &&
133
+ $pos.parent.canReplace(index, index + 1)
134
+ );
135
+ }
@@ -3,10 +3,12 @@
3
3
  import { deepEqual } from "../model/attrs.js";
4
4
  import {
5
5
  type Attrs,
6
+ FoliDocumentError,
6
7
  Fragment,
7
8
  type Mark,
8
9
  MarkType,
9
10
  type Node,
11
+ type NodeRange,
10
12
  type NodeType,
11
13
  Slice,
12
14
  } from "../model/index.js";
@@ -16,10 +18,31 @@ import {
16
18
  NodeMarkupBatchStep,
17
19
  NodeMarkupStep,
18
20
  RemoveMarkStep,
21
+ ReplaceAroundStep,
19
22
  ReplaceStep,
20
23
  type Step,
21
24
  type StepResult,
22
25
  } from "./steps.js";
26
+ import type { NodeTypeWithAttrs } from "./structure.js";
27
+
28
+ /** The attributes a block gets when it becomes `type` (see Transform.setBlockType). */
29
+ function blockAttrs(node: Node, type: NodeType, attrs: Attrs | null): Attrs {
30
+ const merged: Record<string, unknown> = {};
31
+ const own = node.type.spec.attrs ?? {};
32
+ for (const name of Object.keys(type.spec.attrs ?? {})) {
33
+ if (attrs && Object.hasOwn(attrs, name)) merged[name] = attrs[name];
34
+ else if (Object.hasOwn(own, name)) merged[name] = node.attrs[name];
35
+ }
36
+ for (const name of Object.keys(attrs ?? {})) {
37
+ if (!Object.hasOwn(merged, name)) merged[name] = attrs?.[name]; // unknown: rejected below
38
+ }
39
+ try {
40
+ return type.createOpen(merged).attrs;
41
+ } catch (error) {
42
+ if (error instanceof FoliDocumentError) throw new TransformError(error.message);
43
+ throw error;
44
+ }
45
+ }
23
46
 
24
47
  /** A step could not be applied (the change would break the schema or the range is invalid). */
25
48
  export class TransformError extends Error {
@@ -150,35 +173,142 @@ export class Transform {
150
173
  }
151
174
 
152
175
  /**
153
- * Splits the textblock around `pos` in two. The second half gets the same markup unless
154
- * `after` says otherwise. shortcut: splits one level only; nested splits arrive with lists (Phase 7).
176
+ * Splits the node around `pos` and `depth - 1` of its ancestors in two (depth 2 in a list
177
+ * item's paragraph splits the item). The new nodes after the split get the types in
178
+ * `typesAfter`: entry 0 for the outermost split node, entry `depth - 1` for the innermost;
179
+ * missing or null entries keep the original type and attributes. Check with `canSplit`
180
+ * first: an invalid split (content or attributes) throws TransformError.
155
181
  */
156
- split(pos: number, after?: { type: NodeType; attrs?: Attrs | null }): this {
157
- const parent = this.doc.resolve(pos).parent;
158
- const second = after ? after.type.create(after.attrs) : parent.copy();
159
- return this.replace(pos, pos, new Slice(Fragment.from([parent.copy(), second]), 1, 1));
182
+ split(
183
+ pos: number,
184
+ depth = 1,
185
+ typesAfter?: readonly (NodeTypeWithAttrs | null | undefined)[],
186
+ ): this {
187
+ const $pos = this.doc.resolve(pos);
188
+ if (depth < 1 || depth > $pos.depth)
189
+ throw new TransformError(`Cannot split ${depth} levels at ${pos}`);
190
+ let before = Fragment.empty;
191
+ let after = Fragment.empty;
192
+ for (let d = $pos.depth, i = depth - 1; d > $pos.depth - depth; d--, i--) {
193
+ before = Fragment.from($pos.node(d).copy(before));
194
+ const typeAfter = typesAfter?.[i];
195
+ let next: Node;
196
+ try {
197
+ next = typeAfter
198
+ ? typeAfter.type.createOpen(typeAfter.attrs, after)
199
+ : $pos.node(d).copy(after);
200
+ } catch (error) {
201
+ if (error instanceof FoliDocumentError) throw new TransformError(error.message);
202
+ throw error;
203
+ }
204
+ after = Fragment.from(next);
205
+ }
206
+ return this.step(
207
+ new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true),
208
+ );
160
209
  }
161
210
 
162
211
  /**
163
- * Joins the two textblocks on either side of `pos`. Throws TransformError for any other position.
164
- * shortcut: textblocks only; joining other compatible blocks (lists, Phase 7) needs a content check.
212
+ * Joins the nodes on either side of `pos` (and, with `depth` > 1, their last and first
213
+ * descendants down to that depth). Throws TransformError when they cannot be joined; check
214
+ * with `canJoin` first.
165
215
  */
166
- join(pos: number): this {
167
- // Without this check a position inside text would silently delete the two characters around it.
216
+ join(pos: number, depth = 1): this {
217
+ // Without this check a position inside text would silently delete the characters around it.
168
218
  const $pos = pos > 0 && pos < this.doc.content.size ? this.doc.resolve(pos) : null;
169
- if (!$pos?.nodeBefore?.isTextblock || !$pos.nodeAfter?.isTextblock) {
170
- throw new TransformError(`Position ${pos} is not between two textblocks`);
219
+ const before = $pos?.nodeBefore;
220
+ const after = $pos?.nodeAfter;
221
+ if (!before || !after || before.isLeaf || after.isLeaf || $pos?.textOffset) {
222
+ throw new TransformError(`Position ${pos} is not between two joinable nodes`);
171
223
  }
172
- return this.delete(pos - 1, pos + 1);
224
+ return this.step(new ReplaceStep(pos - depth, pos + depth, Slice.empty, true));
173
225
  }
174
226
 
175
- /** Changes every textblock touching `from..to` to `type` with `attrs`, keeping content. */
227
+ /**
228
+ * Wraps the blocks of `range` in `wrappers` (outermost first, as `findWrapping` returns
229
+ * them). The blocks move inside without being re-created, so positions in them map through.
230
+ */
231
+ wrap(range: NodeRange, wrappers: readonly NodeTypeWithAttrs[]): this {
232
+ let content = Fragment.empty;
233
+ for (let i = wrappers.length - 1; i >= 0; i--) {
234
+ const wrapper = wrappers[i] as NodeTypeWithAttrs;
235
+ if (content.size && !wrapper.type.contentMatch.matchFragment(content)?.validEnd) {
236
+ throw new TransformError(`${wrapper.type.name} cannot hold the next wrapper`);
237
+ }
238
+ content = Fragment.from(wrapper.type.createOpen(wrapper.attrs, content));
239
+ }
240
+ const { start, end } = range;
241
+ return this.step(
242
+ new ReplaceAroundStep(
243
+ start,
244
+ end,
245
+ start,
246
+ end,
247
+ new Slice(content, 0, 0),
248
+ wrappers.length,
249
+ true,
250
+ ),
251
+ );
252
+ }
253
+
254
+ /**
255
+ * Moves the blocks of `range` up to `target` depth (from `liftTarget`), splitting the
256
+ * ancestors they leave around them; ancestors left empty on a side are removed.
257
+ */
258
+ lift(range: NodeRange, target: number): this {
259
+ const { $from, $to, depth } = range;
260
+ const gapStart = $from.before(depth + 1);
261
+ const gapEnd = $to.after(depth + 1);
262
+ let start = gapStart;
263
+ let end = gapEnd;
264
+ let before = Fragment.empty;
265
+ let openStart = 0;
266
+ for (let d = depth, splitting = false; d > target; d--) {
267
+ if (splitting || $from.index(d) > 0) {
268
+ splitting = true;
269
+ before = Fragment.from($from.node(d).copy(before));
270
+ openStart++;
271
+ } else {
272
+ start--;
273
+ }
274
+ }
275
+ let after = Fragment.empty;
276
+ let openEnd = 0;
277
+ for (let d = depth, splitting = false; d > target; d--) {
278
+ if (splitting || $to.after(d + 1) < $to.end(d)) {
279
+ splitting = true;
280
+ after = Fragment.from($to.node(d).copy(after));
281
+ openEnd++;
282
+ } else {
283
+ end++;
284
+ }
285
+ }
286
+ return this.step(
287
+ new ReplaceAroundStep(
288
+ start,
289
+ end,
290
+ gapStart,
291
+ gapEnd,
292
+ new Slice(before.append(after), openStart, openEnd),
293
+ before.size - openStart,
294
+ true,
295
+ ),
296
+ );
297
+ }
298
+
299
+ /**
300
+ * Changes every textblock touching `from..to` to `type`, keeping content. Attributes come from
301
+ * `attrs`, then from the block itself for attributes both types declare (a centered paragraph
302
+ * stays centered as a heading), then from defaults. Blocks already like that are untouched.
303
+ * Invalid attributes throw TransformError.
304
+ */
176
305
  setBlockType(from: number, to: number, type: NodeType, attrs: Attrs | null = null): this {
177
306
  const changed: NodeMarkupStep[] = [];
178
307
  this.doc.nodesBetween(from, to, (node, pos) => {
179
308
  if (!node.isTextblock) return undefined;
180
- if (node.type !== type || !deepEqual(node.attrs, attrs ?? {})) {
181
- changed.push(new NodeMarkupStep(pos, type, attrs));
309
+ const next = blockAttrs(node, type, attrs);
310
+ if (node.type !== type || !deepEqual(node.attrs, next)) {
311
+ changed.push(new NodeMarkupStep(pos, type, next));
182
312
  }
183
313
  return false;
184
314
  });
@@ -186,6 +316,25 @@ export class Transform {
186
316
  return changed.length ? this.step(new NodeMarkupBatchStep(changed)) : this;
187
317
  }
188
318
 
319
+ /**
320
+ * Sets `attrs` on every textblock touching `from..to` whose type declares them (alignment on
321
+ * paragraphs and headings), keeping each block's type. Blocks already like that are untouched.
322
+ * Invalid attributes throw TransformError.
323
+ */
324
+ setBlockAttrs(from: number, to: number, attrs: Attrs): this {
325
+ const changed: NodeMarkupStep[] = [];
326
+ this.doc.nodesBetween(from, to, (node, pos) => {
327
+ if (!node.isTextblock) return undefined;
328
+ const declared = node.type.spec.attrs ?? {};
329
+ const own = Object.fromEntries(Object.entries(attrs).filter(([name]) => name in declared));
330
+ if (!Object.keys(own).length) return false;
331
+ const next = { ...node.attrs, ...own };
332
+ if (!deepEqual(node.attrs, next)) changed.push(new NodeMarkupStep(pos, node.type, next));
333
+ return false;
334
+ });
335
+ return changed.length ? this.step(new NodeMarkupBatchStep(changed)) : this;
336
+ }
337
+
189
338
  /** Changes the markup of the node at `pos` (see NodeMarkupStep). */
190
339
  setNodeMarkup(
191
340
  pos: number,