@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
@@ -0,0 +1,578 @@
1
+ /**
2
+ * Sections (11.6, ADR-0007): what layout needs of `w:cols`, and the commands that insert and
3
+ * remove section breaks and change a section's page setup, as Word records them. A section's
4
+ * setup is on the paragraph that ends it (`section`), the last one's in the envelope.
5
+ *
6
+ * Checked with Word 16 (automation, its saved XML): a break splits the paragraph at the caret; the
7
+ * first half's mark holds the section's setup, header references included, and the rest of the
8
+ * section keeps its setup without them (it inherits them) and starts as the break says. While
9
+ * tracking the new mark is a tracked insertion and nothing else is recorded; a removed break is
10
+ * its mark, tracked as deleted; a changed setup is `w:sectPrChange` holding the setup before.
11
+ * Removing a break leaves the following section's setup, with the header references it inherited.
12
+ */
13
+ import { deepEqual } from "../model/attrs.js";
14
+ import type { Node } from "../model/index.js";
15
+ import type { SectionJSON, StoryJSON } from "../v3/document.js";
16
+ import { parseContent } from "../v3/document.js";
17
+ import { checkSection } from "../v3/schema.js";
18
+ import { closeHistory } from "./history.js";
19
+ import { keepLastMark } from "./mark.js";
20
+ import { TextSelection } from "./selection.js";
21
+ import type { Command, EditorState, Transaction } from "./state.js";
22
+ import { newRevision, nextRevisionId, untracked } from "./track.js";
23
+ import {
24
+ EnvelopeStep,
25
+ type Story,
26
+ StoryStep,
27
+ setEnvelopeValue,
28
+ splitAttrs,
29
+ storyAfter,
30
+ storyBody,
31
+ storyState,
32
+ wordContext,
33
+ } from "./word.js";
34
+
35
+ /** Word's page when a section leaves it out: Letter, 1 inch margins. */
36
+ const LETTER = { width: 12240, height: 15840, margin: 1440 };
37
+ /** Word's default space between columns: half an inch. */
38
+ const COLUMN_SPACE = 720;
39
+
40
+ export interface SectionColumns {
41
+ /** Each column's width. */
42
+ widths: number[];
43
+ /** The space after each column but the last. */
44
+ gaps: number[];
45
+ /** A line between columns. */
46
+ separator: boolean;
47
+ }
48
+
49
+ /**
50
+ * The columns of `section`: its set widths when it says the columns are not equal, otherwise
51
+ * `count` columns sharing the text width.
52
+ */
53
+ export function sectionColumns(section: SectionJSON): SectionColumns {
54
+ const { columns = {} } = section;
55
+ const separator = columns.separator === true;
56
+ const space = columns.space ?? COLUMN_SPACE;
57
+ const set = columns.equalWidth === false ? columns.widths : undefined;
58
+ if (set?.length)
59
+ return {
60
+ widths: set.map((column) => column.width),
61
+ gaps: set.slice(0, -1).map((column) => column.space ?? space),
62
+ separator,
63
+ };
64
+ const count = Math.max(columns.count ?? 1, 1);
65
+ const width = Math.max((textWidth(section) - space * (count - 1)) / count, 1);
66
+ return {
67
+ widths: Array.from({ length: count }, () => width),
68
+ gaps: Array.from({ length: count - 1 }, () => space),
69
+ separator,
70
+ };
71
+ }
72
+
73
+ /** The width between a section's margins, in twips. */
74
+ function textWidth({ pageSize, margins: m = {} }: SectionJSON): number {
75
+ return (
76
+ (pageSize?.width ?? LETTER.width) -
77
+ (m.left ?? LETTER.margin) -
78
+ (m.right ?? LETTER.margin) -
79
+ (m.gutter ?? 0)
80
+ );
81
+ }
82
+
83
+ /** `section` without the keys whose value is undefined (the schema has no such values). */
84
+ function clean(section: Record<string, unknown>): SectionJSON {
85
+ return Object.fromEntries(
86
+ Object.entries(section).filter(([, value]) => value !== undefined),
87
+ ) as SectionJSON;
88
+ }
89
+
90
+ /** The first paragraph holding a section at or after `from`: null when the last section's. */
91
+ function holderFrom(doc: Node, from: number): { pos: number; node: Node } | null {
92
+ let found: { pos: number; node: Node } | null = null;
93
+ doc.forEach((node, pos) => {
94
+ if (!found && pos + node.nodeSize > from && node.attrs.section) found = { pos, node };
95
+ });
96
+ return found;
97
+ }
98
+
99
+ /**
100
+ * The last section's setup as `tr` leaves it.
101
+ * @internal
102
+ */
103
+ export function lastSection(state: EditorState, tr: Transaction): SectionJSON {
104
+ let section = wordContext(state)?.envelope.section ?? {};
105
+ for (const step of tr.steps)
106
+ if (step instanceof EnvelopeStep && step.key === "section") section = step.after as SectionJSON;
107
+ return section;
108
+ }
109
+
110
+ /** Makes `tr` give the section held at `holder` (null: the last one) the setup `section`. */
111
+ function writeSection(
112
+ state: EditorState,
113
+ tr: Transaction,
114
+ holder: { pos: number; node: Node } | null,
115
+ section: SectionJSON,
116
+ ): void {
117
+ if (holder) tr.setNodeMarkup(holder.pos, holder.node.type, { ...holder.node.attrs, section });
118
+ else setEnvelopeValue(state, tr, "section", section);
119
+ }
120
+
121
+ /** The section around the selection's start. */
122
+ export interface SectionAt {
123
+ setup: SectionJSON;
124
+ /** The paragraph holding it; null for the last section (the envelope's). */
125
+ pos: number | null;
126
+ /** Its place among the document's sections, from 0, and how many there are. */
127
+ index: number;
128
+ count: number;
129
+ }
130
+
131
+ export function sectionAt(state: EditorState): SectionAt | null {
132
+ const context = wordContext(state);
133
+ if (!context) return null;
134
+ // In a story: the section of the body's selection.
135
+ const body = storyBody(state);
136
+ if (body) return sectionAt(body.state);
137
+ const { $from } = state.selection;
138
+ const start = $from.depth ? $from.before(1) : $from.pos;
139
+ let index = 0;
140
+ let count = 1;
141
+ state.doc.forEach((node, pos) => {
142
+ if (!node.attrs.section) return;
143
+ count++;
144
+ if (pos + node.nodeSize <= start) index++;
145
+ });
146
+ const holder = holderFrom(state.doc, start);
147
+ return {
148
+ setup: holder ? (holder.node.attrs.section as SectionJSON) : context.envelope.section,
149
+ pos: holder?.pos ?? null,
150
+ index,
151
+ count,
152
+ };
153
+ }
154
+
155
+ /** How a new section starts. */
156
+ export type SectionBreakKind = "nextPage" | "continuous" | "evenPage" | "oddPage";
157
+
158
+ /**
159
+ * Inserts a section break at the selection's start, in a paragraph of the body: the text before
160
+ * it ends a section with the current setup, the rest starts as `kind` says. Tracked while
161
+ * tracking, as an inserted paragraph mark.
162
+ */
163
+ export function insertSectionBreak(kind: SectionBreakKind = "nextPage"): Command {
164
+ return (state, dispatch) => {
165
+ const context = wordContext(state);
166
+ const { $from } = state.selection;
167
+ if (!context || storyBody(state) || !(state.selection instanceof TextSelection)) return false;
168
+ if ($from.depth !== 1 || $from.parent.type.name !== "paragraph") return false;
169
+ if (dispatch) {
170
+ const tr = state.tr.setMeta(untracked, true).setMeta(closeHistory, true);
171
+ const paragraph = $from.parent;
172
+ const start = $from.before();
173
+ const { before, after } = splitAttrs(
174
+ context,
175
+ paragraph,
176
+ $from.parentOffset === paragraph.content.size,
177
+ );
178
+ tr.split($from.pos, 1, [{ type: paragraph.type, attrs: after }]);
179
+ const second = $from.pos + 1;
180
+ const holder = holderFrom(tr.doc, second);
181
+ const setup = holder ? (holder.node.attrs.section as SectionJSON) : lastSection(state, tr);
182
+ // The first part keeps the section as it is.
183
+ const revision = newRevision(state);
184
+ tr.setNodeMarkup(start, paragraph.type, {
185
+ ...(before ?? paragraph.attrs),
186
+ section: setup,
187
+ ...(revision ? { revision: { insertion: revision } } : {}),
188
+ });
189
+ // A tracked setup change covers both parts: each records it, under an id of its own. What
190
+ // the later part was before it starts as this break says.
191
+ const type = kind === "nextPage" ? undefined : kind;
192
+ const change = setup.change && {
193
+ ...setup.change,
194
+ id: nextRevisionId(state) + (revision ? 1 : 0),
195
+ previous: clean({ ...setup.change.previous, type }),
196
+ };
197
+ writeSection(
198
+ state,
199
+ tr,
200
+ holderFrom(tr.doc, second),
201
+ clean({
202
+ ...setup,
203
+ headers: undefined,
204
+ footers: undefined,
205
+ change,
206
+ type,
207
+ }),
208
+ );
209
+ tr.setSelection(TextSelection.create(tr.doc, $from.pos + 2));
210
+ dispatch(tr);
211
+ }
212
+ return true;
213
+ };
214
+ }
215
+
216
+ /**
217
+ * After the section `removed` ended (its break went): the section that follows `from` takes over
218
+ * its text, keeping its own setup, starting as `removed` started, with the header and footer
219
+ * references it inherited.
220
+ * @internal
221
+ */
222
+ export function absorbSection(
223
+ state: EditorState,
224
+ tr: Transaction,
225
+ removed: SectionJSON,
226
+ from: number,
227
+ ): void {
228
+ const holder = holderFrom(tr.doc, from);
229
+ const setup = holder ? (holder.node.attrs.section as SectionJSON) : lastSection(state, tr);
230
+ const inherited = (own?: Record<string, string>, earlier?: Record<string, string>) =>
231
+ own || earlier ? { ...earlier, ...own } : undefined;
232
+ writeSection(
233
+ state,
234
+ tr,
235
+ holder,
236
+ clean({
237
+ ...setup,
238
+ type: removed.type,
239
+ headers: inherited(setup.headers, removed.headers),
240
+ footers: inherited(setup.footers, removed.footers),
241
+ }),
242
+ );
243
+ }
244
+
245
+ /**
246
+ * Removes the section break that ends the caret's section (in the last section, the one before
247
+ * it): the paragraph joins the next, as deleting Word's break does. While tracking its mark is
248
+ * recorded as deleted.
249
+ */
250
+ export const removeSectionBreak: Command = (state, dispatch) => {
251
+ if (storyBody(state)) return false;
252
+ const at = sectionAt(state);
253
+ if (!at || at.count < 2) return false;
254
+ let pos = at.pos;
255
+ if (pos === null)
256
+ state.doc.forEach((node, offset) => {
257
+ if (node.attrs.section) pos = offset;
258
+ });
259
+ if (pos === null) return false;
260
+ const node = state.doc.nodeAt(pos) as Node;
261
+ if (dispatch) {
262
+ const tr = state.tr.setMeta(untracked, true).setMeta(closeHistory, true);
263
+ const revision = newRevision(state);
264
+ const end = pos + node.nodeSize;
265
+ const next = state.doc.nodeAt(end);
266
+ if (revision)
267
+ tr.setNodeMarkup(pos, node.type, {
268
+ ...node.attrs,
269
+ revision: { ...(node.attrs.revision as object | null), deletion: revision },
270
+ });
271
+ else if (next?.isTextblock) {
272
+ tr.join(end);
273
+ keepLastMark(tr, pos, next);
274
+ absorbSection(state, tr, node.attrs.section as SectionJSON, pos);
275
+ } else {
276
+ tr.setNodeMarkup(pos, node.type, { ...node.attrs, section: null });
277
+ absorbSection(state, tr, node.attrs.section as SectionJSON, end);
278
+ }
279
+ dispatch(tr);
280
+ }
281
+ return true;
282
+ };
283
+
284
+ /** What the page setup dialog changes. `pageSize` and `margins` are merged into the section's. */
285
+ export type SectionSetup = {
286
+ [K in "pageSize" | "margins" | "columns" | "type" | "titlePage"]?: SectionJSON[K] | undefined;
287
+ };
288
+
289
+ /**
290
+ * Changes the page setup of section `index` (by default the caret's). Not when the result has no
291
+ * room for text. While tracking it is recorded with the setup before it (`w:sectPrChange`), once:
292
+ * later changes keep the first record, as Word's does.
293
+ */
294
+ export function setSectionSetup(setup: SectionSetup, index?: number): Command {
295
+ const command: Command = (state, dispatch) => {
296
+ const body = storyBody(state);
297
+ if (body) return dispatch ? body.run(command) : body.can(command);
298
+ const at = index === undefined ? sectionAt(state) : sectionNumber(state, index);
299
+ if (!at) return false;
300
+ const { setup: current } = at;
301
+ const next = clean({
302
+ ...current,
303
+ ...setup,
304
+ pageSize: setup.pageSize ? { ...current.pageSize, ...setup.pageSize } : current.pageSize,
305
+ margins: setup.margins ? { ...current.margins, ...setup.margins } : current.margins,
306
+ });
307
+ if (deepEqual(next, current) || checkSection(next)) return false;
308
+ const m = next.margins ?? {};
309
+ const height =
310
+ (next.pageSize?.height ?? LETTER.height) -
311
+ Math.abs(m.top ?? LETTER.margin) -
312
+ Math.abs(m.bottom ?? LETTER.margin);
313
+ const { widths, gaps } = sectionColumns(next);
314
+ const used = [...widths, ...gaps].reduce((sum, width) => sum + width, 0);
315
+ if (height <= 0 || textWidth(next) <= 0 || used > textWidth(next) + widths.length) return false;
316
+ if (dispatch) {
317
+ const tr = state.tr.setMeta(untracked, true).setMeta(closeHistory, true);
318
+ const revision = newRevision(state);
319
+ if (revision && !current.change)
320
+ next.change = {
321
+ ...revision,
322
+ // What the change can restore: the references stay with the section.
323
+ previous: clean({
324
+ ...current,
325
+ ext: undefined,
326
+ headers: undefined,
327
+ footers: undefined,
328
+ }),
329
+ };
330
+ const holder =
331
+ at.pos === null ? null : { pos: at.pos, node: state.doc.nodeAt(at.pos) as Node };
332
+ writeSection(state, tr, holder, next);
333
+ dispatch(tr);
334
+ }
335
+ return true;
336
+ };
337
+ return command;
338
+ }
339
+
340
+ /** Section `index` of the document, as `sectionAt` gives the caret's. */
341
+ function sectionNumber(state: EditorState, index: number): SectionAt | null {
342
+ const sections = documentSections(state);
343
+ const found = sections[index];
344
+ return found ? { setup: found.setup, pos: found.pos, index, count: sections.length } : null;
345
+ }
346
+
347
+ /** The document's sections in order, each with the paragraph holding it (the last: none). */
348
+ export function documentSections(state: EditorState): { setup: SectionJSON; pos: number | null }[] {
349
+ const body = storyBody(state);
350
+ if (body) return documentSections(body.state);
351
+ const out: { setup: SectionJSON; pos: number | null }[] = [];
352
+ state.doc.forEach((node, pos) => {
353
+ if (node.attrs.section) out.push({ setup: node.attrs.section as SectionJSON, pos });
354
+ });
355
+ const last = wordContext(state)?.envelope.section;
356
+ if (last) out.push({ setup: last, pos: null });
357
+ return out;
358
+ }
359
+
360
+ /** A header or a footer. */
361
+ export type StorySide = "header" | "footer";
362
+ /** Which of a section's headers or footers (Word's `w:type`). */
363
+ export type StoryVariant = "default" | "first" | "even";
364
+
365
+ const REFERENCES = { header: "headers", footer: "footers" } as const;
366
+
367
+ /**
368
+ * The story a section shows for `side` and `variant`: its own, or, linked to the previous section
369
+ * (no reference of its own), the nearest earlier section's. Null when none has one.
370
+ */
371
+ export function storyOfSection(
372
+ sections: readonly SectionJSON[],
373
+ index: number,
374
+ side: StorySide,
375
+ variant: StoryVariant,
376
+ ): { id: string; section: number } | null {
377
+ for (let i = Math.min(index, sections.length - 1); i >= 0; i--) {
378
+ const id = sections[i]?.[REFERENCES[side]]?.[variant];
379
+ if (id) return { id, section: i };
380
+ }
381
+ return null;
382
+ }
383
+
384
+ /**
385
+ * The variant a page shows (ADR-0007, as Word's PDFs of the corpus show): the first page of a
386
+ * section with a different first page, the even one on an even displayed number when the document
387
+ * has even and odd headers, else the default.
388
+ */
389
+ export function pageVariant(
390
+ section: SectionJSON,
391
+ page: { first: boolean; number: number },
392
+ evenAndOdd: boolean,
393
+ ): StoryVariant {
394
+ if (section.titlePage && page.first) return "first";
395
+ return evenAndOdd && page.number % 2 === 0 ? "even" : "default";
396
+ }
397
+
398
+ /** Every story id a section refers to, once per reference. */
399
+ function storyReferences(sections: readonly SectionJSON[]): string[] {
400
+ return sections.flatMap((setup) => [
401
+ ...Object.values(setup.headers ?? {}),
402
+ ...Object.values(setup.footers ?? {}),
403
+ ]);
404
+ }
405
+
406
+ /**
407
+ * A new story id. Random, never counted: the id of a story removed since may still be a
408
+ * relationship of the package the document came from, to another part.
409
+ */
410
+ function freshStoryId(state: EditorState, tr: Transaction): string {
411
+ const used = new Set<string>(wordContext(state)?.stories.keys());
412
+ for (const id of storyReferences(documentSections(state).map((s) => s.setup))) used.add(id);
413
+ for (const step of tr.steps) if (step instanceof StoryStep) used.add(step.id);
414
+ for (;;) {
415
+ const id = `rIdFoli${Math.random().toString(36).slice(2, 12)}`;
416
+ if (!used.has(id)) return id;
417
+ }
418
+ }
419
+
420
+ /** A copy of a story for another section: a bookmark's name is the document's only once. */
421
+ function copyOfStory(state: EditorState, story: Story): Story {
422
+ const tr = storyState(state, story.doc).tr;
423
+ const marks: number[] = [];
424
+ story.doc.descendants((node, pos) => {
425
+ if (node.type.name === "bookmarkStart" || node.type.name === "bookmarkEnd") marks.push(pos);
426
+ return true;
427
+ });
428
+ for (const pos of marks.reverse()) tr.delete(pos, pos + 1);
429
+ return { ...story, doc: tr.doc };
430
+ }
431
+
432
+ /** An empty header or footer, in the document's style for it when it has one. */
433
+ function emptyStory(state: EditorState, side: StorySide): Story {
434
+ const style = wordContext(state)?.envelope.styles.find(
435
+ (s) => s.type === "paragraph" && s.name?.toLowerCase() === side,
436
+ );
437
+ const content: StoryJSON["content"] = {
438
+ type: "doc",
439
+ content: [{ type: "paragraph", ...(style ? { attrs: { style: style.id } } : {}) }],
440
+ };
441
+ return { kind: side, doc: parseContent(content, { schema: state.schema }) };
442
+ }
443
+
444
+ /** Makes `tr` give section `index` the reference `id` for `side` and `variant` (null: none). */
445
+ function setStoryReference(
446
+ state: EditorState,
447
+ tr: Transaction,
448
+ index: number,
449
+ side: StorySide,
450
+ variant: StoryVariant,
451
+ id: string | null,
452
+ ): void {
453
+ const section = documentSections(state)[index] as { setup: SectionJSON; pos: number | null };
454
+ const key = REFERENCES[side];
455
+ const { [variant]: _old, ...others } = section.setup[key] ?? {};
456
+ const refs = id ? { ...others, [variant]: id } : others;
457
+ const holder =
458
+ section.pos === null ? null : { pos: section.pos, node: state.doc.nodeAt(section.pos) as Node };
459
+ writeSection(
460
+ state,
461
+ tr,
462
+ holder,
463
+ clean({ ...section.setup, [key]: Object.keys(refs).length ? refs : undefined }),
464
+ );
465
+ }
466
+
467
+ /**
468
+ * Makes sure section `index` shows a story for `side` and `variant`: when neither it nor an earlier
469
+ * section has one, an empty one is added to the first section, which the others are linked to, as
470
+ * Word's are. The header of a page opens on it.
471
+ */
472
+ export function ensureStory(side: StorySide, variant: StoryVariant, index: number): Command {
473
+ const command: Command = (state, dispatch) => {
474
+ const body = storyBody(state);
475
+ if (body) return dispatch ? body.run(command) : body.can(command);
476
+ const sections = documentSections(state);
477
+ if (!wordContext(state) || index < 0 || index >= sections.length) return false;
478
+ if (
479
+ storyOfSection(
480
+ sections.map((s) => s.setup),
481
+ index,
482
+ side,
483
+ variant,
484
+ )
485
+ )
486
+ return false;
487
+ if (dispatch) {
488
+ const tr = state.tr.setMeta(untracked, true).setMeta(closeHistory, true);
489
+ const id = freshStoryId(state, tr);
490
+ tr.step(new StoryStep(id, null, emptyStory(state, side)));
491
+ setStoryReference(state, tr, 0, side, variant, id);
492
+ dispatch(tr);
493
+ }
494
+ return true;
495
+ };
496
+ return command;
497
+ }
498
+
499
+ /**
500
+ * Links section `index`'s header or footer to the previous section (its own story goes, when no
501
+ * other section uses it), or unlinks it: it gets a copy of what it was showing, as in Word.
502
+ */
503
+ export function setStoryLinked(
504
+ side: StorySide,
505
+ variant: StoryVariant,
506
+ linked: boolean,
507
+ index?: number,
508
+ ): Command {
509
+ const command: Command = (state, dispatch) => {
510
+ const body = storyBody(state);
511
+ if (body) return dispatch ? body.run(command) : body.can(command);
512
+ const context = wordContext(state);
513
+ const at = index ?? sectionAt(state)?.index;
514
+ const sections = documentSections(state);
515
+ if (!context || at === undefined || at < 1 || at >= sections.length) return false;
516
+ const setups = sections.map((s) => s.setup);
517
+ const own = setups[at]?.[REFERENCES[side]]?.[variant];
518
+ if (linked ? !own : !!own) return false;
519
+ if (dispatch) {
520
+ const tr = state.tr.setMeta(untracked, true).setMeta(closeHistory, true);
521
+ if (own) {
522
+ setStoryReference(state, tr, at, side, variant, null);
523
+ // Another section's reference, or another variant's of this one, keeps it.
524
+ const shared = storyReferences(setups).filter((id) => id === own).length > 1;
525
+ const story = storyAfter(state, tr, own);
526
+ if (story && !shared) tr.step(new StoryStep(own, story, null));
527
+ } else {
528
+ const shown = storyOfSection(setups, at - 1, side, variant);
529
+ const copied = shown ? context.stories.get(shown.id) : undefined;
530
+ const id = freshStoryId(state, tr);
531
+ const story = copied ? copyOfStory(state, copied) : emptyStory(state, side);
532
+ tr.step(new StoryStep(id, null, story));
533
+ setStoryReference(state, tr, at, side, variant, id);
534
+ }
535
+ dispatch(tr);
536
+ }
537
+ return true;
538
+ };
539
+ return command;
540
+ }
541
+
542
+ /** Turns a different first page on or off for section `index` (by default the caret's). */
543
+ export const setDifferentFirstPage = (on: boolean, index?: number): Command =>
544
+ setSectionSetup({ titlePage: on ? true : undefined }, index);
545
+
546
+ /** Turns different odd and even pages on or off, for the whole document as in Word. */
547
+ export function setDifferentEvenPages(on: boolean): Command {
548
+ const command: Command = (state, dispatch) => {
549
+ const body = storyBody(state);
550
+ if (body) return dispatch ? body.run(command) : body.can(command);
551
+ const context = wordContext(state);
552
+ if (!context || !!context.envelope.settings?.evenAndOddHeaders === on) return false;
553
+ if (dispatch) {
554
+ const { evenAndOddHeaders: _old, ...rest } = context.envelope.settings ?? {};
555
+ // Said even when off: left out, export would keep what the file says.
556
+ const tr = state.tr.setMeta(untracked, true).setMeta(closeHistory, true);
557
+ setEnvelopeValue(state, tr, "settings", { ...rest, evenAndOddHeaders: on });
558
+ dispatch(tr);
559
+ }
560
+ return true;
561
+ };
562
+ return command;
563
+ }
564
+
565
+ /**
566
+ * `section` once its tracked setup change is accepted, or rejected.
567
+ * @internal
568
+ */
569
+ export function resolveSectionChange(section: SectionJSON, accept: boolean): SectionJSON {
570
+ const { change, ...rest } = section;
571
+ if (accept || !change) return rest;
572
+ return clean({
573
+ ...change.previous,
574
+ headers: section.headers,
575
+ footers: section.footers,
576
+ ext: section.ext,
577
+ });
578
+ }
@@ -40,11 +40,21 @@ export interface PluginSpec<T> {
40
40
  oldState: EditorState,
41
41
  newState: EditorState,
42
42
  ): Transaction | null | undefined;
43
- /** Key name (e.g. "Mod-b", "Shift-Enter") → command. The view normalizes key events to these names. */
43
+ /**
44
+ * Key name (e.g. "Mod-b", "Shift-Enter") → command. The view normalizes key events to these
45
+ * names. A user plugin's keymap runs before the built-in ones, so it can take any key that is
46
+ * not reserved (`docs/keyboard.md`).
47
+ */
44
48
  keymap?: Readonly<Record<string, Command>>;
49
+ /**
50
+ * Named command factories: `editor.commands.<name>(...args)` runs `factory(...args)`. Typed by
51
+ * augmenting `FoliCommands`. A name taken twice, or by a built-in command, throws in
52
+ * `createEditor`.
53
+ */
54
+ commands?: Readonly<Record<string, (...args: never[]) => Command>>;
45
55
  }
46
56
 
47
- /** Internal extension point; built-in features (history, keymap) use the same API. */
57
+ /** A plugin: state, transaction hooks, keys and commands. Built-in features use the same API. */
48
58
  export class Plugin<T = unknown> {
49
59
  readonly key: PluginKey<T>;
50
60
 
@@ -171,7 +181,10 @@ export class Transaction extends Transform {
171
181
  }
172
182
  }
173
183
 
174
- /** The first textblock type of the schema (the "normal paragraph"). */
184
+ /**
185
+ * The first textblock type of the schema (the "normal paragraph").
186
+ * @internal
187
+ */
175
188
  export function defaultTextblockType(schema: Schema): NodeType {
176
189
  const type = Object.values(schema.nodes).find((t) => t.isTextblock);
177
190
  if (!type) throw new RangeError("Schema has no textblock type");
@@ -227,6 +240,11 @@ export class EditorState {
227
240
  return this.applyTransaction(tr).state;
228
241
  }
229
242
 
243
+ /** @internal This state over another tree (a story's, after undo): plugin states stay. */
244
+ withDocument(doc: Node, selection: Selection): EditorState {
245
+ return new EditorState(doc, selection, null, this.plugins, new Map(this.fields));
246
+ }
247
+
230
248
  /** Applies `root` plus any transactions plugins append; returns all that were applied. */
231
249
  applyTransaction(root: Transaction): { state: EditorState; transactions: Transaction[] } {
232
250
  if (!this.passesFilters(root)) return { state: this, transactions: [] };