@folijs/core 0.5.0 → 1.0.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 (202) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +0 -7
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +5 -1
  6. package/dist/document.js.map +1 -1
  7. package/dist/index.d.ts +4 -4
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +8 -4
  10. package/dist/index.js.map +1 -1
  11. package/dist/internal.d.ts +5 -0
  12. package/dist/internal.d.ts.map +1 -0
  13. package/dist/internal.js +7 -0
  14. package/dist/internal.js.map +1 -0
  15. package/dist/model/attrs.d.ts +0 -10
  16. package/dist/model/attrs.d.ts.map +1 -1
  17. package/dist/model/attrs.js +10 -2
  18. package/dist/model/attrs.js.map +1 -1
  19. package/dist/model/content.d.ts +1 -1
  20. package/dist/model/content.d.ts.map +1 -1
  21. package/dist/model/content.js +1 -1
  22. package/dist/model/content.js.map +1 -1
  23. package/dist/model/errors.d.ts +0 -2
  24. package/dist/model/errors.d.ts.map +1 -1
  25. package/dist/model/errors.js +4 -1
  26. package/dist/model/errors.js.map +1 -1
  27. package/dist/model/fragment.d.ts +1 -1
  28. package/dist/model/fragment.d.ts.map +1 -1
  29. package/dist/model/fragment.js +3 -1
  30. package/dist/model/fragment.js.map +1 -1
  31. package/dist/model/mark.d.ts +1 -1
  32. package/dist/model/mark.d.ts.map +1 -1
  33. package/dist/model/mark.js +1 -1
  34. package/dist/model/mark.js.map +1 -1
  35. package/dist/model/node.d.ts +4 -4
  36. package/dist/model/node.d.ts.map +1 -1
  37. package/dist/model/node.js +8 -4
  38. package/dist/model/node.js.map +1 -1
  39. package/dist/model/schema.d.ts +8 -8
  40. package/dist/model/schema.d.ts.map +1 -1
  41. package/dist/model/schema.js +4 -3
  42. package/dist/model/schema.js.map +1 -1
  43. package/dist/schema.d.ts +0 -11
  44. package/dist/schema.d.ts.map +1 -1
  45. package/dist/schema.js +2 -0
  46. package/dist/schema.js.map +1 -1
  47. package/dist/state/attempt.d.ts +1 -3
  48. package/dist/state/attempt.d.ts.map +1 -1
  49. package/dist/state/commands.d.ts +2 -0
  50. package/dist/state/commands.d.ts.map +1 -1
  51. package/dist/state/commands.js +38 -6
  52. package/dist/state/commands.js.map +1 -1
  53. package/dist/state/comments.d.ts +1 -7
  54. package/dist/state/comments.d.ts.map +1 -1
  55. package/dist/state/comments.js +13 -3
  56. package/dist/state/comments.js.map +1 -1
  57. package/dist/state/controls.d.ts +110 -0
  58. package/dist/state/controls.d.ts.map +1 -0
  59. package/dist/state/controls.js +1473 -0
  60. package/dist/state/controls.js.map +1 -0
  61. package/dist/state/editor.d.ts +188 -68
  62. package/dist/state/editor.d.ts.map +1 -1
  63. package/dist/state/editor.js +265 -79
  64. package/dist/state/editor.js.map +1 -1
  65. package/dist/state/fields.d.ts +68 -0
  66. package/dist/state/fields.d.ts.map +1 -0
  67. package/dist/state/fields.js +410 -0
  68. package/dist/state/fields.js.map +1 -0
  69. package/dist/state/fieldupdate.d.ts +132 -0
  70. package/dist/state/fieldupdate.d.ts.map +1 -0
  71. package/dist/state/fieldupdate.js +1575 -0
  72. package/dist/state/fieldupdate.js.map +1 -0
  73. package/dist/state/find.d.ts +66 -0
  74. package/dist/state/find.d.ts.map +1 -0
  75. package/dist/state/find.js +405 -0
  76. package/dist/state/find.js.map +1 -0
  77. package/dist/state/history.d.ts +2 -0
  78. package/dist/state/history.d.ts.map +1 -1
  79. package/dist/state/history.js +44 -7
  80. package/dist/state/history.js.map +1 -1
  81. package/dist/state/index.d.ts +13 -6
  82. package/dist/state/index.d.ts.map +1 -1
  83. package/dist/state/index.js +12 -5
  84. package/dist/state/index.js.map +1 -1
  85. package/dist/state/lists.d.ts +3 -3
  86. package/dist/state/lists.d.ts.map +1 -1
  87. package/dist/state/lists.js.map +1 -1
  88. package/dist/state/mark.d.ts +1 -17
  89. package/dist/state/mark.d.ts.map +1 -1
  90. package/dist/state/mark.js +10 -1
  91. package/dist/state/mark.js.map +1 -1
  92. package/dist/state/navigation.d.ts +70 -0
  93. package/dist/state/navigation.d.ts.map +1 -0
  94. package/dist/state/navigation.js +226 -0
  95. package/dist/state/navigation.js.map +1 -0
  96. package/dist/state/notes.d.ts +84 -0
  97. package/dist/state/notes.d.ts.map +1 -0
  98. package/dist/state/notes.js +451 -0
  99. package/dist/state/notes.js.map +1 -0
  100. package/dist/state/review.d.ts +8 -4
  101. package/dist/state/review.d.ts.map +1 -1
  102. package/dist/state/review.js +134 -18
  103. package/dist/state/review.js.map +1 -1
  104. package/dist/state/sections.d.ts +91 -0
  105. package/dist/state/sections.d.ts.map +1 -0
  106. package/dist/state/sections.js +479 -0
  107. package/dist/state/sections.js.map +1 -0
  108. package/dist/state/state.d.ts +13 -7
  109. package/dist/state/state.d.ts.map +1 -1
  110. package/dist/state/state.js +9 -2
  111. package/dist/state/state.js.map +1 -1
  112. package/dist/state/stories.d.ts +2 -0
  113. package/dist/state/stories.d.ts.map +1 -0
  114. package/dist/state/stories.js +259 -0
  115. package/dist/state/stories.js.map +1 -0
  116. package/dist/state/tables.d.ts +1 -36
  117. package/dist/state/tables.d.ts.map +1 -1
  118. package/dist/state/tables.js +25 -6
  119. package/dist/state/tables.js.map +1 -1
  120. package/dist/state/track.d.ts +1 -6
  121. package/dist/state/track.d.ts.map +1 -1
  122. package/dist/state/track.js +65 -9
  123. package/dist/state/track.js.map +1 -1
  124. package/dist/state/word.d.ts +47 -55
  125. package/dist/state/word.d.ts.map +1 -1
  126. package/dist/state/word.js +306 -19
  127. package/dist/state/word.js.map +1 -1
  128. package/dist/state/wordclip.d.ts +17 -6
  129. package/dist/state/wordclip.d.ts.map +1 -1
  130. package/dist/state/wordclip.js +254 -17
  131. package/dist/state/wordclip.js.map +1 -1
  132. package/dist/state/wordformat.d.ts +1 -86
  133. package/dist/state/wordformat.d.ts.map +1 -1
  134. package/dist/state/wordformat.js +114 -12
  135. package/dist/state/wordformat.js.map +1 -1
  136. package/dist/transform/stepmap.d.ts +0 -2
  137. package/dist/transform/stepmap.d.ts.map +1 -1
  138. package/dist/v3/check.d.ts +0 -25
  139. package/dist/v3/check.d.ts.map +1 -1
  140. package/dist/v3/check.js +35 -7
  141. package/dist/v3/check.js.map +1 -1
  142. package/dist/v3/document.d.ts +135 -10
  143. package/dist/v3/document.d.ts.map +1 -1
  144. package/dist/v3/document.js +192 -38
  145. package/dist/v3/document.js.map +1 -1
  146. package/dist/v3/extensions.d.ts +43 -0
  147. package/dist/v3/extensions.d.ts.map +1 -0
  148. package/dist/v3/extensions.js +154 -0
  149. package/dist/v3/extensions.js.map +1 -0
  150. package/dist/v3/index.d.ts +3 -2
  151. package/dist/v3/index.d.ts.map +1 -1
  152. package/dist/v3/index.js +3 -2
  153. package/dist/v3/index.js.map +1 -1
  154. package/dist/v3/resolve.d.ts +9 -3
  155. package/dist/v3/resolve.d.ts.map +1 -1
  156. package/dist/v3/resolve.js +28 -4
  157. package/dist/v3/resolve.js.map +1 -1
  158. package/dist/v3/schema.d.ts +5 -16
  159. package/dist/v3/schema.d.ts.map +1 -1
  160. package/dist/v3/schema.js +167 -7
  161. package/dist/v3/schema.js.map +1 -1
  162. package/package.json +5 -1
  163. package/src/document.ts +5 -1
  164. package/src/index.ts +330 -4
  165. package/src/internal.ts +50 -0
  166. package/src/model/attrs.ts +10 -2
  167. package/src/model/content.ts +1 -1
  168. package/src/model/errors.ts +4 -1
  169. package/src/model/fragment.ts +2 -1
  170. package/src/model/mark.ts +1 -1
  171. package/src/model/node.ts +6 -4
  172. package/src/model/schema.ts +9 -3
  173. package/src/schema.ts +2 -0
  174. package/src/state/commands.ts +41 -4
  175. package/src/state/comments.ts +12 -3
  176. package/src/state/controls.ts +1612 -0
  177. package/src/state/editor.ts +508 -143
  178. package/src/state/fields.ts +444 -0
  179. package/src/state/fieldupdate.ts +1771 -0
  180. package/src/state/find.ts +518 -0
  181. package/src/state/history.ts +53 -7
  182. package/src/state/index.ts +125 -1
  183. package/src/state/lists.ts +2 -2
  184. package/src/state/mark.ts +10 -1
  185. package/src/state/navigation.ts +305 -0
  186. package/src/state/notes.ts +529 -0
  187. package/src/state/numeric-pictures.word.json +172 -0
  188. package/src/state/review.ts +172 -19
  189. package/src/state/sections.ts +578 -0
  190. package/src/state/state.ts +21 -3
  191. package/src/state/stories.ts +312 -0
  192. package/src/state/tables.ts +29 -7
  193. package/src/state/track.ts +72 -10
  194. package/src/state/word.ts +360 -24
  195. package/src/state/wordclip.ts +282 -32
  196. package/src/state/wordformat.ts +116 -12
  197. package/src/v3/check.ts +35 -7
  198. package/src/v3/document.ts +358 -50
  199. package/src/v3/extensions.ts +201 -0
  200. package/src/v3/index.ts +16 -0
  201. package/src/v3/resolve.ts +38 -9
  202. package/src/v3/schema.ts +174 -7
@@ -1,5 +1,5 @@
1
1
  import type { DocumentSettings, FoliDocumentV2 } from "../document.js";
2
- import type { Attrs, Node } from "../model/index.js";
2
+ import { type Attrs, type Node, type Schema, Slice } from "../model/index.js";
3
3
  import type { Alignment } from "../schema.js";
4
4
  import {
5
5
  createDocument,
@@ -8,6 +8,7 @@ import {
8
8
  parseDocument,
9
9
  type SectionJSON,
10
10
  } from "../v3/document.js";
11
+ import { type Extension, schemaWith, writeCustom } from "../v3/extensions.js";
11
12
  import { twipsToMm as mm } from "../v3/units.js";
12
13
  import {
13
14
  baseKeymap,
@@ -37,10 +38,22 @@ import {
37
38
  replyToComment,
38
39
  resolveComment,
39
40
  } from "./comments.js";
41
+ import {
42
+ type ControlValue,
43
+ type ControlValueInput,
44
+ controlsIn,
45
+ controlsPlugin,
46
+ controlValues,
47
+ setControlValue,
48
+ } from "./controls.js";
49
+ import { fieldsPlugin } from "./fields.js";
50
+ import type { FieldLayout, FieldsReport, UpdateFieldsOptions } from "./fieldupdate.js";
51
+ import type { FindMatch, FindOptions } from "./find.js";
40
52
  import { setAlign, setHighlight, setTextColor } from "./format.js";
41
53
  import { history, redo, undo } from "./history.js";
42
54
  import { removeLink, setLink } from "./links.js";
43
55
  import { liftListItem, listKeymap, sinkListItem, toggleList, wrapInList } from "./lists.js";
56
+ import { notesPlugin } from "./notes.js";
44
57
  import {
45
58
  acceptAllChanges,
46
59
  acceptChange,
@@ -49,8 +62,10 @@ import {
49
62
  rejectAllChanges,
50
63
  rejectChange,
51
64
  } from "./review.js";
52
- import { TextSelection } from "./selection.js";
53
- import { type Command, EditorState, type Plugin, type Transaction } from "./state.js";
65
+ import type { StorySide, StoryVariant } from "./sections.js";
66
+ import { Selection, TextSelection } from "./selection.js";
67
+ import { type Command, EditorState, Plugin, PluginKey, type Transaction } from "./state.js";
68
+ import { callListener, StoryEditing } from "./stories.js";
54
69
  import { tableKeymap } from "./tables.js";
55
70
  import {
56
71
  type ReviewView,
@@ -61,7 +76,14 @@ import {
61
76
  trackState,
62
77
  trackTransaction,
63
78
  } from "./track.js";
64
- import { type WordEnvelope, wordContext, wordPlugin } from "./word.js";
79
+ import {
80
+ documentJSON,
81
+ storyBody,
82
+ type WordContext,
83
+ type WordEnvelope,
84
+ wordContext,
85
+ wordPlugin,
86
+ } from "./word.js";
65
87
  import type { ListKind } from "./wordformat.js";
66
88
 
67
89
  /**
@@ -75,6 +97,12 @@ export interface EditorOptions {
75
97
  document?: EditorDocument;
76
98
  /** Run before the built-in plugins, so their keymaps take precedence. */
77
99
  plugins?: readonly Plugin[];
100
+ /**
101
+ * Custom node and mark types and their plugins (ADR-0008), added to the Word schema. Their
102
+ * plugins run after `plugins`, before the built-ins. Content of types none of them declares is
103
+ * kept as foreign nodes and marks and saved back unchanged.
104
+ */
105
+ extensions?: readonly Extension[];
78
106
  /** Who edits: tracked changes are made in this name. Default "Author". */
79
107
  author?: string;
80
108
  /**
@@ -88,6 +116,151 @@ export interface EditorOptions {
88
116
 
89
117
  export type EditorListener = (state: EditorState, transactions: readonly Transaction[]) => void;
90
118
 
119
+ /** A header, footer or note open for editing on its page. */
120
+ export interface OpenStory {
121
+ id: string;
122
+ side: StorySide | "note";
123
+ variant: StoryVariant;
124
+ /** The section it was opened from (a linked one shows an earlier section's story). */
125
+ section: number;
126
+ }
127
+
128
+ /** A place to show: `from..to` of the body (`story` null) or of a story. */
129
+ export interface DocumentTarget {
130
+ story: string | null;
131
+ from: number;
132
+ to: number;
133
+ }
134
+
135
+ /** What find shows on the pages. */
136
+ export interface FoundMatches extends FindOptions {
137
+ query: string;
138
+ matches: readonly FindMatch[];
139
+ /** The one marked apart, if any. */
140
+ current: FindMatch | null;
141
+ /** Scroll to `current`: on a search or a step, not when the document changed under it. */
142
+ scroll?: boolean;
143
+ }
144
+
145
+ /** The commands Word has keys for, answered by what the app shows for them. */
146
+ export type NavigationRequest =
147
+ | "find"
148
+ | "replace"
149
+ | "goTo"
150
+ | "next"
151
+ | "previous"
152
+ | "bookmarks"
153
+ | "outline";
154
+
155
+ /** What opens stories on the pages: the view of the editor's document. */
156
+ export interface StoryView {
157
+ readonly open: OpenStory | null;
158
+ /** Opens the header or footer of a page (default: the selection's). Whether it is open now. */
159
+ edit(side: StorySide, page?: number): boolean;
160
+ /** Opens a note where it is: `id`, or the one whose reference is at the selection. */
161
+ editNote(id?: string): boolean;
162
+ /** Back from the note being edited to its reference, the caret after it. */
163
+ toReference(): boolean;
164
+ close(): void;
165
+ /** The pages as last laid out, for fields; null when there are none. */
166
+ readonly fieldLayout: FieldLayout | null;
167
+ /**
168
+ * Updates fields with the pages in view (of the body, or of `editor`, a story's), again when
169
+ * that moved them. One undo step.
170
+ */
171
+ updateFields(options?: UpdateFieldsOptions, editor?: Editor): FieldsReport;
172
+ /** Marks what find found on the pages (never in the document, not printed); null: nothing. */
173
+ showMatches(found: FoundMatches | null): void;
174
+ /**
175
+ * Selects `target` and scrolls to it, opening its story where it is, or leaving the open one.
176
+ * `focus`: the document takes the focus. False when no page shows it.
177
+ */
178
+ reveal(target: DocumentTarget, options?: { focus?: boolean }): boolean;
179
+ /** The caret to the start of page `page` (1-based), scrolled to. False when there is none. */
180
+ goToPage(page: number, options?: { focus?: boolean }): boolean;
181
+ /** Focuses the document, or the story open in it. */
182
+ focus(): void;
183
+ }
184
+
185
+ /** The built-in commands on `editor.commands`. */
186
+ export interface BuiltInCommands {
187
+ insertText(text: string): boolean;
188
+ deleteSelection(): boolean;
189
+ deleteBackward(unit?: DeleteUnit): boolean;
190
+ deleteForward(unit?: DeleteUnit): boolean;
191
+ joinBackward(): boolean;
192
+ joinForward(): boolean;
193
+ splitBlock(): boolean;
194
+ insertHardBreak(): boolean;
195
+ insertPageBreak(): boolean;
196
+ toggleMark(type: string, attrs?: Attrs | null): boolean;
197
+ setBlockType(type: string, attrs?: Attrs | null): boolean;
198
+ selectAll(): boolean;
199
+ undo(): boolean;
200
+ redo(): boolean;
201
+ /** Numbers the selected paragraphs as a list ("bulletList" or "orderedList"). */
202
+ wrapInList(kind: ListKind): boolean;
203
+ /** The list buttons: removes the selection's numbering when it is a list of `kind`, else numbers it. */
204
+ toggleList(kind: ListKind): boolean;
205
+ /** Tab in a list: one level deeper. */
206
+ indentListItem(): boolean;
207
+ /** Shift+Tab in a list: one level up (out of the list at the top). */
208
+ outdentListItem(): boolean;
209
+ /**
210
+ * Links the selection to `href` (normalized, then validated: unsafe hrefs do not apply); at
211
+ * a caret in a link, changes it; elsewhere inserts the href as linked text.
212
+ */
213
+ setLink(href: string): boolean;
214
+ /** Removes the links in the selection, or the link around the caret. */
215
+ removeLink(): boolean;
216
+ /** Aligns the selected paragraphs and headings ("start", "center", "end", "justify"). */
217
+ setAlign(align: Alignment): boolean;
218
+ /** Text color (lowercase `#rrggbb`) of the selected or next typed text; null removes it. */
219
+ setTextColor(color: string | null): boolean;
220
+ /** Highlight (`#rrggbb`) of the selected or next typed text; null removes it. */
221
+ setHighlight(color: string | null): boolean;
222
+ /** Turns tracked changes on or off (`author` changes who makes them). */
223
+ setTrackChanges(on: boolean, author?: string): boolean;
224
+ /** How the editor's views show tracked changes. */
225
+ setReviewView(view: ReviewView): boolean;
226
+ /** Accepts the change at the caret, or the changes in the selection. */
227
+ acceptChange(): boolean;
228
+ /** Rejects the change at the caret, or the changes in the selection. */
229
+ rejectChange(): boolean;
230
+ /** Accepts every change, or every change of `author`. */
231
+ acceptAllChanges(author?: string): boolean;
232
+ /** Rejects every change, or every change of `author`. */
233
+ rejectAllChanges(author?: string): boolean;
234
+ /** Selects the next change after the selection. */
235
+ nextChange(): boolean;
236
+ /** Selects the previous change before the selection. */
237
+ previousChange(): boolean;
238
+ /** Comments the selection (at a caret, the point there). */
239
+ addComment(content: CommentContent, options?: CommentOptions): boolean;
240
+ /** Replies to a comment's thread. */
241
+ replyToComment(id: number, content: CommentContent, options?: CommentOptions): boolean;
242
+ /** Replaces a comment's content. */
243
+ editComment(id: number, content: CommentContent): boolean;
244
+ /** Resolves (`done` false: reopens) a comment's thread. */
245
+ resolveComment(id: number, done?: boolean): boolean;
246
+ /** Deletes a comment, its replies and their anchors. */
247
+ deleteComment(id: number): boolean;
248
+ /** Deletes every comment. */
249
+ deleteAllComments(): boolean;
250
+ /**
251
+ * Fills the content controls with this id or tag, here and in the stories (from the body's
252
+ * editor): one undo step, tracked when tracking is on. False when none could take it.
253
+ */
254
+ setControlValue(target: string, value: ControlValueInput): boolean;
255
+ }
256
+
257
+ /**
258
+ * The commands on `editor.commands`: the built-in ones and those plugins add. Apps add the names
259
+ * of their plugins' commands by augmenting it:
260
+ * `declare module "@folijs/core" { interface FoliCommands { insertMention(id: string): boolean } }`.
261
+ */
262
+ export interface FoliCommands extends BuiltInCommands {}
263
+
91
264
  /** A headless editor: state, commands, history and change notifications, no DOM. */
92
265
  export interface Editor {
93
266
  readonly state: EditorState;
@@ -105,71 +278,13 @@ export interface Editor {
105
278
  handleKey(key: string): boolean;
106
279
  /** Places a text selection (positions are clamped into the document). */
107
280
  select(anchor: number, head?: number): void;
108
- readonly commands: {
109
- insertText(text: string): boolean;
110
- deleteSelection(): boolean;
111
- deleteBackward(unit?: DeleteUnit): boolean;
112
- deleteForward(unit?: DeleteUnit): boolean;
113
- joinBackward(): boolean;
114
- joinForward(): boolean;
115
- splitBlock(): boolean;
116
- insertHardBreak(): boolean;
117
- insertPageBreak(): boolean;
118
- toggleMark(type: string, attrs?: Attrs | null): boolean;
119
- setBlockType(type: string, attrs?: Attrs | null): boolean;
120
- selectAll(): boolean;
121
- undo(): boolean;
122
- redo(): boolean;
123
- /** Numbers the selected paragraphs as a list ("bulletList" or "orderedList"). */
124
- wrapInList(kind: ListKind): boolean;
125
- /** The list buttons: removes the selection's numbering when it is a list of `kind`, else numbers it. */
126
- toggleList(kind: ListKind): boolean;
127
- /** Tab in a list: one level deeper. */
128
- indentListItem(): boolean;
129
- /** Shift+Tab in a list: one level up (out of the list at the top). */
130
- outdentListItem(): boolean;
131
- /**
132
- * Links the selection to `href` (normalized, then validated: unsafe hrefs do not apply); at
133
- * a caret in a link, changes it; elsewhere inserts the href as linked text.
134
- */
135
- setLink(href: string): boolean;
136
- /** Removes the links in the selection, or the link around the caret. */
137
- removeLink(): boolean;
138
- /** Aligns the selected paragraphs and headings ("start", "center", "end", "justify"). */
139
- setAlign(align: Alignment): boolean;
140
- /** Text color (lowercase `#rrggbb`) of the selected or next typed text; null removes it. */
141
- setTextColor(color: string | null): boolean;
142
- /** Highlight (`#rrggbb`) of the selected or next typed text; null removes it. */
143
- setHighlight(color: string | null): boolean;
144
- /** Turns tracked changes on or off (`author` changes who makes them). */
145
- setTrackChanges(on: boolean, author?: string): boolean;
146
- /** How the editor's views show tracked changes. */
147
- setReviewView(view: ReviewView): boolean;
148
- /** Accepts the change at the caret, or the changes in the selection. */
149
- acceptChange(): boolean;
150
- /** Rejects the change at the caret, or the changes in the selection. */
151
- rejectChange(): boolean;
152
- /** Accepts every change, or every change of `author`. */
153
- acceptAllChanges(author?: string): boolean;
154
- /** Rejects every change, or every change of `author`. */
155
- rejectAllChanges(author?: string): boolean;
156
- /** Selects the next change after the selection. */
157
- nextChange(): boolean;
158
- /** Selects the previous change before the selection. */
159
- previousChange(): boolean;
160
- /** Comments the selection (at a caret, the point there). */
161
- addComment(content: CommentContent, options?: CommentOptions): boolean;
162
- /** Replies to a comment's thread. */
163
- replyToComment(id: number, content: CommentContent, options?: CommentOptions): boolean;
164
- /** Replaces a comment's content. */
165
- editComment(id: number, content: CommentContent): boolean;
166
- /** Resolves (`done` false: reopens) a comment's thread. */
167
- resolveComment(id: number, done?: boolean): boolean;
168
- /** Deletes a comment, its replies and their anchors. */
169
- deleteComment(id: number): boolean;
170
- /** Deletes every comment. */
171
- deleteAllComments(): boolean;
172
- };
281
+ /**
282
+ * The named commands: the built-in ones and those plugins add (`PluginSpec.commands`), each
283
+ * run on this editor; whether it applied.
284
+ */
285
+ readonly commands: FoliCommands;
286
+ /** The content controls' values, the stories' after the body's (from the body's editor). */
287
+ controlValues(): ControlValue[];
173
288
  /** Whether edits are recorded as tracked changes. */
174
289
  readonly trackingChanges: boolean;
175
290
  isMarkActive(type: string): boolean;
@@ -178,6 +293,27 @@ export interface Editor {
178
293
  /** Replaces the whole document (an older one migrated) and resets history. */
179
294
  setDocument(document: EditorDocument): void;
180
295
  subscribe(listener: EditorListener): () => void;
296
+ /**
297
+ * An editor over a story (a header, footer or note) by id, null when there is none. It has its
298
+ * own selection, and its changes go through this editor: one undo history, in `state.doc` order
299
+ * of the changes. On a story's editor `getDocument` gives the story as a document's content and
300
+ * `setDocument` replaces its content.
301
+ */
302
+ story(id: string): Editor | null;
303
+ /** Set by the view showing the pages: what opens a story there, shared with stories' editors. */
304
+ storyView: StoryView | null;
305
+ /** The view opened or closed a story: tells the editor's listeners (no transaction). */
306
+ storyChanged(): void;
307
+ /**
308
+ * Set by the app's navigation UI: what Word's keys for it do. The view asks it first and leaves
309
+ * a key to the browser when it answers false, or when there is none.
310
+ */
311
+ navigation: ((request: NavigationRequest) => boolean) | null;
312
+ /**
313
+ * The extensions it was made with (`EditorOptions.extensions`), the same list on its stories'
314
+ * editors: a view reads its view hooks from them (`ViewExtension` in `@folijs/view`).
315
+ */
316
+ readonly extensions: readonly Extension[];
181
317
  }
182
318
 
183
319
  /** Word's page when a section leaves it out: Letter, 1 inch margins. */
@@ -207,123 +343,352 @@ interface Loaded {
207
343
  }
208
344
 
209
345
  /** Validates (and migrates) a document and reads what the editor keeps of it. */
210
- function load(document: EditorDocument): Loaded {
211
- const { content, ...envelope } = parseDocument(document);
212
- return { doc: parseContent(content), settings: sectionSettings(envelope.section), envelope };
346
+ function loadDocument(
347
+ document: EditorDocument,
348
+ extensions: readonly Extension[],
349
+ schema: Schema,
350
+ ): Loaded {
351
+ const { content, ...envelope } = parseDocument(document, { extensions });
352
+ return {
353
+ doc: parseContent(content, { schema }),
354
+ settings: sectionSettings(envelope.section),
355
+ envelope,
356
+ };
357
+ }
358
+
359
+ /** What differs between the editor of the body and of a story. */
360
+ interface EditorParts {
361
+ state(): EditorState;
362
+ dispatch(tr: Transaction): void;
363
+ settings(): DocumentSettings;
364
+ getDocument(): FoliDocument;
365
+ setDocument(document: EditorDocument): void;
366
+ subscribe(listener: EditorListener): () => void;
367
+ story(id: string): Editor | null;
368
+ /** The view opening stories, and the navigation UI: one for the body and its stories. */
369
+ views: { current: StoryView | null; navigation: Editor["navigation"] };
370
+ storyChanged(): void;
371
+ extensions: readonly Extension[];
372
+ /** The user's and extensions' plugins: their `commands` join the built-in ones. */
373
+ plugins: readonly Plugin[];
374
+ }
375
+
376
+ function makeEditor(parts: EditorParts): Editor {
377
+ const { dispatch } = parts;
378
+ const run = (command: Command) => command(parts.state(), dispatch);
379
+ /** This editor and, from the body's, those of the stories holding controls. */
380
+ const withStories = (): { editor: Editor; story?: string }[] => {
381
+ const state = parts.state();
382
+ const context = storyBody(state) ? null : wordContext(state);
383
+ const held = [...(context?.stories ?? [])].filter(([, s]) => controlsIn(s.doc).length);
384
+ return [
385
+ { editor: self },
386
+ ...held.flatMap(([story]) => {
387
+ const editor = parts.story(story);
388
+ return editor ? [{ editor, story }] : [];
389
+ }),
390
+ ];
391
+ };
392
+ // Each named command as a factory, so `editorCommand` can give it for a dry run.
393
+ const factories = withPluginFactories(parts.plugins, {
394
+ insertText: (text) => insertText(text),
395
+ deleteSelection: () => deleteSelection,
396
+ deleteBackward: (unit) => deleteBackward(unit),
397
+ deleteForward: (unit) => deleteForward(unit),
398
+ joinBackward: () => joinBackward,
399
+ joinForward: () => joinForward,
400
+ splitBlock: () => splitBlock,
401
+ insertHardBreak: () => insertHardBreak,
402
+ insertPageBreak: () => insertPageBreak,
403
+ toggleMark: (type, attrs) => toggleMark(type, attrs),
404
+ setBlockType: (type, attrs) => setBlockType(type, attrs),
405
+ selectAll: () => selectAll,
406
+ undo: () => undo,
407
+ redo: () => redo,
408
+ wrapInList: (kind) => wrapInList(kind),
409
+ toggleList: (kind) => toggleList(kind),
410
+ indentListItem: () => sinkListItem,
411
+ outdentListItem: () => liftListItem,
412
+ setLink: (href) => setLink(href),
413
+ removeLink: () => removeLink,
414
+ setAlign: (align) => setAlign(align),
415
+ setTextColor: (color) => setTextColor(color),
416
+ setHighlight: (color) => setHighlight(color),
417
+ setTrackChanges: (on, name) => setTrackChanges(on, name),
418
+ setReviewView: (view) => setReviewView(view),
419
+ acceptChange: () => acceptChange,
420
+ rejectChange: () => rejectChange,
421
+ acceptAllChanges: (name) => acceptAllChanges(name),
422
+ rejectAllChanges: (name) => rejectAllChanges(name),
423
+ nextChange: () => nextChange,
424
+ previousChange: () => previousChange,
425
+ addComment: (content, options) => addComment(content, options),
426
+ replyToComment: (id, content, options) => replyToComment(id, content, options),
427
+ editComment: (id, content) => editComment(id, content),
428
+ resolveComment: (id, done) => resolveComment(id, done),
429
+ deleteComment: (id) => deleteComment(id),
430
+ deleteAllComments: () => deleteAllComments,
431
+ // Across the body and its stories: `state` is the body's; a dry run asks each editor.
432
+ setControlValue: (target, value) => (_state, dispatch) => {
433
+ let done = false;
434
+ for (const { editor } of withStories())
435
+ if (
436
+ dispatch
437
+ ? editor.run(setControlValue(target, value, done))
438
+ : editor.can(setControlValue(target, value, done))
439
+ )
440
+ done = true;
441
+ return done;
442
+ },
443
+ });
444
+ const self: Editor = {
445
+ get settings() {
446
+ return parts.settings();
447
+ },
448
+ get state() {
449
+ return parts.state();
450
+ },
451
+ dispatch,
452
+ run,
453
+ can: (command) => command(parts.state()),
454
+ handleKey(key) {
455
+ const state = parts.state();
456
+ return state.plugins.some((plugin) => {
457
+ const command = plugin.spec.keymap?.[key];
458
+ return command ? command(state, dispatch) : false;
459
+ });
460
+ },
461
+ select(anchor, head = anchor) {
462
+ const state = parts.state();
463
+ const size = state.doc.content.size;
464
+ const clamp = (pos: number) => Math.max(0, Math.min(pos, size));
465
+ dispatch(state.tr.setSelection(TextSelection.create(state.doc, clamp(anchor), clamp(head))));
466
+ },
467
+ commands: commandsOf(factories, run),
468
+ controlValues: () =>
469
+ withStories().flatMap(({ editor, story }) =>
470
+ controlValues(editor.state).map((value) => (story ? { ...value, story } : value)),
471
+ ),
472
+ get trackingChanges() {
473
+ return trackState(parts.state())?.on ?? false;
474
+ },
475
+ isMarkActive: (type) => isMarkActive(parts.state(), type),
476
+ getDocument: parts.getDocument,
477
+ setDocument: parts.setDocument,
478
+ subscribe: parts.subscribe,
479
+ story: parts.story,
480
+ get storyView() {
481
+ return parts.views.current;
482
+ },
483
+ set storyView(view) {
484
+ parts.views.current = view;
485
+ },
486
+ storyChanged: parts.storyChanged,
487
+ extensions: parts.extensions,
488
+ get navigation() {
489
+ return parts.views.navigation;
490
+ },
491
+ set navigation(handler) {
492
+ parts.views.navigation = handler;
493
+ },
494
+ };
495
+ commandFactories.set(self, factories);
496
+ return self;
497
+ }
498
+
499
+ /** The built-in commands as factories of the commands they run. */
500
+ type BuiltInFactories = {
501
+ [K in keyof BuiltInCommands]: (...args: Parameters<BuiltInCommands[K]>) => Command;
502
+ };
503
+ type Factories = Record<string, (...args: never[]) => Command>;
504
+
505
+ /**
506
+ * Adds the command factories `plugins` name (`PluginSpec.commands`) to the built-in ones. A name
507
+ * taken twice, or by a built-in command, throws.
508
+ */
509
+ function withPluginFactories(plugins: readonly Plugin[], builtIns: BuiltInFactories): Factories {
510
+ const factories: Factories = { ...builtIns };
511
+ for (const plugin of plugins)
512
+ for (const [name, factory] of Object.entries(plugin.spec.commands ?? {})) {
513
+ if (Object.hasOwn(factories, name))
514
+ throw new RangeError(
515
+ `Command "${name}" is already defined: plugin commands need names of their own`,
516
+ );
517
+ if (typeof factory !== "function")
518
+ throw new TypeError(`Command "${name}" is not a function returning a command`);
519
+ // defineProperty: a name such as "__proto__" is a command, not the object's prototype.
520
+ Object.defineProperty(factories, name, { value: factory, enumerable: true });
521
+ }
522
+ return factories;
523
+ }
524
+
525
+ /** `editor.commands`: each factory's command run on the editor. */
526
+ function commandsOf(factories: Factories, run: (command: Command) => boolean): FoliCommands {
527
+ const commands = {};
528
+ for (const [name, factory] of Object.entries(factories))
529
+ Object.defineProperty(commands, name, {
530
+ value: (...args: never[]) => run(factory(...args)),
531
+ enumerable: true,
532
+ });
533
+ return commands as FoliCommands;
534
+ }
535
+
536
+ const commandFactories = new WeakMap<Editor, Factories>();
537
+
538
+ /**
539
+ * The command `editor.commands[name](...args)` would run, for a dry run (`editor.can`): built-in
540
+ * or a plugin's; undefined when the editor has no command of that name.
541
+ */
542
+ export function editorCommand(
543
+ editor: Editor,
544
+ name: string,
545
+ args: readonly unknown[],
546
+ ): Command | undefined {
547
+ const factories = commandFactories.get(editor);
548
+ const factory = factories && Object.hasOwn(factories, name) ? factories[name] : undefined;
549
+ return factory?.(...(args as never[]));
213
550
  }
214
551
 
552
+ /**
553
+ * Where the view's own overridable keys run (ADR-0008, `docs/keyboard.md`): a plugin
554
+ * with no keymap placed after the user's plugins and before the built-in ones.
555
+ */
556
+ export const viewKeys = new PluginKey<never>("viewKeys");
557
+
215
558
  export function createEditor({
216
559
  document = createDocument(),
217
560
  plugins = [],
561
+ extensions = [],
218
562
  author = "Author",
219
563
  trackChanges = false,
220
564
  reviewView = "markup",
221
565
  }: EditorOptions = {}): Editor {
566
+ const schema = schemaWith(extensions);
567
+ const own = [...plugins, ...extensions.flatMap((e) => e.plugins ?? [])];
568
+ const load = (next: EditorDocument) => loadDocument(next, extensions, schema);
222
569
  let loaded = load(document);
223
570
  let track: TrackState = { on: trackChanges, author, view: reviewView };
224
571
  const pluginsFor = ({ envelope }: Loaded) => [
225
- ...plugins,
572
+ ...own,
573
+ new Plugin({ key: viewKeys }),
226
574
  history(),
227
575
  wordPlugin(envelope),
228
576
  trackPlugin(track),
577
+ fieldsPlugin(),
578
+ controlsPlugin(),
229
579
  commentsPlugin(),
580
+ notesPlugin(),
230
581
  tableKeymap(),
231
582
  listKeymap(),
232
583
  baseKeymap(),
233
584
  ];
234
585
  let state = EditorState.create({ doc: loaded.doc, plugins: pluginsFor(loaded) });
235
586
  const listeners = new Set<EditorListener>();
587
+ const views: EditorParts["views"] = { current: null, navigation: null };
588
+ /** The stories being edited, by id. */
589
+ const stories = new Map<string, { editing: StoryEditing; editor: Editor }>();
236
590
 
237
591
  const notify = (transactions: readonly Transaction[]) => {
238
- for (const listener of listeners) listener(state, transactions);
592
+ for (const listener of listeners) callListener(listener, state, transactions);
239
593
  };
594
+ const storyChanged = () => notify([]);
240
595
  const dispatch = (tr: Transaction) => {
241
596
  // With tracking on, the edit is rebuilt as tracked changes; one that cannot be is not made.
242
597
  const tracked = trackTransaction(state, tr);
243
598
  if (!tracked) return;
244
599
  const result = state.applyTransaction(tracked);
245
600
  state = result.state;
246
- if (result.transactions.length) notify(result.transactions);
601
+ if (!result.transactions.length) return;
602
+ // The stories first: a view of the body redraws them from what they now are.
603
+ for (const [id, { editing }] of stories) {
604
+ editing.sync(result.transactions);
605
+ if (!editing.alive) stories.delete(id);
606
+ }
607
+ notify(result.transactions);
247
608
  };
248
609
  const run = (command: Command) => command(state, dispatch);
610
+ let current = { section: loaded.envelope.section, settings: loaded.settings };
611
+ const settings = () => {
612
+ // The last section's page setup, as it is now (`setSectionSetup` changes it).
613
+ const section = wordContext(state)?.envelope.section ?? current.section;
614
+ if (section !== current.section) current = { section, settings: sectionSettings(section) };
615
+ return current.settings;
616
+ };
617
+ const getDocument = (): FoliDocument =>
618
+ documentJSON(wordContext(state)?.envelope ?? loaded.envelope, state.doc);
249
619
 
250
- return {
251
- get settings() {
252
- return loaded.settings;
253
- },
254
- get state() {
255
- return state;
256
- },
620
+ const storyEditor = (id: string): Editor => {
621
+ const editing = new StoryEditing(id, {
622
+ get state() {
623
+ return state;
624
+ },
625
+ run,
626
+ can: (command) => command(state),
627
+ dispatch,
628
+ plugins: (context: WordContext, value) => [
629
+ ...own,
630
+ new Plugin({ key: viewKeys }),
631
+ wordPlugin(context.envelope, context),
632
+ trackPlugin(value ?? track),
633
+ fieldsPlugin(),
634
+ controlsPlugin(),
635
+ commentsPlugin(),
636
+ tableKeymap(),
637
+ listKeymap(),
638
+ baseKeymap(),
639
+ ],
640
+ });
641
+ const editor = makeEditor({
642
+ state: () => editing.state,
643
+ dispatch: editing.dispatch,
644
+ settings,
645
+ getDocument: () => ({ ...getDocument(), content: writeCustom(editing.state.doc.toJSON()) }),
646
+ setDocument(next) {
647
+ const { doc } = load(next);
648
+ const tr = editing.state.tr.replace(
649
+ 0,
650
+ editing.state.doc.content.size,
651
+ new Slice(doc.content, 0, 0),
652
+ );
653
+ editing.dispatch(tr.setSelection(Selection.atStart(tr.doc)));
654
+ },
655
+ subscribe(listener) {
656
+ editing.listeners.add(listener);
657
+ return () => editing.listeners.delete(listener);
658
+ },
659
+ story,
660
+ views,
661
+ storyChanged,
662
+ extensions,
663
+ plugins: own,
664
+ });
665
+ stories.set(id, { editing, editor });
666
+ return editor;
667
+ };
668
+ const story = (id: string): Editor | null =>
669
+ wordContext(state)?.stories.has(id) ? (stories.get(id)?.editor ?? storyEditor(id)) : null;
670
+
671
+ return makeEditor({
672
+ state: () => state,
257
673
  dispatch,
258
- run,
259
- can: (command) => command(state),
260
- handleKey(key) {
261
- return state.plugins.some((plugin) => {
262
- const command = plugin.spec.keymap?.[key];
263
- return command ? command(state, dispatch) : false;
264
- });
265
- },
266
- select(anchor, head = anchor) {
267
- const size = state.doc.content.size;
268
- const clamp = (pos: number) => Math.max(0, Math.min(pos, size));
269
- dispatch(state.tr.setSelection(TextSelection.create(state.doc, clamp(anchor), clamp(head))));
270
- },
271
- commands: {
272
- insertText: (text) => run(insertText(text)),
273
- deleteSelection: () => run(deleteSelection),
274
- deleteBackward: (unit) => run(deleteBackward(unit)),
275
- deleteForward: (unit) => run(deleteForward(unit)),
276
- joinBackward: () => run(joinBackward),
277
- joinForward: () => run(joinForward),
278
- splitBlock: () => run(splitBlock),
279
- insertHardBreak: () => run(insertHardBreak),
280
- insertPageBreak: () => run(insertPageBreak),
281
- toggleMark: (type, attrs) => run(toggleMark(type, attrs)),
282
- setBlockType: (type, attrs) => run(setBlockType(type, attrs)),
283
- selectAll: () => run(selectAll),
284
- undo: () => run(undo),
285
- redo: () => run(redo),
286
- wrapInList: (kind) => run(wrapInList(kind)),
287
- toggleList: (kind) => run(toggleList(kind)),
288
- indentListItem: () => run(sinkListItem),
289
- outdentListItem: () => run(liftListItem),
290
- setLink: (href) => run(setLink(href)),
291
- removeLink: () => run(removeLink),
292
- setAlign: (align) => run(setAlign(align)),
293
- setTextColor: (color) => run(setTextColor(color)),
294
- setHighlight: (color) => run(setHighlight(color)),
295
- setTrackChanges: (on, name) => run(setTrackChanges(on, name)),
296
- setReviewView: (view) => run(setReviewView(view)),
297
- acceptChange: () => run(acceptChange),
298
- rejectChange: () => run(rejectChange),
299
- acceptAllChanges: (name) => run(acceptAllChanges(name)),
300
- rejectAllChanges: (name) => run(rejectAllChanges(name)),
301
- nextChange: () => run(nextChange),
302
- previousChange: () => run(previousChange),
303
- addComment: (content, options) => run(addComment(content, options)),
304
- replyToComment: (id, content, options) => run(replyToComment(id, content, options)),
305
- editComment: (id, content) => run(editComment(id, content)),
306
- resolveComment: (id, done) => run(resolveComment(id, done)),
307
- deleteComment: (id) => run(deleteComment(id)),
308
- deleteAllComments: () => run(deleteAllComments),
309
- },
310
- get trackingChanges() {
311
- return trackState(state)?.on ?? false;
312
- },
313
- isMarkActive: (type) => isMarkActive(state, type),
314
- getDocument: () => ({
315
- ...structuredClone(wordContext(state)?.envelope ?? loaded.envelope),
316
- content: state.doc.toJSON(),
317
- }),
674
+ settings,
675
+ getDocument,
318
676
  setDocument(next) {
319
677
  track = trackState(state) ?? track;
320
678
  loaded = load(next);
321
679
  state = EditorState.create({ doc: loaded.doc, plugins: pluginsFor(loaded) });
680
+ for (const { editing } of stories.values()) editing.retire();
681
+ stories.clear();
322
682
  notify([]);
323
683
  },
324
684
  subscribe(listener) {
325
685
  listeners.add(listener);
326
686
  return () => listeners.delete(listener);
327
687
  },
328
- };
688
+ story,
689
+ views,
690
+ storyChanged,
691
+ extensions,
692
+ plugins: own,
693
+ });
329
694
  }