@folijs/core 0.4.0 → 0.6.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 (153) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/model/schema.d.ts +9 -1
  3. package/dist/model/schema.d.ts.map +1 -1
  4. package/dist/model/schema.js +13 -3
  5. package/dist/model/schema.js.map +1 -1
  6. package/dist/state/commands.d.ts +10 -1
  7. package/dist/state/commands.d.ts.map +1 -1
  8. package/dist/state/commands.js +125 -40
  9. package/dist/state/commands.js.map +1 -1
  10. package/dist/state/comments.d.ts.map +1 -1
  11. package/dist/state/comments.js +15 -6
  12. package/dist/state/comments.js.map +1 -1
  13. package/dist/state/controls.d.ts +128 -0
  14. package/dist/state/controls.d.ts.map +1 -0
  15. package/dist/state/controls.js +1459 -0
  16. package/dist/state/controls.js.map +1 -0
  17. package/dist/state/editor.d.ts +86 -1
  18. package/dist/state/editor.d.ts.map +1 -1
  19. package/dist/state/editor.js +169 -41
  20. package/dist/state/editor.js.map +1 -1
  21. package/dist/state/fields.d.ts +79 -0
  22. package/dist/state/fields.d.ts.map +1 -0
  23. package/dist/state/fields.js +398 -0
  24. package/dist/state/fields.js.map +1 -0
  25. package/dist/state/fieldupdate.d.ts +178 -0
  26. package/dist/state/fieldupdate.d.ts.map +1 -0
  27. package/dist/state/fieldupdate.js +1574 -0
  28. package/dist/state/fieldupdate.js.map +1 -0
  29. package/dist/state/find.d.ts +68 -0
  30. package/dist/state/find.d.ts.map +1 -0
  31. package/dist/state/find.js +397 -0
  32. package/dist/state/find.js.map +1 -0
  33. package/dist/state/history.d.ts +12 -1
  34. package/dist/state/history.d.ts.map +1 -1
  35. package/dist/state/history.js +43 -7
  36. package/dist/state/history.js.map +1 -1
  37. package/dist/state/index.d.ts +15 -5
  38. package/dist/state/index.d.ts.map +1 -1
  39. package/dist/state/index.js +13 -3
  40. package/dist/state/index.js.map +1 -1
  41. package/dist/state/links.d.ts.map +1 -1
  42. package/dist/state/links.js +30 -19
  43. package/dist/state/links.js.map +1 -1
  44. package/dist/state/mark.d.ts.map +1 -1
  45. package/dist/state/mark.js +8 -1
  46. package/dist/state/mark.js.map +1 -1
  47. package/dist/state/navigation.d.ts +70 -0
  48. package/dist/state/navigation.d.ts.map +1 -0
  49. package/dist/state/navigation.js +226 -0
  50. package/dist/state/navigation.js.map +1 -0
  51. package/dist/state/notes.d.ts +94 -0
  52. package/dist/state/notes.d.ts.map +1 -0
  53. package/dist/state/notes.js +444 -0
  54. package/dist/state/notes.js.map +1 -0
  55. package/dist/state/pictures.d.ts +51 -0
  56. package/dist/state/pictures.d.ts.map +1 -0
  57. package/dist/state/pictures.js +140 -0
  58. package/dist/state/pictures.js.map +1 -0
  59. package/dist/state/review.d.ts +13 -4
  60. package/dist/state/review.d.ts.map +1 -1
  61. package/dist/state/review.js +223 -29
  62. package/dist/state/review.js.map +1 -1
  63. package/dist/state/sections.d.ts +101 -0
  64. package/dist/state/sections.d.ts.map +1 -0
  65. package/dist/state/sections.js +472 -0
  66. package/dist/state/sections.js.map +1 -0
  67. package/dist/state/selection.d.ts +12 -1
  68. package/dist/state/selection.d.ts.map +1 -1
  69. package/dist/state/selection.js +12 -0
  70. package/dist/state/selection.js.map +1 -1
  71. package/dist/state/state.d.ts +2 -0
  72. package/dist/state/state.d.ts.map +1 -1
  73. package/dist/state/state.js +4 -0
  74. package/dist/state/state.js.map +1 -1
  75. package/dist/state/stories.d.ts +41 -0
  76. package/dist/state/stories.d.ts.map +1 -0
  77. package/dist/state/stories.js +243 -0
  78. package/dist/state/stories.js.map +1 -0
  79. package/dist/state/tablecommands.d.ts +77 -0
  80. package/dist/state/tablecommands.d.ts.map +1 -0
  81. package/dist/state/tablecommands.js +675 -0
  82. package/dist/state/tablecommands.js.map +1 -0
  83. package/dist/state/tables.d.ts +110 -0
  84. package/dist/state/tables.d.ts.map +1 -0
  85. package/dist/state/tables.js +730 -0
  86. package/dist/state/tables.js.map +1 -0
  87. package/dist/state/track.d.ts +23 -0
  88. package/dist/state/track.d.ts.map +1 -1
  89. package/dist/state/track.js +113 -15
  90. package/dist/state/track.js.map +1 -1
  91. package/dist/state/word.d.ts +78 -16
  92. package/dist/state/word.d.ts.map +1 -1
  93. package/dist/state/word.js +231 -11
  94. package/dist/state/word.js.map +1 -1
  95. package/dist/state/wordclip.d.ts +15 -6
  96. package/dist/state/wordclip.d.ts.map +1 -1
  97. package/dist/state/wordclip.js +213 -18
  98. package/dist/state/wordclip.js.map +1 -1
  99. package/dist/state/wordformat.d.ts +10 -2
  100. package/dist/state/wordformat.d.ts.map +1 -1
  101. package/dist/state/wordformat.js +98 -17
  102. package/dist/state/wordformat.js.map +1 -1
  103. package/dist/v3/document.d.ts +237 -7
  104. package/dist/v3/document.d.ts.map +1 -1
  105. package/dist/v3/document.js +314 -15
  106. package/dist/v3/document.js.map +1 -1
  107. package/dist/v3/index.d.ts +2 -2
  108. package/dist/v3/index.d.ts.map +1 -1
  109. package/dist/v3/index.js +2 -2
  110. package/dist/v3/index.js.map +1 -1
  111. package/dist/v3/migrate.d.ts +2 -2
  112. package/dist/v3/migrate.d.ts.map +1 -1
  113. package/dist/v3/resolve.d.ts +57 -5
  114. package/dist/v3/resolve.d.ts.map +1 -1
  115. package/dist/v3/resolve.js +224 -16
  116. package/dist/v3/resolve.js.map +1 -1
  117. package/dist/v3/schema.d.ts +6 -0
  118. package/dist/v3/schema.d.ts.map +1 -1
  119. package/dist/v3/schema.js +254 -8
  120. package/dist/v3/schema.js.map +1 -1
  121. package/package.json +1 -1
  122. package/src/model/schema.ts +18 -2
  123. package/src/state/commands.ts +121 -32
  124. package/src/state/comments.ts +14 -6
  125. package/src/state/controls.ts +1596 -0
  126. package/src/state/editor.ts +292 -46
  127. package/src/state/fields.ts +432 -0
  128. package/src/state/fieldupdate.ts +1770 -0
  129. package/src/state/find.ts +510 -0
  130. package/src/state/history.ts +51 -7
  131. package/src/state/index.ts +157 -0
  132. package/src/state/links.ts +27 -17
  133. package/src/state/mark.ts +8 -1
  134. package/src/state/navigation.ts +305 -0
  135. package/src/state/notes.ts +519 -0
  136. package/src/state/numeric-pictures.word.json +172 -0
  137. package/src/state/pictures.ts +168 -0
  138. package/src/state/review.ts +265 -31
  139. package/src/state/sections.ts +571 -0
  140. package/src/state/selection.ts +15 -1
  141. package/src/state/state.ts +5 -0
  142. package/src/state/stories.ts +285 -0
  143. package/src/state/tablecommands.ts +741 -0
  144. package/src/state/tables.ts +761 -0
  145. package/src/state/track.ts +128 -16
  146. package/src/state/word.ts +276 -13
  147. package/src/state/wordclip.ts +231 -32
  148. package/src/state/wordformat.ts +96 -14
  149. package/src/v3/document.ts +572 -16
  150. package/src/v3/index.ts +21 -0
  151. package/src/v3/migrate.ts +2 -2
  152. package/src/v3/resolve.ts +289 -21
  153. package/src/v3/schema.ts +278 -9
@@ -0,0 +1,510 @@
1
+ /**
2
+ * Find and replace over the body and every story (ADR-0007, 11.11), with the rules Word 16 was seen
3
+ * to follow through its object model: a match runs across runs, marks and whatever draws nothing
4
+ * (field markers, bookmarks, comment anchors) but not across a note reference or a picture; a
5
+ * straight quote finds curly ones and a space a no-break space, not the other way round; "whole
6
+ * words" takes letters and digits as word characters (`_` and `'` end a word) and is ignored when
7
+ * the query has a space; the replacement takes the formatting of the match's first character and,
8
+ * unless the case must match, follows its capitals.
9
+ *
10
+ * Regular expressions are left out: a user's pattern can backtrack for ever on the main thread, and
11
+ * Word's own wildcards are another language.
12
+ */
13
+ import { Fragment, type Node, Slice } from "../model/index.js";
14
+ import type { ControlJSON } from "../v3/document.js";
15
+ import { controlAt, controlsIn, readOnlyAt } from "./controls.js";
16
+ import { createEditor, type Editor, type EditorDocument } from "./editor.js";
17
+ import { fieldAround, fieldCodesShown, fieldsIn, isUnseen } from "./fields.js";
18
+ import { inlineText, storyIdOf, withoutReview } from "./fieldupdate.js";
19
+ import { TextSelection } from "./selection.js";
20
+ import type { EditorState, Transaction } from "./state.js";
21
+ import { editTrees } from "./stories.js";
22
+ import { trackState, trackTransaction } from "./track.js";
23
+ import { storyBody, wordContext } from "./word.js";
24
+
25
+ export interface FindOptions {
26
+ /** Capitals count. Default false. */
27
+ matchCase?: boolean | undefined;
28
+ /** Only whole words (ignored when the query has a space, as in Word). Default false. */
29
+ wholeWord?: boolean | undefined;
30
+ }
31
+
32
+ /** A place the query was found. Positions are those of its tree. */
33
+ export interface FindMatch {
34
+ /** The story it is in; null: the body. */
35
+ story: string | null;
36
+ from: number;
37
+ to: number;
38
+ /** The text found, as the document has it. */
39
+ text: string;
40
+ }
41
+
42
+ /** Why a match was left as it is. */
43
+ export type ReplaceRefusal =
44
+ /** In a content control that is locked or filled from bound data. */
45
+ | "locked"
46
+ /** A control's kind does not take it, or the match runs over a control's edge. */
47
+ | "control"
48
+ /** The match runs over the edge of a field's result. */
49
+ | "field"
50
+ /** In a field's code, which shows only while codes are shown. */
51
+ | "field-code"
52
+ /** In text already deleted as a tracked change. */
53
+ | "deleted"
54
+ /** The document no longer has this text there. */
55
+ | "stale"
56
+ /** It could not be made or recorded as a tracked change. */
57
+ | "refused";
58
+
59
+ export interface ReplaceReport {
60
+ replaced: number;
61
+ refused: { match: FindMatch; reason: ReplaceRefusal }[];
62
+ }
63
+
64
+ // ---------- matching text ----------
65
+
66
+ /** What stands for something that draws but is not text: nothing matches it. */
67
+ const BARRIER = "";
68
+ /** What a plain character in a query also finds. */
69
+ const LOOSE: Readonly<Record<string, string>> = {
70
+ "‘": "'",
71
+ "’": "'",
72
+ "“": '"',
73
+ "”": '"',
74
+ " ": " ",
75
+ };
76
+ const LOOSE_CHARS = /[‘’“” ]/g;
77
+ const loosen = (text: string) => text.replace(LOOSE_CHARS, (c) => LOOSE[c] as string);
78
+ /** Letters, digits and what combines with them. */
79
+ const WORD_CHAR = /^[\p{L}\p{N}\p{M}]/u;
80
+
81
+ /** Lower case, unit for unit, so offsets stay the text's. */
82
+ function fold(text: string): string {
83
+ let out = text.toLowerCase();
84
+ if (out.length !== text.length) {
85
+ // By code point, so a capital outside the BMP still folds; one that grows stays as it is.
86
+ out = "";
87
+ for (const char of text) {
88
+ const lower = char.toLowerCase();
89
+ out += lower.length === char.length ? lower : char;
90
+ }
91
+ }
92
+ return out.replace(/ς/g, "σ"); // a final sigma is a sigma
93
+ }
94
+
95
+ interface Needle {
96
+ query: string;
97
+ text: string;
98
+ matchCase: boolean;
99
+ whole: boolean;
100
+ /** Offsets of the characters that find only themselves. */
101
+ exact: number[];
102
+ }
103
+
104
+ function needleFor(query: string, { matchCase = false, wholeWord = false }: FindOptions) {
105
+ if (!query || query.includes(BARRIER)) return null;
106
+ const plain = loosen(query);
107
+ const exact: number[] = [];
108
+ for (let i = 0; i < query.length; i++) if (query[i] !== plain[i]) exact.push(i);
109
+ const whole = wholeWord && !/\s/.test(query);
110
+ return { query, text: matchCase ? plain : fold(plain), matchCase, whole, exact } as Needle;
111
+ }
112
+
113
+ const charAfter = (text: string, at: number) =>
114
+ String.fromCodePoint(text.codePointAt(at) as number);
115
+ function charBefore(text: string, at: number): string {
116
+ const unit = text.charCodeAt(at - 1);
117
+ return unit >= 0xdc00 && unit <= 0xdfff && at > 1 ? text.slice(at - 2, at) : (text[at - 1] ?? "");
118
+ }
119
+
120
+ /** Whether no word goes on past either end of `from..to`. */
121
+ function isWhole(text: string, from: number, to: number): boolean {
122
+ if (from > 0 && WORD_CHAR.test(charAfter(text, from)) && WORD_CHAR.test(charBefore(text, from)))
123
+ return false;
124
+ return !(
125
+ to < text.length &&
126
+ WORD_CHAR.test(charBefore(text, to)) &&
127
+ WORD_CHAR.test(charAfter(text, to))
128
+ );
129
+ }
130
+
131
+ function eachHit(
132
+ raw: string,
133
+ haystack: string,
134
+ needle: Needle,
135
+ hit: (from: number, to: number) => void,
136
+ ): void {
137
+ const { text, query, exact, whole } = needle;
138
+ let at = haystack.indexOf(text);
139
+ while (at >= 0) {
140
+ const end = at + text.length;
141
+ if (exact.every((i) => raw[at + i] === query[i]) && (!whole || isWhole(raw, at, end))) {
142
+ hit(at, end);
143
+ at = haystack.indexOf(text, end);
144
+ } else at = haystack.indexOf(text, at + 1);
145
+ }
146
+ }
147
+
148
+ /** Where `query` is in a plain text, by Word's rules: `[from, to]` pairs, none overlapping. */
149
+ export function findInText(
150
+ text: string,
151
+ query: string,
152
+ options: FindOptions = {},
153
+ ): [number, number][] {
154
+ const needle = needleFor(query, options);
155
+ if (!needle) return [];
156
+ const out: [number, number][] = [];
157
+ const plain = loosen(text);
158
+ eachHit(text, needle.matchCase ? plain : fold(plain), needle, (from, to) => {
159
+ out.push([from, to]);
160
+ });
161
+ return out;
162
+ }
163
+
164
+ // ---------- what can be searched ----------
165
+
166
+ /** A stretch of a line's text and where it is in the tree. */
167
+ interface Piece {
168
+ at: number;
169
+ length: number;
170
+ pos: number;
171
+ /** A field code: one node, however long its text. */
172
+ code: boolean;
173
+ }
174
+
175
+ /** A paragraph as find sees it. */
176
+ interface Line {
177
+ text: string;
178
+ pieces: Piece[];
179
+ plain?: string;
180
+ folded?: string;
181
+ }
182
+
183
+ /** What shows, which decides what can be found. */
184
+ interface Scope {
185
+ codes: boolean;
186
+ hideDeleted: boolean;
187
+ controls: Readonly<Record<string, ControlJSON>> | undefined;
188
+ }
189
+
190
+ interface Hidden {
191
+ from: number;
192
+ to: number;
193
+ /** It shows as something else: a match cannot run across it. */
194
+ barrier: boolean;
195
+ }
196
+
197
+ const PAGE_FIELDS = new Set(["PAGE", "NUMPAGES", "SECTIONPAGES"]);
198
+ const hasMark = (node: Node, name: string) =>
199
+ node.marks.some((m) => m.type.name === name && m.attrs.value !== false);
200
+
201
+ /** What of `tree` is not on the page, in order, overlaps joined. */
202
+ function hiddenRanges(tree: Node, scope: Scope, story: boolean): Hidden[] {
203
+ const ranges: Hidden[] = [];
204
+ for (const field of fieldsIn(tree)) {
205
+ if (scope.codes) {
206
+ if (field.separator !== null)
207
+ ranges.push({ from: field.separator + 1, to: field.resultTo, barrier: false });
208
+ continue;
209
+ }
210
+ ranges.push({ from: field.from, to: field.codeEnd, barrier: false });
211
+ // The view draws these page by page: what the tree stores is not what shows.
212
+ if (story && PAGE_FIELDS.has(field.name))
213
+ ranges.push({ from: field.resultFrom, to: field.resultTo, barrier: true });
214
+ }
215
+ const { controls } = scope;
216
+ if (controls)
217
+ for (const range of controlsIn(tree))
218
+ if (Object.hasOwn(controls, range.id) && controls[range.id]?.placeholder?.showing)
219
+ ranges.push({ from: range.contentFrom, to: range.contentTo, barrier: true });
220
+ ranges.sort((a, b) => a.from - b.from);
221
+ const out: Hidden[] = [];
222
+ for (const range of ranges) {
223
+ const last = out[out.length - 1];
224
+ if (last && range.from <= last.to) {
225
+ last.to = Math.max(last.to, range.to);
226
+ last.barrier ||= range.barrier;
227
+ } else out.push({ ...range });
228
+ }
229
+ return out;
230
+ }
231
+
232
+ const known = new WeakMap<Node, { key: string; scope: Scope; lines: Line[] }>();
233
+
234
+ /** The lines of `tree`, kept while the tree and what shows stay the same (typing in the panel). */
235
+ function linesOf(tree: Node, scope: Scope, story: boolean): Line[] {
236
+ const key = `${scope.codes}|${scope.hideDeleted}`;
237
+ const cached = known.get(tree);
238
+ if (cached?.key === key && cached.scope.controls === scope.controls) return cached.lines;
239
+ const hidden = hiddenRanges(tree, scope, story);
240
+ const lines: Line[] = [];
241
+ let h = 0;
242
+ tree.descendants((node, pos) => {
243
+ if (!node.isTextblock) return true;
244
+ const pieces: Piece[] = [];
245
+ let text = "";
246
+ let walled = -1;
247
+ const add = (value: string, at: number, code = false) => {
248
+ pieces.push({ at: text.length, length: value.length, pos: at, code });
249
+ text += value;
250
+ };
251
+ node.forEach((child, offset) => {
252
+ const at = pos + 1 + offset;
253
+ while (h < hidden.length && (hidden[h] as Hidden).to <= at) h++;
254
+ const range = hidden[h];
255
+ if (range && range.from <= at) {
256
+ if (range.barrier && walled !== h) {
257
+ walled = h;
258
+ text += BARRIER;
259
+ }
260
+ return;
261
+ }
262
+ if (hasMark(child, "hidden") || (scope.hideDeleted && hasMark(child, "deletion"))) return;
263
+ const name = child.type.name;
264
+ if (child.isText) add(child.text as string, at);
265
+ else if (name === "tab") add("\t", at);
266
+ else if (name === "hardBreak") add("\n", at);
267
+ else if (name === "fieldCode" && scope.codes) add(String(child.attrs.text ?? ""), at, true);
268
+ else if (!isUnseen(child)) text += BARRIER;
269
+ });
270
+ if (text) lines.push({ text, pieces });
271
+ return false;
272
+ });
273
+ known.set(tree, { key, scope, lines });
274
+ return lines;
275
+ }
276
+
277
+ /** A found place with the stretches of the tree it covers. */
278
+ interface Hit {
279
+ match: FindMatch;
280
+ parts: { from: number; to: number; code: boolean }[];
281
+ }
282
+
283
+ function hitsIn(lines: readonly Line[], story: string | null, needle: Needle, out: Hit[]): void {
284
+ for (const line of lines) {
285
+ line.plain ??= loosen(line.text);
286
+ if (!needle.matchCase) line.folded ??= fold(line.plain);
287
+ const haystack = needle.matchCase ? line.plain : (line.folded as string);
288
+ if (haystack.length < needle.text.length) continue;
289
+ eachHit(line.text, haystack, needle, (a, b) => {
290
+ const parts: Hit["parts"] = [];
291
+ for (const { at, length, pos, code } of line.pieces) {
292
+ const start = Math.max(a, at);
293
+ const end = Math.min(b, at + length);
294
+ if (start >= end) continue;
295
+ if (code) parts.push({ from: pos, to: pos + 1, code });
296
+ else parts.push({ from: pos + start - at, to: pos + end - at, code });
297
+ }
298
+ const first = parts[0];
299
+ const last = parts[parts.length - 1];
300
+ if (!first || !last) return;
301
+ const match = { story, from: first.from, to: last.to, text: line.text.slice(a, b) };
302
+ out.push({ match, parts });
303
+ });
304
+ }
305
+ }
306
+
307
+ /** The body's state of `target`, whichever of its editors it is. */
308
+ const bodyState = (state: EditorState) => storyBody(state)?.state ?? state;
309
+
310
+ const scopeOf = (body: EditorState): Scope => {
311
+ const view = trackState(body)?.view ?? "markup";
312
+ return {
313
+ codes: fieldCodesShown(body),
314
+ hideDeleted: view !== "markup",
315
+ controls: wordContext(body)?.envelope.controls,
316
+ };
317
+ };
318
+
319
+ /** The trees searched: the body, then the stories that hold text (no note separators). */
320
+ function treesOf(body: EditorState): { id: string | null; tree: Node }[] {
321
+ const stories = wordContext(body)?.stories ?? new Map();
322
+ return [
323
+ { id: null, tree: body.doc },
324
+ ...[...stories]
325
+ .filter(([, story]) => !story.noteType)
326
+ .map(([id, story]) => ({ id: id as string, tree: story.doc as Node })),
327
+ ];
328
+ }
329
+
330
+ function hitsOf(body: EditorState, query: string, options: FindOptions): Hit[] {
331
+ const needle = needleFor(query, options);
332
+ if (!needle) return [];
333
+ const scope = scopeOf(body);
334
+ const out: Hit[] = [];
335
+ for (const { id, tree } of treesOf(body))
336
+ hitsIn(linesOf(tree, scope, id !== null), id, needle, out);
337
+ return out;
338
+ }
339
+
340
+ /**
341
+ * Every place `query` is, in the body then in each story, as the document shows now: a field's
342
+ * code only while codes are shown (its result then not), text deleted as a tracked change only in
343
+ * the `markup` review view, no control's placeholder, no hidden text. A `document` is read as an
344
+ * editor would load it, with those at their defaults.
345
+ */
346
+ export function findAll(
347
+ target: Editor | EditorDocument,
348
+ query: string,
349
+ options: FindOptions = {},
350
+ ): FindMatch[] {
351
+ const editor = "getDocument" in target ? target : createEditor({ document: target });
352
+ return hitsOf(bodyState(editor.state), query, options).map((hit) => hit.match);
353
+ }
354
+
355
+ // ---------- replacing ----------
356
+
357
+ /** The replacement as Word writes it over `found`: its capitals followed. */
358
+ function withCaseOf(found: string, text: string): string {
359
+ const first = found[0] ?? "";
360
+ if (first === first.toLowerCase() || !text) return text;
361
+ if (found === found.toUpperCase()) return text.toUpperCase();
362
+ return (text[0] as string).toUpperCase() + text.slice(1);
363
+ }
364
+
365
+ /** Control characters other than tab and line ends cannot be in a Word file. */
366
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: that is what it removes
367
+ const cleaned = (text: string) => text.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "");
368
+
369
+ /** Puts `text` where `hit` is: in its first stretch, with that stretch's marks. */
370
+ function applyHit(tr: Transaction, { parts }: Hit, text: string): number {
371
+ const first = parts[0] as Hit["parts"][number];
372
+ for (const part of parts.slice(1).reverse()) tr.delete(part.from, part.to);
373
+ const marks = withoutReview(tr.doc.nodeAt(first.from)?.marks ?? []);
374
+ const nodes = inlineText(tr.doc.type.schema, text, marks);
375
+ tr.replace(first.from, first.to, new Slice(Fragment.fromArray(nodes), 0, 0));
376
+ return first.from + nodes.reduce((size, node) => size + node.nodeSize, 0);
377
+ }
378
+
379
+ /** Why `hit` may not be replaced in `state` (its tree's), if so. */
380
+ function refusalOf(state: EditorState, scope: Scope, hit: Hit, text: string) {
381
+ const tree = state.doc;
382
+ const { parts, match } = hit;
383
+ if (parts.some((part) => part.code)) return "field-code";
384
+ if (parts.some((part) => tree.nodeAt(part.from)?.marks.some((m) => m.type.name === "deletion")))
385
+ return "deleted";
386
+ const first = parts[0] as Hit["parts"][number];
387
+ if (parts.length > 1) {
388
+ const field = fieldAround(tree, first.from);
389
+ if (parts.some((part) => fieldAround(tree, part.from) !== field)) return "field";
390
+ const control = controlAt(tree, first.from);
391
+ if (parts.some((part) => controlAt(tree, part.from) !== control)) return "control";
392
+ }
393
+ if (!controlAt(tree, first.from)) return null;
394
+ if (readOnlyAt(tree, scope.controls, match.from, match.to)) return "locked";
395
+ // What else a control takes is the filter's to say.
396
+ const tr = state.tr;
397
+ applyHit(tr, hit, text);
398
+ const made = trackTransaction(state, tr);
399
+ return made && state.applyTransaction(made).transactions.length ? null : "control";
400
+ }
401
+
402
+ /** Replaces `hits` tree by tree in one undo step; `after`: a caret after the single one. */
403
+ function replaceHits(
404
+ editor: Editor,
405
+ hits: readonly Hit[],
406
+ text: string,
407
+ matchCase: boolean,
408
+ caretAfter: boolean,
409
+ ): ReplaceReport {
410
+ const body = bodyState(editor.state);
411
+ const scope = scopeOf(body);
412
+ const report: ReplaceReport = { replaced: 0, refused: [] };
413
+ const value = cleaned(text);
414
+ const textOf = (hit: Hit) => (matchCase ? value : withCaseOf(hit.match.text, value));
415
+ const byTree = new Map<string | null, Hit[]>();
416
+ for (const hit of hits) {
417
+ const { story } = hit.match;
418
+ const state = story === null ? body : editor.story(story)?.state;
419
+ const reason = state ? refusalOf(state, scope, hit, textOf(hit)) : "stale";
420
+ if (reason) report.refused.push({ match: hit.match, reason });
421
+ else byTree.set(story, [...(byTree.get(story) ?? []), hit]);
422
+ }
423
+ const edits = new Map<string | null, (tr: Transaction) => void>();
424
+ for (const [story, list] of byTree)
425
+ edits.set(story, (tr) => {
426
+ let caret = 0;
427
+ for (const hit of [...list].reverse()) caret = applyHit(tr, hit, textOf(hit));
428
+ if (caretAfter) tr.setSelection(TextSelection.create(tr.doc, caret));
429
+ });
430
+ const failed = edits.size ? editTrees(editor, edits, { tracked: true }) : new Set();
431
+ for (const [story, list] of byTree) {
432
+ if (failed.has(story))
433
+ report.refused.push(...list.map((hit) => ({ match: hit.match, reason: "refused" as const })));
434
+ else report.replaced += list.length;
435
+ }
436
+ return report;
437
+ }
438
+
439
+ /**
440
+ * Replaces one match found by `findAll`: tracked when tracking is on, in the formatting of the
441
+ * match's first character, its capitals followed unless `matchCase`. Anything between its pieces
442
+ * that draws nothing (a bookmark, a comment's anchor) stays. A line feed in `text` makes a line
443
+ * break, a tab a tab. The caret goes after it. One undo step.
444
+ */
445
+ export function replace(
446
+ editor: Editor,
447
+ match: FindMatch,
448
+ text: string,
449
+ { matchCase = false }: Pick<FindOptions, "matchCase"> = {},
450
+ ): ReplaceReport {
451
+ const body = bodyState(editor.state);
452
+ const needle = needleFor(match.text, { matchCase: true }) as Needle | null;
453
+ const tree = match.story === null ? body.doc : wordContext(body)?.stories.get(match.story)?.doc;
454
+ const hits: Hit[] = [];
455
+ if (needle && tree)
456
+ hitsIn(linesOf(tree, scopeOf(body), match.story !== null), match.story, needle, hits);
457
+ const hit = hits.find((h) => h.match.from === match.from && h.match.to === match.to);
458
+ if (!hit) return { replaced: 0, refused: [{ match, reason: "stale" }] };
459
+ return replaceHits(editor, [hit], text, matchCase, true);
460
+ }
461
+
462
+ /**
463
+ * Replaces every match of `query`, in the body and every story, as one undo step. What may not be
464
+ * replaced stays and is in `refused`, with why.
465
+ */
466
+ export function replaceAll(
467
+ editor: Editor,
468
+ query: string,
469
+ text: string,
470
+ options: FindOptions = {},
471
+ ): ReplaceReport {
472
+ const hits = hitsOf(bodyState(editor.state), query, options);
473
+ return replaceHits(editor, hits, text, options.matchCase === true, false);
474
+ }
475
+
476
+ /** The story `editor` edits; null for the body's. */
477
+ export function storyOfEditor(editor: Editor): string | null {
478
+ const body = storyBody(editor.state)?.state;
479
+ return body ? storyIdOf(body, editor.state.doc) : null;
480
+ }
481
+
482
+ /**
483
+ * The match to go to from the selection of the story open (or the body): the next, or with
484
+ * `backward` the previous, around the end of the document.
485
+ */
486
+ export function nextMatch(
487
+ editor: Editor,
488
+ matches: readonly FindMatch[],
489
+ backward = false,
490
+ ): FindMatch | null {
491
+ if (!matches.length) return null;
492
+ const open = editor.storyView?.open?.id ?? storyOfEditor(editor);
493
+ const body = bodyState(editor.state);
494
+ const order = new Map(treesOf(body).map(({ id }, i) => [id, i]));
495
+ const rank = (story: string | null) => order.get(story) ?? -1;
496
+ const state = (open && editor.story(open)?.state) || body;
497
+ const here = rank(open);
498
+ const { from, to } = state.selection;
499
+ const after = (m: FindMatch) => {
500
+ const tree = rank(m.story);
501
+ return tree > here || (tree === here && m.from >= to);
502
+ };
503
+ const before = (m: FindMatch) => {
504
+ const tree = rank(m.story);
505
+ return tree < here || (tree === here && m.to <= from);
506
+ };
507
+ if (backward)
508
+ return [...matches].reverse().find(before) ?? (matches[matches.length - 1] as FindMatch);
509
+ return matches.find(after) ?? (matches[0] as FindMatch);
510
+ }
@@ -4,6 +4,7 @@ import { AddMarkStep, RemoveMarkStep, ReplaceStep, type Step } from "../transfor
4
4
  import { TransformError } from "../transform/transform.js";
5
5
  import { Selection, type SelectionJSON } from "./selection.js";
6
6
  import { type Command, type EditorState, Plugin, PluginKey, type Transaction } from "./state.js";
7
+ import { StoryStep, storedStepsApply, storyBody, wordContext } from "./word.js";
7
8
 
8
9
  /** One undoable unit: inverted steps in the order they apply, and the selection to restore. */
9
10
  interface HistoryEvent {
@@ -20,6 +21,8 @@ interface HistoryState {
20
21
  /** Time and changed ranges (in current-document positions) of the last recorded change. */
21
22
  readonly prevTime: number;
22
23
  readonly prevRanges: readonly number[] | null;
24
+ /** The story `prevRanges` are positions of (ADR-0007); none: the body. */
25
+ readonly prevStory?: string | null;
23
26
  }
24
27
 
25
28
  export interface HistoryOptions {
@@ -36,6 +39,19 @@ const historyOp = "historyOp";
36
39
  /** Set this meta on a transaction to make it an undo step of its own (no merging either side). */
37
40
  export const closeHistory = "closeHistory";
38
41
 
42
+ /** Set this meta on a transaction to make it part of the undo step before it. */
43
+ export const joinHistory = "joinHistory";
44
+
45
+ /**
46
+ * On a body transaction carrying a story's change: the story's id and its own transaction, which
47
+ * decides what typing joins, as the body's does for body typing.
48
+ */
49
+ export const storyEdit = "storyEdit";
50
+ export interface StoryEdit {
51
+ id: string;
52
+ tr: Transaction;
53
+ }
54
+
39
55
  const EMPTY: HistoryState = { done: [], undone: [], prevTime: 0, prevRanges: null };
40
56
 
41
57
  /**
@@ -84,12 +100,15 @@ export function history({ newGroupDelay = 500, depth = 100 }: HistoryOptions = {
84
100
  }
85
101
 
86
102
  const last = hist.done[hist.done.length - 1];
103
+ const story = tr.getMeta(storyEdit) as StoryEdit | undefined;
87
104
  const merge =
88
105
  last !== undefined &&
89
106
  (root !== undefined ||
107
+ tr.getMeta(joinHistory) === true ||
90
108
  (!tr.getMeta(closeHistory) &&
91
109
  tr.time - hist.prevTime < newGroupDelay &&
92
- isAdjacent(hist.prevRanges, tr)));
110
+ (hist.prevStory ?? null) === (story?.id ?? null) &&
111
+ isAdjacent(hist.prevRanges, story?.tr ?? tr)));
93
112
  const done = merge
94
113
  ? [
95
114
  ...hist.done.slice(0, -1),
@@ -101,18 +120,26 @@ export function history({ newGroupDelay = 500, depth = 100 }: HistoryOptions = {
101
120
  undone: [],
102
121
  // A closed change is a step of its own on both sides: what follows does not join it.
103
122
  prevTime: root ? hist.prevTime : tr.getMeta(closeHistory) ? 0 : tr.time,
104
- prevRanges: root ? mapRanges(hist.prevRanges, tr.mapping) : changedRanges(tr),
123
+ prevRanges: root
124
+ ? mapRanges(hist.prevRanges, tr.mapping)
125
+ : changedRanges(story?.tr ?? tr),
126
+ prevStory: root ? (hist.prevStory ?? null) : (story?.id ?? null),
105
127
  };
106
128
  },
107
129
  },
108
130
  });
109
131
  }
110
132
 
111
- /** Puts `inverted` (applied first) before `steps`, merging adjacent replace steps (typing runs). */
133
+ /** Puts `inverted` (applied first) before `steps`, merging adjacent steps (typing runs). */
112
134
  function prepend(inverted: readonly Step[], steps: readonly Step[]): Step[] {
113
135
  const last = inverted[inverted.length - 1];
114
136
  const first = steps[0];
115
- const merged = last instanceof ReplaceStep && first ? last.merge(first) : null;
137
+ const merged =
138
+ last instanceof ReplaceStep && first
139
+ ? last.merge(first)
140
+ : last instanceof StoryStep && first instanceof StoryStep
141
+ ? last.merge(first)
142
+ : null;
116
143
  return merged ? [...inverted.slice(0, -1), merged, ...steps.slice(1)] : [...inverted, ...steps];
117
144
  }
118
145
 
@@ -261,13 +288,29 @@ function applyStored(tr: Transaction, step: Step): boolean {
261
288
  }
262
289
 
263
290
  function historyCommand(redo: boolean): Command {
264
- return (state, dispatch) => {
291
+ const command: Command = (state, dispatch) => {
292
+ // One history, the body's: a story's editor has none of its own.
293
+ const body = storyBody(state);
294
+ if (body) return dispatch ? body.run(command) : body.can(command);
265
295
  const hist = historyKey.getState(state);
266
296
  const source = hist && (redo ? hist.undone : hist.done);
267
297
  const event = source?.[source.length - 1];
268
298
  if (!hist || !source || !event) return false;
269
299
  if (dispatch) {
270
300
  const tr = state.tr;
301
+ // The envelope changed outside history: the event is dropped whole, never half applied.
302
+ const context = wordContext(state);
303
+ if (context && !storedStepsApply(context, event.steps)) {
304
+ const rest = source.slice(0, -1);
305
+ tr.setMeta(historyKey, {
306
+ done: redo ? hist.done : rest,
307
+ undone: redo ? rest : hist.undone,
308
+ prevTime: 0,
309
+ prevRanges: null,
310
+ } satisfies HistoryState);
311
+ dispatch(tr);
312
+ return true;
313
+ }
271
314
  // Rebasing keeps stored steps applicable; should one still fail, later steps are remapped
272
315
  // as if it never existed rather than applied at positions that assumed it.
273
316
  let remap: RebaseMapping | null = null;
@@ -297,15 +340,16 @@ function historyCommand(redo: boolean): Command {
297
340
  }
298
341
  return true;
299
342
  };
343
+ return command;
300
344
  }
301
345
 
302
346
  export const undo: Command = historyCommand(false);
303
347
  export const redo: Command = historyCommand(true);
304
348
 
305
349
  export function undoDepth(state: EditorState): number {
306
- return historyKey.getState(state)?.done.length ?? 0;
350
+ return historyKey.getState(storyBody(state)?.state ?? state)?.done.length ?? 0;
307
351
  }
308
352
 
309
353
  export function redoDepth(state: EditorState): number {
310
- return historyKey.getState(state)?.undone.length ?? 0;
354
+ return historyKey.getState(storyBody(state)?.state ?? state)?.undone.length ?? 0;
311
355
  }