@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
@@ -5,6 +5,8 @@ export {
5
5
  deleteBackward,
6
6
  deleteForward,
7
7
  deleteSelection,
8
+ deleteSelectionKeepingTables,
9
+ insertColumnBreak,
8
10
  insertHardBreak,
9
11
  insertPageBreak,
10
12
  insertTab,
@@ -28,14 +30,82 @@ export {
28
30
  replyToComment,
29
31
  resolveComment,
30
32
  } from "./comments.js";
33
+ export {
34
+ addRepeatingItem,
35
+ type ControlInsertOptions,
36
+ type ControlPropertiesPatch,
37
+ type ControlRange,
38
+ type ControlValue,
39
+ type ControlValueInput,
40
+ controlAt,
41
+ controlIsReadOnly,
42
+ controlProperties,
43
+ controlSpot,
44
+ controlsIn,
45
+ controlValues,
46
+ insertControl,
47
+ insertControlText,
48
+ setControlProperties,
49
+ setControlValue,
50
+ } from "./controls.js";
31
51
  export {
32
52
  createEditor,
53
+ type DocumentTarget,
33
54
  type Editor,
34
55
  type EditorDocument,
35
56
  type EditorListener,
36
57
  type EditorOptions,
58
+ type FoundMatches,
59
+ type NavigationRequest,
60
+ type OpenStory,
61
+ type StoryView,
37
62
  sectionSettings,
38
63
  } from "./editor.js";
64
+ export {
65
+ caretStop,
66
+ type Field,
67
+ type FieldDisplay,
68
+ fieldAround,
69
+ fieldCodesShown,
70
+ fieldDisplay,
71
+ fieldsIn,
72
+ sameSpot,
73
+ toggleFieldCodes,
74
+ } from "./fields.js";
75
+ export {
76
+ type CrossReference,
77
+ type CrossReferenceTargets,
78
+ crossReferenceTargets,
79
+ type FieldInstruction,
80
+ type FieldLayout,
81
+ type FieldPage,
82
+ type FieldSkip,
83
+ type FieldSkipReason,
84
+ type FieldsReport,
85
+ formatDatePicture,
86
+ formatNumericPicture,
87
+ type InsertFieldOptions,
88
+ insertCrossReference,
89
+ insertDate,
90
+ insertField,
91
+ insertPageNumber,
92
+ insertTableOfContents,
93
+ parseFieldInstruction,
94
+ type TableOfContentsOptions,
95
+ type UpdateFieldsOptions,
96
+ updateFields,
97
+ } from "./fieldupdate.js";
98
+ export {
99
+ type FindMatch,
100
+ type FindOptions,
101
+ findAll,
102
+ findInText,
103
+ nextMatch,
104
+ type ReplaceRefusal,
105
+ type ReplaceReport,
106
+ replace,
107
+ replaceAll,
108
+ } from "./find.js";
39
109
  export {
40
110
  alignAt,
41
111
  colorAt,
@@ -47,6 +117,7 @@ export {
47
117
  closeHistory,
48
118
  type HistoryOptions,
49
119
  history,
120
+ joinHistory,
50
121
  redo,
51
122
  redoDepth,
52
123
  undo,
@@ -74,6 +145,41 @@ export {
74
145
  wrapInList,
75
146
  } from "./lists.js";
76
147
  export { typedMarks } from "./mark.js";
148
+ export {
149
+ type BookmarkInfo,
150
+ type BookmarkResult,
151
+ deleteBookmark,
152
+ documentOutline,
153
+ goTo,
154
+ insertBookmark,
155
+ isBookmarkName,
156
+ listBookmarks,
157
+ type OutlineEntry,
158
+ renameBookmark,
159
+ } from "./navigation.js";
160
+ export {
161
+ convertNotes,
162
+ type InsertNoteOptions,
163
+ insertNote,
164
+ isNote,
165
+ type NoteKind,
166
+ type NoteNumber,
167
+ type NoteNumberOptions,
168
+ noteAtSelection,
169
+ noteKindOf,
170
+ noteNumbers,
171
+ noteProperties,
172
+ noteTexts,
173
+ referencesIn,
174
+ setNoteProperties,
175
+ } from "./notes.js";
176
+ export {
177
+ insertPicture,
178
+ type NewPicture,
179
+ selectedPicture,
180
+ setPictureAlt,
181
+ setPictureSize,
182
+ } from "./pictures.js";
77
183
  export {
78
184
  acceptAllChanges,
79
185
  acceptChange,
@@ -86,6 +192,26 @@ export {
86
192
  rejectChange,
87
193
  trackedChanges,
88
194
  } from "./review.js";
195
+ export {
196
+ documentSections,
197
+ ensureStory,
198
+ insertSectionBreak,
199
+ pageVariant,
200
+ removeSectionBreak,
201
+ type SectionAt,
202
+ type SectionBreakKind,
203
+ type SectionColumns,
204
+ type SectionSetup,
205
+ type StorySide,
206
+ type StoryVariant,
207
+ sectionAt,
208
+ sectionColumns,
209
+ setDifferentEvenPages,
210
+ setDifferentFirstPage,
211
+ setSectionSetup,
212
+ setStoryLinked,
213
+ storyOfSection,
214
+ } from "./sections.js";
89
215
  export {
90
216
  AllSelection,
91
217
  marksAt,
@@ -104,6 +230,32 @@ export {
104
230
  type PluginSpec,
105
231
  Transaction,
106
232
  } from "./state.js";
233
+ export {
234
+ deleteColumns,
235
+ deleteRows,
236
+ deleteTable,
237
+ insertColumn,
238
+ insertRow,
239
+ insertTable,
240
+ isHeaderRow,
241
+ mergeCells,
242
+ setCellShading,
243
+ setColumnWidth,
244
+ setTableStyle,
245
+ splitCell,
246
+ tableStyleAt,
247
+ tableStyles,
248
+ toggleHeaderRow,
249
+ } from "./tablecommands.js";
250
+ export {
251
+ CellSelection,
252
+ cellsAsTable,
253
+ extendCellSelection,
254
+ goToCell,
255
+ goToCellVertically,
256
+ keepTablesApart,
257
+ pasteCells,
258
+ } from "./tables.js";
107
259
  export {
108
260
  type ReviewView,
109
261
  setReviewView,
@@ -115,7 +267,11 @@ export {
115
267
  } from "./track.js";
116
268
  export {
117
269
  CommentStep,
270
+ EnvelopeStep,
271
+ type Story,
272
+ StoryStep,
118
273
  setComments,
274
+ storyBody,
119
275
  type WordContext,
120
276
  type WordEnvelope,
121
277
  withEnvelope,
@@ -123,6 +279,7 @@ export {
123
279
  } from "./word.js";
124
280
  export {
125
281
  copiedDefinitions,
282
+ type FittedPaste,
126
283
  fitPaste,
127
284
  fitPastedV2,
128
285
  type WordDefinitions,
@@ -4,6 +4,7 @@ import { TransformError } from "../transform/transform.js";
4
4
  import { attempt } from "./attempt.js";
5
5
  import { AllSelection, marksAt, TextSelection } from "./selection.js";
6
6
  import type { Command, EditorState, Transaction } from "./state.js";
7
+ import { CellSelection } from "./tables.js";
7
8
  import { styleLink, unstyleLink } from "./wordformat.js";
8
9
 
9
10
  const EMAIL = /^[^\s@/:]+@[^\s@/:]+\.\p{L}{2,}$/iu;
@@ -78,10 +79,11 @@ function canLink(state: EditorState, type: MarkType): boolean {
78
79
  return parent.inlineContent && parent.type.allowsMarkType(type);
79
80
  }
80
81
  let found = false;
81
- state.doc.nodesBetween(selection.from, selection.to, (node) => {
82
- if (node.isTextblock && node.type.allowsMarkType(type)) found = true;
83
- return !found;
84
- });
82
+ for (const { from, to } of selection.ranges)
83
+ state.doc.nodesBetween(from, to, (node) => {
84
+ if (node.isTextblock && node.type.allowsMarkType(type)) found = true;
85
+ return !found;
86
+ });
85
87
  return found;
86
88
  }
87
89
 
@@ -97,13 +99,14 @@ export function linkAt(state: EditorState): string | null {
97
99
  return (linkAround(selection.$from, type)?.mark.attrs.href as string) ?? null;
98
100
  // undefined: no text seen yet; null: text without a link, or with another one.
99
101
  let href = undefined as string | null | undefined;
100
- state.doc.nodesBetween(selection.from, selection.to, (node, _pos, parent) => {
101
- if (href === null) return false;
102
- if (!node.isInline || !parent?.type.allowsMarkType(type)) return undefined;
103
- const value = (type.isInSet(node.marks)?.attrs.href as string | undefined) ?? null;
104
- href = href === undefined || href === value ? value : null;
105
- return false;
106
- });
102
+ for (const { from, to } of selection.ranges)
103
+ state.doc.nodesBetween(from, to, (node, _pos, parent) => {
104
+ if (href === null) return false;
105
+ if (!node.isInline || !parent?.type.allowsMarkType(type)) return undefined;
106
+ const value = (type.isInSet(node.marks)?.attrs.href as string | undefined) ?? null;
107
+ href = href === undefined || href === value ? value : null;
108
+ return false;
109
+ });
107
110
  return href ?? null;
108
111
  }
109
112
 
@@ -118,6 +121,8 @@ export function insertLink(href: string, text?: string): Command {
118
121
  const label = text ?? normalized;
119
122
  const { selection } = state;
120
123
  if (!type || !label || !isSafeHref(normalized)) return false;
124
+ // Selected cells are linked by `setLink`, never replaced by one link.
125
+ if (selection instanceof CellSelection) return false;
121
126
  if (!(selection instanceof AllSelection) && !canLink(state, type)) return false;
122
127
  const link = type.create({ href: normalized });
123
128
  return attempt(state, dispatch, (tr) => {
@@ -150,8 +155,10 @@ export function setLink(href: string): Command {
150
155
  const { selection } = state;
151
156
  if (!selection.empty) {
152
157
  return attempt(state, dispatch, (tr) => {
153
- tr.addMark(selection.from, selection.to, mark);
154
- styleLink(tr, state, selection.from, selection.to);
158
+ for (const { from, to } of selection.ranges) {
159
+ tr.addMark(from, to, mark);
160
+ styleLink(tr, state, from, to);
161
+ }
155
162
  });
156
163
  }
157
164
  const around = linkAround(selection.$from, type);
@@ -165,11 +172,14 @@ export const removeLink: Command = (state, dispatch) => {
165
172
  const type = linkType(state);
166
173
  if (!type) return false;
167
174
  const { selection } = state;
168
- const range = selection.empty ? linkAround(selection.$from, type) : selection;
169
- if (!range) return false;
175
+ const around = selection.empty && linkAround(selection.$from, type);
176
+ const ranges = selection.empty ? (around ? [around] : []) : selection.ranges;
177
+ if (!ranges.length) return false;
170
178
  return attempt(state, dispatch, (tr) => {
171
- tr.removeMark(range.from, range.to, type);
172
- unstyleLink(tr, state, range.from, range.to);
179
+ for (const range of ranges) {
180
+ tr.removeMark(range.from, range.to, type);
181
+ unstyleLink(tr, state, range.from, range.to);
182
+ }
173
183
  });
174
184
  };
175
185
 
package/src/state/mark.ts CHANGED
@@ -14,7 +14,14 @@ import type { Transform } from "../transform/transform.js";
14
14
  export const MARK_ATTRS = ["section", "revision", "formatChange", "attributes"] as const;
15
15
 
16
16
  /** Inline nodes that stand between runs: bookmarks and comment ranges. */
17
- const MARKERS = new Set(["bookmarkStart", "bookmarkEnd", "commentStart", "commentEnd"]);
17
+ const MARKERS = new Set([
18
+ "bookmarkStart",
19
+ "bookmarkEnd",
20
+ "commentStart",
21
+ "commentEnd",
22
+ "controlStart",
23
+ "controlEnd",
24
+ ]);
18
25
 
19
26
  /**
20
27
  * After a join, or a deletion across paragraphs, the merged paragraph at `pos` ends with the
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Going places in a document (11.11): bookmarks with Word's rules for their names, and the outline.
3
+ * Bookmarks are not tracked (Word does not track them) and their ids are unique over the body and
4
+ * every story.
5
+ */
6
+ import { Fragment, type Mark, type Node, type NodeType, Slice } from "../model/index.js";
7
+ import { formatNumber } from "../v3/resolve.js";
8
+ import type { DocumentTarget, Editor } from "./editor.js";
9
+ import { fieldsIn } from "./fields.js";
10
+ import {
11
+ bookmarkContent,
12
+ bookmarksIn,
13
+ entryTitle,
14
+ type FieldLayout,
15
+ headingLevel,
16
+ nextBookmarkId,
17
+ paragraphsOf,
18
+ } from "./fieldupdate.js";
19
+ import { storyOfEditor } from "./find.js";
20
+ import { TextSelection } from "./selection.js";
21
+ import type { EditorState, Transaction } from "./state.js";
22
+ import { editTrees } from "./stories.js";
23
+ import { storyBody, wordContext } from "./word.js";
24
+
25
+ /** A letter, then letters, digits and `_`; at most 40 (what Word takes). */
26
+ const NAME = /^\p{L}[\p{L}\p{N}_]{0,39}$/u;
27
+
28
+ /** Whether Word takes `name` for a bookmark made by hand. */
29
+ export const isBookmarkName = (name: string): boolean => NAME.test(name);
30
+
31
+ export interface BookmarkInfo {
32
+ name: string;
33
+ /** The story it is in; null: the body. */
34
+ story: string | null;
35
+ /** After its start marker, before its end marker. */
36
+ from: number;
37
+ to: number;
38
+ /** The text it holds. */
39
+ text: string;
40
+ /** Word's own (`_Toc…`, `_Ref…`, `_GoBack`): not listed unless asked for. */
41
+ hidden: boolean;
42
+ }
43
+
44
+ export type BookmarkResult =
45
+ | { ok: true; bookmark: BookmarkInfo }
46
+ | {
47
+ ok: false;
48
+ /**
49
+ * `invalid-name`: not a name Word takes. `no-place`: the selection is not in text.
50
+ * `missing`: no bookmark has that name. `exists`: another one does. `refused`: the content
51
+ * there cannot change (a locked control).
52
+ */
53
+ reason: "invalid-name" | "no-place" | "missing" | "exists" | "refused";
54
+ };
55
+
56
+ const bodyOf = (state: EditorState) => storyBody(state)?.state ?? state;
57
+
58
+ function treesOf(state: EditorState): { id: string | null; tree: Node }[] {
59
+ const body = bodyOf(state);
60
+ return [
61
+ { id: null, tree: body.doc },
62
+ ...[...(wordContext(body)?.stories ?? [])].map(([id, story]) => ({ id, tree: story.doc })),
63
+ ];
64
+ }
65
+
66
+ /** The document's bookmarks, the body's first; Word's hidden ones only with `hidden`. */
67
+ export function listBookmarks(
68
+ target: Editor | EditorState,
69
+ { hidden = false }: { hidden?: boolean } = {},
70
+ ): BookmarkInfo[] {
71
+ return treesOf("getDocument" in target ? target.state : target).flatMap(({ id, tree }) =>
72
+ [...bookmarksIn(tree).values()].flatMap((mark) => {
73
+ const secret = mark.name.startsWith("_");
74
+ if (secret && !hidden) return [];
75
+ const text = bookmarkContent(tree, mark)
76
+ .map((node) => node.text ?? " ")
77
+ .join("");
78
+ return [{ ...mark, story: id, text, hidden: secret }];
79
+ }),
80
+ );
81
+ }
82
+
83
+ const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
84
+
85
+ /** The positions of `name`'s markers in `tree`, either end. */
86
+ function markersOf(tree: Node, name: string): number[] {
87
+ const ids = new Set<unknown>();
88
+ const out: number[] = [];
89
+ tree.descendants((node, pos) => {
90
+ if (node.type.name === "bookmarkStart" && same(String(node.attrs.name), name)) {
91
+ ids.add(node.attrs.id);
92
+ out.push(pos);
93
+ } else if (node.type.name === "bookmarkEnd" && ids.has(node.attrs.id)) out.push(pos);
94
+ return !node.isInline;
95
+ });
96
+ return out;
97
+ }
98
+
99
+ const find = (editor: Editor, name: string) =>
100
+ listBookmarks(editor, { hidden: true }).find((b) => same(b.name, name));
101
+
102
+ const result = (editor: Editor, name: string, failed: Set<unknown>): BookmarkResult => {
103
+ const bookmark = failed.size ? undefined : find(editor, name);
104
+ return bookmark ? { ok: true, bookmark } : { ok: false, reason: "refused" };
105
+ };
106
+
107
+ /**
108
+ * A bookmark over the selection or `range` of `editor`'s tree (a caret: a point). As in Word, a
109
+ * name already used, in any case and any story, moves that bookmark here.
110
+ */
111
+ export function insertBookmark(
112
+ editor: Editor,
113
+ name: string,
114
+ range?: { from: number; to: number },
115
+ ): BookmarkResult {
116
+ if (!isBookmarkName(name)) return { ok: false, reason: "invalid-name" };
117
+ const { state } = editor;
118
+ const { from, to } = range ?? state.selection;
119
+ const size = state.doc.content.size;
120
+ if (from < 0 || to > size || from > to) return { ok: false, reason: "no-place" };
121
+ if (![from, to].every((pos) => state.doc.resolve(pos).parent.inlineContent))
122
+ return { ok: false, reason: "no-place" };
123
+ const here = storyOfEditor(editor);
124
+ const edits = new Map<string | null, (tr: Transaction) => void>();
125
+ for (const { id, tree } of treesOf(state)) {
126
+ const old = markersOf(tree, name);
127
+ if (id !== here && !old.length) continue;
128
+ edits.set(id, (tr) => {
129
+ const { bookmarkStart, bookmarkEnd } = tr.doc.type.schema.nodes as Record<string, NodeType>;
130
+ const mark = id === here ? nextBookmarkId(state, tr) : 0;
131
+ // From the end back, so positions hold; at one place the old goes first, the start ends first.
132
+ const steps: { pos: number; rank: number; run: () => void }[] = old.map((pos) => ({
133
+ pos,
134
+ rank: 0,
135
+ run: () => tr.delete(pos, pos + 1),
136
+ }));
137
+ if (id === here)
138
+ steps.push(
139
+ {
140
+ pos: to,
141
+ rank: 1,
142
+ run: () => tr.insert(to, (bookmarkEnd as NodeType).create({ id: mark })),
143
+ },
144
+ {
145
+ pos: from,
146
+ rank: 2,
147
+ run: () => tr.insert(from, (bookmarkStart as NodeType).create({ id: mark, name })),
148
+ },
149
+ );
150
+ steps.sort((a, b) => b.pos - a.pos || a.rank - b.rank);
151
+ for (const step of steps) step.run();
152
+ });
153
+ }
154
+ return result(editor, name, editTrees(editor, edits, { tracked: false }));
155
+ }
156
+
157
+ const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
158
+
159
+ /** Word's field names: a code starting with one is that field, never a bookmark standing for `REF`. */
160
+ const FIELD_NAMES = new Set(
161
+ (
162
+ "ADDRESSBLOCK ADVANCE ASK AUTHOR AUTONUM AUTONUMLGL AUTONUMOUT AUTOTEXT AUTOTEXTLIST BARCODE " +
163
+ "BIBLIOGRAPHY BIDIOUTLINE CITATION COMMENTS COMPARE CREATEDATE DATABASE DATE DISPLAYBARCODE " +
164
+ "DOCPROPERTY DOCVARIABLE EDITTIME EQ FILENAME FILESIZE FILLIN FORMCHECKBOX FORMDROPDOWN " +
165
+ "FORMTEXT GOTOBUTTON GREETINGLINE HYPERLINK IF INCLUDEPICTURE INCLUDETEXT INDEX INFO KEYWORDS " +
166
+ "LASTSAVEDBY LINK LISTNUM MACROBUTTON MERGEBARCODE MERGEFIELD MERGEREC MERGESEQ NEXT NEXTIF " +
167
+ "NOTEREF NUMCHARS NUMPAGES NUMWORDS PAGE PAGEREF PRINT PRINTDATE PRIVATE QUOTE RD REF REVNUM " +
168
+ "SAVEDATE SECTION SECTIONPAGES SEQ SET SKIPIF STYLEREF SUBJECT SYMBOL TA TC TEMPLATE TIME " +
169
+ "TITLE TOA TOC USERADDRESS USERINITIALS USERNAME XE"
170
+ ).split(" "),
171
+ );
172
+
173
+ /** Renames a bookmark, and what refers to it: `REF`, `PAGEREF`, `NOTEREF` and links. */
174
+ export function renameBookmark(editor: Editor, name: string, next: string): BookmarkResult {
175
+ if (!isBookmarkName(next)) return { ok: false, reason: "invalid-name" };
176
+ const current = find(editor, name);
177
+ if (!current) return { ok: false, reason: "missing" };
178
+ const taken = find(editor, next);
179
+ if (taken && !same(taken.name, name)) return { ok: false, reason: "exists" };
180
+ const old = escaped(current.name);
181
+ // shortcut: a reference whose name is split over two `w:instrText` runs is not followed.
182
+ // A bare name stands for `REF` only when it is no field's name: `{ TITLE }` is the title.
183
+ const bare = FIELD_NAMES.has(current.name.toUpperCase()) ? "" : "?";
184
+ const reference = new RegExp(`^(\\s*(?:(?:REF|PAGEREF|NOTEREF)\\s+)${bare})${old}(?=\\s|$)`, "i");
185
+ const edits = new Map<string | null, (tr: Transaction) => void>();
186
+ for (const { id, tree } of treesOf(editor.state))
187
+ edits.set(id, (tr) => {
188
+ const swap = (pos: number, node: Node, attrs: Record<string, unknown>) =>
189
+ tr.replace(
190
+ pos,
191
+ pos + 1,
192
+ new Slice(
193
+ Fragment.from(node.type.create({ ...node.attrs, ...attrs }, null, node.marks)),
194
+ 0,
195
+ 0,
196
+ ),
197
+ );
198
+ const codes = new Set(fieldsIn(tree).map((field) => field.from));
199
+ let inField = false;
200
+ tree.descendants((node, pos) => {
201
+ if (!node.isInline) return true;
202
+ const type = node.type.name;
203
+ if (type === "fieldStart") inField = codes.has(pos);
204
+ if (type === "bookmarkStart" && same(String(node.attrs.name), name))
205
+ swap(pos, node, { name: next });
206
+ if (type === "fieldCode" && inField) {
207
+ const text = String(node.attrs.text ?? "");
208
+ const changed = text.replace(reference, `$1${next}`);
209
+ if (changed !== text) swap(pos, node, { text: changed });
210
+ inField = false;
211
+ }
212
+ const link = node.marks.find(
213
+ (m: Mark) => m.type.name === "link" && m.attrs.anchor === current.name,
214
+ );
215
+ if (link) {
216
+ const end = pos + node.nodeSize;
217
+ tr.removeMark(pos, end, link);
218
+ tr.addMark(pos, end, link.type.create({ ...link.attrs, anchor: next }));
219
+ }
220
+ return false;
221
+ });
222
+ });
223
+ return result(editor, next, editTrees(editor, edits, { tracked: false }));
224
+ }
225
+
226
+ /** Deletes a bookmark, in whichever tree it is. What refers to it keeps its last result. */
227
+ export function deleteBookmark(editor: Editor, name: string): boolean {
228
+ const edits = new Map<string | null, (tr: Transaction) => void>();
229
+ for (const { id, tree } of treesOf(editor.state)) {
230
+ const markers = markersOf(tree, name);
231
+ if (markers.length)
232
+ edits.set(id, (tr) => {
233
+ for (const pos of markers.reverse()) tr.delete(pos, pos + 1);
234
+ });
235
+ }
236
+ return edits.size > 0 && !editTrees(editor, edits, { tracked: false }).size;
237
+ }
238
+
239
+ /**
240
+ * Selects `target` and shows it: through the view when there is one (which opens a story for it),
241
+ * else in the editor of its tree. Whether it could.
242
+ */
243
+ export function goTo(
244
+ editor: Editor,
245
+ target: DocumentTarget,
246
+ options: { focus?: boolean } = {},
247
+ ): boolean {
248
+ const view = editor.storyView;
249
+ if (view) return view.reveal(target, options);
250
+ const host = target.story === null ? null : editor.story(target.story);
251
+ if (target.story !== null && !host) return false;
252
+ const state = (host ?? editor).state;
253
+ const tr = state.tr.setSelection(TextSelection.create(state.doc, target.from, target.to));
254
+ (host ?? storyBody(editor.state) ?? editor).dispatch(tr);
255
+ return true;
256
+ }
257
+
258
+ export interface OutlineEntry {
259
+ /** Before the paragraph. */
260
+ pos: number;
261
+ /** 1 to 9. */
262
+ level: number;
263
+ text: string;
264
+ /** Its list number, if any. */
265
+ number: string;
266
+ /** Its page as the document numbers it; null without a layout. */
267
+ page: string | null;
268
+ }
269
+
270
+ /**
271
+ * The body's headings, by the rule of a table of contents with `\o` and `\u`: a heading style's
272
+ * level, else the paragraph's outline level. Empty ones and a table of contents' own lines are
273
+ * left out. `layout` (`editor.storyView.fieldLayout`) gives their pages.
274
+ */
275
+ export function documentOutline(
276
+ state: EditorState,
277
+ layout: FieldLayout | null = null,
278
+ ): OutlineEntry[] {
279
+ const body = bodyOf(state);
280
+ const word = wordContext(body);
281
+ if (!word) return [];
282
+ const tree = body.doc;
283
+ const paragraphs = paragraphsOf(tree);
284
+ const markers = word.resolver.markers(paragraphs.map((p) => p.node.attrs));
285
+ const contents = fieldsIn(tree).filter((field) => field.name === "TOC");
286
+ return paragraphs.flatMap((paragraph, i) => {
287
+ const { node, pos } = paragraph;
288
+ const outline = word.resolver.paragraph(node.attrs).paragraph.outlineLevel;
289
+ const level =
290
+ headingLevel(word, node) ?? (outline !== null && outline < 9 ? outline + 1 : null);
291
+ if (level === null || contents.some((f) => pos + 1 >= f.from && pos < f.to)) return [];
292
+ const text = entryTitle(tree, word, paragraph);
293
+ if (!text.trim()) return [];
294
+ const at = layout?.pageAt(pos + 1);
295
+ return [
296
+ {
297
+ pos,
298
+ level,
299
+ text,
300
+ number: markers[i]?.text ?? "",
301
+ page: at ? formatNumber(at.number, at.format) : null,
302
+ },
303
+ ];
304
+ });
305
+ }