@folijs/core 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/model/schema.d.ts +9 -1
  3. package/dist/model/schema.d.ts.map +1 -1
  4. package/dist/model/schema.js +13 -3
  5. package/dist/model/schema.js.map +1 -1
  6. package/dist/state/commands.d.ts +10 -1
  7. package/dist/state/commands.d.ts.map +1 -1
  8. package/dist/state/commands.js +125 -40
  9. package/dist/state/commands.js.map +1 -1
  10. package/dist/state/comments.d.ts.map +1 -1
  11. package/dist/state/comments.js +15 -6
  12. package/dist/state/comments.js.map +1 -1
  13. package/dist/state/controls.d.ts +128 -0
  14. package/dist/state/controls.d.ts.map +1 -0
  15. package/dist/state/controls.js +1459 -0
  16. package/dist/state/controls.js.map +1 -0
  17. package/dist/state/editor.d.ts +86 -1
  18. package/dist/state/editor.d.ts.map +1 -1
  19. package/dist/state/editor.js +169 -41
  20. package/dist/state/editor.js.map +1 -1
  21. package/dist/state/fields.d.ts +79 -0
  22. package/dist/state/fields.d.ts.map +1 -0
  23. package/dist/state/fields.js +398 -0
  24. package/dist/state/fields.js.map +1 -0
  25. package/dist/state/fieldupdate.d.ts +178 -0
  26. package/dist/state/fieldupdate.d.ts.map +1 -0
  27. package/dist/state/fieldupdate.js +1574 -0
  28. package/dist/state/fieldupdate.js.map +1 -0
  29. package/dist/state/find.d.ts +68 -0
  30. package/dist/state/find.d.ts.map +1 -0
  31. package/dist/state/find.js +397 -0
  32. package/dist/state/find.js.map +1 -0
  33. package/dist/state/history.d.ts +12 -1
  34. package/dist/state/history.d.ts.map +1 -1
  35. package/dist/state/history.js +43 -7
  36. package/dist/state/history.js.map +1 -1
  37. package/dist/state/index.d.ts +15 -5
  38. package/dist/state/index.d.ts.map +1 -1
  39. package/dist/state/index.js +13 -3
  40. package/dist/state/index.js.map +1 -1
  41. package/dist/state/links.d.ts.map +1 -1
  42. package/dist/state/links.js +30 -19
  43. package/dist/state/links.js.map +1 -1
  44. package/dist/state/mark.d.ts.map +1 -1
  45. package/dist/state/mark.js +8 -1
  46. package/dist/state/mark.js.map +1 -1
  47. package/dist/state/navigation.d.ts +70 -0
  48. package/dist/state/navigation.d.ts.map +1 -0
  49. package/dist/state/navigation.js +226 -0
  50. package/dist/state/navigation.js.map +1 -0
  51. package/dist/state/notes.d.ts +94 -0
  52. package/dist/state/notes.d.ts.map +1 -0
  53. package/dist/state/notes.js +444 -0
  54. package/dist/state/notes.js.map +1 -0
  55. package/dist/state/pictures.d.ts +51 -0
  56. package/dist/state/pictures.d.ts.map +1 -0
  57. package/dist/state/pictures.js +140 -0
  58. package/dist/state/pictures.js.map +1 -0
  59. package/dist/state/review.d.ts +13 -4
  60. package/dist/state/review.d.ts.map +1 -1
  61. package/dist/state/review.js +223 -29
  62. package/dist/state/review.js.map +1 -1
  63. package/dist/state/sections.d.ts +101 -0
  64. package/dist/state/sections.d.ts.map +1 -0
  65. package/dist/state/sections.js +472 -0
  66. package/dist/state/sections.js.map +1 -0
  67. package/dist/state/selection.d.ts +12 -1
  68. package/dist/state/selection.d.ts.map +1 -1
  69. package/dist/state/selection.js +12 -0
  70. package/dist/state/selection.js.map +1 -1
  71. package/dist/state/state.d.ts +2 -0
  72. package/dist/state/state.d.ts.map +1 -1
  73. package/dist/state/state.js +4 -0
  74. package/dist/state/state.js.map +1 -1
  75. package/dist/state/stories.d.ts +41 -0
  76. package/dist/state/stories.d.ts.map +1 -0
  77. package/dist/state/stories.js +243 -0
  78. package/dist/state/stories.js.map +1 -0
  79. package/dist/state/tablecommands.d.ts +77 -0
  80. package/dist/state/tablecommands.d.ts.map +1 -0
  81. package/dist/state/tablecommands.js +675 -0
  82. package/dist/state/tablecommands.js.map +1 -0
  83. package/dist/state/tables.d.ts +110 -0
  84. package/dist/state/tables.d.ts.map +1 -0
  85. package/dist/state/tables.js +730 -0
  86. package/dist/state/tables.js.map +1 -0
  87. package/dist/state/track.d.ts +23 -0
  88. package/dist/state/track.d.ts.map +1 -1
  89. package/dist/state/track.js +113 -15
  90. package/dist/state/track.js.map +1 -1
  91. package/dist/state/word.d.ts +78 -16
  92. package/dist/state/word.d.ts.map +1 -1
  93. package/dist/state/word.js +231 -11
  94. package/dist/state/word.js.map +1 -1
  95. package/dist/state/wordclip.d.ts +15 -6
  96. package/dist/state/wordclip.d.ts.map +1 -1
  97. package/dist/state/wordclip.js +213 -18
  98. package/dist/state/wordclip.js.map +1 -1
  99. package/dist/state/wordformat.d.ts +10 -2
  100. package/dist/state/wordformat.d.ts.map +1 -1
  101. package/dist/state/wordformat.js +98 -17
  102. package/dist/state/wordformat.js.map +1 -1
  103. package/dist/v3/document.d.ts +237 -7
  104. package/dist/v3/document.d.ts.map +1 -1
  105. package/dist/v3/document.js +314 -15
  106. package/dist/v3/document.js.map +1 -1
  107. package/dist/v3/index.d.ts +2 -2
  108. package/dist/v3/index.d.ts.map +1 -1
  109. package/dist/v3/index.js +2 -2
  110. package/dist/v3/index.js.map +1 -1
  111. package/dist/v3/migrate.d.ts +2 -2
  112. package/dist/v3/migrate.d.ts.map +1 -1
  113. package/dist/v3/resolve.d.ts +57 -5
  114. package/dist/v3/resolve.d.ts.map +1 -1
  115. package/dist/v3/resolve.js +224 -16
  116. package/dist/v3/resolve.js.map +1 -1
  117. package/dist/v3/schema.d.ts +6 -0
  118. package/dist/v3/schema.d.ts.map +1 -1
  119. package/dist/v3/schema.js +254 -8
  120. package/dist/v3/schema.js.map +1 -1
  121. package/package.json +1 -1
  122. package/src/model/schema.ts +18 -2
  123. package/src/state/commands.ts +121 -32
  124. package/src/state/comments.ts +14 -6
  125. package/src/state/controls.ts +1596 -0
  126. package/src/state/editor.ts +292 -46
  127. package/src/state/fields.ts +432 -0
  128. package/src/state/fieldupdate.ts +1770 -0
  129. package/src/state/find.ts +510 -0
  130. package/src/state/history.ts +51 -7
  131. package/src/state/index.ts +157 -0
  132. package/src/state/links.ts +27 -17
  133. package/src/state/mark.ts +8 -1
  134. package/src/state/navigation.ts +305 -0
  135. package/src/state/notes.ts +519 -0
  136. package/src/state/numeric-pictures.word.json +172 -0
  137. package/src/state/pictures.ts +168 -0
  138. package/src/state/review.ts +265 -31
  139. package/src/state/sections.ts +571 -0
  140. package/src/state/selection.ts +15 -1
  141. package/src/state/state.ts +5 -0
  142. package/src/state/stories.ts +285 -0
  143. package/src/state/tablecommands.ts +741 -0
  144. package/src/state/tables.ts +761 -0
  145. package/src/state/track.ts +128 -16
  146. package/src/state/word.ts +276 -13
  147. package/src/state/wordclip.ts +231 -32
  148. package/src/state/wordformat.ts +96 -14
  149. package/src/v3/document.ts +572 -16
  150. package/src/v3/index.ts +21 -0
  151. package/src/v3/migrate.ts +2 -2
  152. package/src/v3/resolve.ts +289 -21
  153. package/src/v3/schema.ts +278 -9
@@ -0,0 +1,1459 @@
1
+ /**
2
+ * Word's content controls in the editor (ADR-0007, 11.9). Inline ones are `controlStart` and
3
+ * `controlEnd` markers, block, row and cell ones the `controls` attribute; their properties are the
4
+ * envelope's `controls`, changed through `EnvelopeStep`s so undo takes them back.
5
+ *
6
+ * The rules are Word's, checked through its object model (`scripts/corpus/control-roundtrip.mjs`,
7
+ * ADR-0007): a filter compares what a transaction leaves with what was there, so it holds for
8
+ * typing, paste, deletion, tracked changes and code alike; undo passes.
9
+ */
10
+ import { FoliDocumentError, Fragment, Slice, } from "../model/index.js";
11
+ import { isSafeLink } from "../schema.js";
12
+ import { Mapping } from "../transform/stepmap.js";
13
+ import { TransformError } from "../transform/transform.js";
14
+ import { parseContent } from "../v3/document.js";
15
+ import { attempt } from "./attempt.js";
16
+ import { insertHardBreak, insertText } from "./commands.js";
17
+ import { formatDatePicture } from "./fieldupdate.js";
18
+ import { closeHistory, joinHistory } from "./history.js";
19
+ import { marksAt, Selection, TextSelection } from "./selection.js";
20
+ import { Plugin } from "./state.js";
21
+ import { trackedDeletes, trackTransaction } from "./track.js";
22
+ import { setEnvelopeValue, withEnvelope, wordContext, } from "./word.js";
23
+ import { ensureStyle, styleNamed } from "./wordformat.js";
24
+ /**
25
+ * On a transaction: `value` fills a control, `accept` and `reject` resolve tracked changes, `fields`
26
+ * updates fields: what Word lets through where typing is refused.
27
+ */
28
+ export const controlEdit = "controlEdit";
29
+ const LOCKED_CONTENT = new Set(["contentLocked", "sdtContentLocked"]);
30
+ const LOCKED_CONTROL = new Set(["sdtLocked", "sdtContentLocked"]);
31
+ /** Their content is one run of text. */
32
+ const TEXT_KINDS = new Set(["text", "comboBox", "date"]);
33
+ /** Their content changes only by choosing (a list item, the box's state). */
34
+ const CHOICE_KINDS = new Set(["dropDown", "checkbox", "picture"]);
35
+ /** They have no placeholder to come back to. */
36
+ const NO_PLACEHOLDER = new Set(["checkbox", "picture", "repeating", "repeatingItem", "other"]);
37
+ const REVIEW = new Set(["insertion", "deletion", "formatChange"]);
38
+ /** Word lets a comment be anchored anywhere: they are not what a control holds. */
39
+ const COMMENT_ANCHORS = new Set(["commentStart", "commentEnd", "commentReference"]);
40
+ const isMarkerNode = (node) => node?.type.name === "controlStart" || node?.type.name === "controlEnd";
41
+ const isDeleted = (node) => node.marks.some((m) => m.type.name === "deletion");
42
+ /** Word's text for its built-in placeholders, which need no glossary entry in the file. */
43
+ const BUILT_IN = {
44
+ text: { docPart: "DefaultPlaceholder_-1854013440", text: "Click or tap here to enter text." },
45
+ richText: { docPart: "DefaultPlaceholder_-1854013440", text: "Click or tap here to enter text." },
46
+ dropDown: { docPart: "DefaultPlaceholder_-1854013438", text: "Choose an item." },
47
+ comboBox: { docPart: "DefaultPlaceholder_-1854013438", text: "Choose an item." },
48
+ date: { docPart: "DefaultPlaceholder_-1854013437", text: "Click or tap to enter a date." },
49
+ };
50
+ /** What Word shows in an emptied control whose placeholder it cannot find. */
51
+ const BLANK_PLACEHOLDER = " ";
52
+ const CHECKED = { value: "2612", font: "MS Gothic" };
53
+ const UNCHECKED = { value: "2610", font: "MS Gothic" };
54
+ /** Whether a control's content may not be edited: locked, or filled from bound data. */
55
+ export const controlIsReadOnly = (control) => LOCKED_CONTENT.has(control.lock ?? "") || !!control.binding;
56
+ const scans = new WeakMap();
57
+ function firstCaret(tree, pos) {
58
+ let at = pos;
59
+ for (let node = tree.nodeAt(at); node; node = node.firstChild) {
60
+ if (node.isTextblock)
61
+ return at + 1;
62
+ if (node.isLeaf)
63
+ return pos;
64
+ at++;
65
+ }
66
+ return pos;
67
+ }
68
+ function lastCaret(tree, pos) {
69
+ let at = pos;
70
+ for (let node = tree.resolve(at).nodeBefore; node; node = node.lastChild) {
71
+ if (node.isTextblock)
72
+ return at - 1;
73
+ if (node.isLeaf)
74
+ return pos;
75
+ at--;
76
+ }
77
+ return pos;
78
+ }
79
+ function scan(tree) {
80
+ const known = scans.get(tree);
81
+ if (known)
82
+ return known;
83
+ const ranges = [];
84
+ const unpaired = new Set();
85
+ const inline = (block, start) => {
86
+ const open = [];
87
+ block.forEach((child, offset) => {
88
+ const id = child.attrs.id;
89
+ if (child.type.name === "controlStart")
90
+ open.push({ id, at: start + offset });
91
+ else if (child.type.name === "controlEnd") {
92
+ const index = open.map((o) => o.id).lastIndexOf(id);
93
+ if (index < 0) {
94
+ unpaired.add(id);
95
+ return;
96
+ }
97
+ const { at } = open.splice(index, 1)[0];
98
+ const end = start + offset;
99
+ ranges.push({
100
+ id,
101
+ level: "inline",
102
+ from: at,
103
+ to: end + 1,
104
+ contentFrom: at + 1,
105
+ contentTo: end,
106
+ });
107
+ }
108
+ });
109
+ for (const { id } of open)
110
+ unpaired.add(id);
111
+ };
112
+ const walk = (parent, start) => {
113
+ const open = new Map();
114
+ const runs = [];
115
+ parent.forEach((child, offset, index) => {
116
+ const pos = start + offset;
117
+ const end = pos + child.nodeSize;
118
+ for (const id of child.attrs.controls ?? []) {
119
+ const run = open.get(id);
120
+ if (run && run.index === index - 1) {
121
+ run.index = index;
122
+ run.to = end;
123
+ continue;
124
+ }
125
+ const name = child.type.name;
126
+ const level = name === "tableRow" ? "row" : name === "tableCell" ? "cell" : "block";
127
+ const fresh = { index, from: pos, to: end, level };
128
+ open.set(id, fresh);
129
+ runs.push({ id, run: fresh });
130
+ }
131
+ if (child.isTextblock)
132
+ inline(child, pos + 1);
133
+ else if (!child.isLeaf)
134
+ walk(child, pos + 1);
135
+ });
136
+ for (const { id, run } of runs)
137
+ ranges.push({
138
+ id,
139
+ level: run.level,
140
+ from: run.from,
141
+ to: run.to,
142
+ contentFrom: firstCaret(tree, run.from),
143
+ contentTo: lastCaret(tree, run.to),
144
+ });
145
+ };
146
+ walk(tree, 0);
147
+ ranges.sort((a, b) => a.from - b.from || b.to - a.to);
148
+ const found = { ranges, unpaired };
149
+ scans.set(tree, found);
150
+ return found;
151
+ }
152
+ /** The content controls of `tree` in document order, outer before inner. */
153
+ export const controlsIn = (tree) => scan(tree).ranges;
154
+ /** The innermost control with `pos` inside it (its content's edges included). */
155
+ export function controlAt(tree, pos) {
156
+ let found = null;
157
+ for (const range of controlsIn(tree)) {
158
+ if (range.from >= pos)
159
+ break;
160
+ if (pos < range.to)
161
+ found = range;
162
+ }
163
+ return found;
164
+ }
165
+ /** A control's properties. */
166
+ export const controlProperties = (state, id) => {
167
+ const controls = wordContext(state)?.envelope.controls;
168
+ return controls && Object.hasOwn(controls, id) ? controls[id] : undefined;
169
+ };
170
+ /** Whether only control markers stand between two positions: one place on the screen. */
171
+ export function controlSpot(tree, a, b) {
172
+ if (a === b)
173
+ return true;
174
+ const from = Math.min(a, b);
175
+ const to = Math.max(a, b);
176
+ if (tree.resolve(from).parent !== tree.resolve(to).parent)
177
+ return false;
178
+ let only = true;
179
+ tree.nodesBetween(from, to, (node) => {
180
+ if (node.isInline && !isMarkerNode(node))
181
+ only = false;
182
+ return only;
183
+ });
184
+ return only;
185
+ }
186
+ /**
187
+ * Whether a change at `from..to` is in content that may not be edited: it touches such a control and
188
+ * is not all inside an editable one within it. One whose own deletion is tracked does not count.
189
+ */
190
+ export function readOnlyAt(tree, controls, from, to) {
191
+ if (!controls)
192
+ return false;
193
+ const at = (id) => (Object.hasOwn(controls, id) ? controls[id] : undefined);
194
+ const ranges = controlsIn(tree);
195
+ return ranges.some((range) => {
196
+ const control = at(range.id);
197
+ if (!control || !controlIsReadOnly(control) || control.deleted)
198
+ return false;
199
+ if (range.from >= Math.max(to, from + 1) || from >= range.to)
200
+ return false;
201
+ return !ranges.some((inner) => {
202
+ const own = at(inner.id);
203
+ return (inner !== range &&
204
+ inner.from >= range.from &&
205
+ inner.to <= range.to &&
206
+ inner.from < from &&
207
+ to < inner.to &&
208
+ !!own &&
209
+ !controlIsReadOnly(own));
210
+ });
211
+ });
212
+ }
213
+ const contentOf = (tree, range) => range.level === "inline"
214
+ ? tree.slice(range.from + 1, range.to - 1).content
215
+ : tree.slice(range.from, range.to).content;
216
+ /** Each control of `before` with the index in `after` of the same one (by id, then in order). */
217
+ function pairUp(before, after) {
218
+ const places = new Map();
219
+ after.forEach((range, i) => {
220
+ const list = places.get(range.id);
221
+ if (list)
222
+ list.push(i);
223
+ else
224
+ places.set(range.id, [i]);
225
+ });
226
+ const used = new Map();
227
+ const pairs = new Map();
228
+ for (const range of before) {
229
+ const n = used.get(range.id) ?? 0;
230
+ used.set(range.id, n + 1);
231
+ const at = places.get(range.id)?.[n];
232
+ if (at !== undefined)
233
+ pairs.set(range, at);
234
+ }
235
+ return pairs;
236
+ }
237
+ /** Where two trees differ, in each one's positions: top-level blocks they share lie outside. */
238
+ function changedSpan(a, b) {
239
+ const shared = Math.min(a.childCount, b.childCount);
240
+ let start = 0;
241
+ let fromA = 0;
242
+ while (start < shared && a.child(start) === b.child(start)) {
243
+ fromA += a.child(start).nodeSize;
244
+ start++;
245
+ }
246
+ const fromB = fromA;
247
+ let toA = a.content.size;
248
+ let toB = b.content.size;
249
+ for (let i = 1; i <= shared - start; i++) {
250
+ const node = a.child(a.childCount - i);
251
+ if (node !== b.child(b.childCount - i))
252
+ break;
253
+ toA -= node.nodeSize;
254
+ toB -= node.nodeSize;
255
+ }
256
+ return { fromA, toA, fromB, toB };
257
+ }
258
+ /** The controls directly inside the one at `index` of `ranges`. */
259
+ function innerControls(ranges, index) {
260
+ const outer = ranges[index];
261
+ const inner = [];
262
+ let end = -1;
263
+ for (let i = index + 1; i < ranges.length; i++) {
264
+ const range = ranges[i];
265
+ if (range.from >= outer.to)
266
+ break;
267
+ if (range.to > outer.to || range.from < end)
268
+ continue;
269
+ inner.push(range);
270
+ end = range.to;
271
+ }
272
+ return inner;
273
+ }
274
+ /**
275
+ * What a control holds of its own, as text to compare: not what the controls inside it hold, nor
276
+ * comment anchors. `strict`: its formatting too; otherwise only its tracked changes.
277
+ */
278
+ function signature(tree, range, inner, strict) {
279
+ const [from, to] = range.level === "inline" ? [range.from + 1, range.to - 1] : [range.from, range.to];
280
+ const start = (r) => (r.level === "inline" ? r.contentFrom : r.from);
281
+ const end = (r) => (r.level === "inline" ? r.contentTo : r.to);
282
+ const parts = [];
283
+ let run = null;
284
+ let at = 0;
285
+ let marked = -1;
286
+ tree.nodesBetween(from, to, (node, pos) => {
287
+ while (inner[at] && pos >= end(inner[at]))
288
+ at++;
289
+ const hole = inner[at];
290
+ if (hole && pos >= start(hole)) {
291
+ if (hole.level !== "inline" && marked !== at) {
292
+ marked = at;
293
+ run = null;
294
+ parts.push(`[${hole.id}]`);
295
+ }
296
+ return false;
297
+ }
298
+ if (COMMENT_ANCHORS.has(node.type.name))
299
+ return false;
300
+ const marks = JSON.stringify(node.marks
301
+ .filter((m) => strict || m.type.name === "insertion" || m.type.name === "deletion")
302
+ .map((m) => m.toJSON()));
303
+ if (node.isText) {
304
+ if (run === marks)
305
+ parts[parts.length - 1] += node.text ?? "";
306
+ else
307
+ parts.push(`${marks}:${node.text}`);
308
+ run = marks;
309
+ return false;
310
+ }
311
+ run = null;
312
+ const attrs = strict || node.isInline ? JSON.stringify(node.attrs) : "";
313
+ parts.push(`<${node.type.name}${attrs}${marks}>`);
314
+ return true;
315
+ });
316
+ return parts.join("\u0001");
317
+ }
318
+ /** Whether one of `deleted` (ranges of the same tree) takes in all of `range` and goes past it. */
319
+ const deletedWhole = (range, deleted) => deleted.some(([a, b]) => a <= range.contentFrom &&
320
+ b >= range.contentTo &&
321
+ (a < range.contentFrom || b > range.contentTo));
322
+ function inlineNodes(tree, range) {
323
+ const nodes = [];
324
+ contentOf(tree, range).forEach((node) => {
325
+ if (node.isInline)
326
+ nodes.push(node);
327
+ else
328
+ node.descendants((child) => {
329
+ if (child.isInline)
330
+ nodes.push(child);
331
+ return true;
332
+ });
333
+ });
334
+ return nodes;
335
+ }
336
+ /** Whether a text control's content is still what such a control holds. */
337
+ function holdsText(tree, range, control, was) {
338
+ if (range.level !== "inline") {
339
+ const first = tree.nodeAt(range.from);
340
+ const single = range.level === "cell"
341
+ ? first?.childCount === 1 && first.firstChild?.isTextblock
342
+ : first?.isTextblock && first.nodeSize === range.to - range.from;
343
+ if (!single)
344
+ return false;
345
+ }
346
+ const had = new Set(was.map((n) => n.type.name));
347
+ return inlineNodes(tree, range).every((node) => node.isText ||
348
+ had.has(node.type.name) ||
349
+ COMMENT_ANCHORS.has(node.type.name) ||
350
+ (node.type.name === "hardBreak" && control.multiLine === true));
351
+ }
352
+ /** Whether `tr` keeps what the controls of `state` require. */
353
+ function allowed(tr, state) {
354
+ if (!tr.docChanged || tr.doc === state.doc || tr.getMeta("historyOp"))
355
+ return true;
356
+ const controls = wordContext(state)?.envelope.controls;
357
+ if (!controls)
358
+ return true;
359
+ const before = scan(state.doc);
360
+ if (!before.ranges.length)
361
+ return true;
362
+ const after = scan(tr.doc);
363
+ const edit = tr.getMeta(controlEdit);
364
+ const deleted = (tr.getMeta(trackedDeletes) ?? []);
365
+ const pairs = pairUp(before.ranges, after.ranges);
366
+ const span = changedSpan(state.doc, tr.doc);
367
+ for (const [index, range] of before.ranges.entries()) {
368
+ const control = Object.hasOwn(controls, range.id) ? controls[range.id] : undefined;
369
+ if (!control)
370
+ continue;
371
+ // A paragraph mark cannot go inside an inline control, nor half of one be deleted.
372
+ if (after.unpaired.has(range.id) && !before.unpaired.has(range.id))
373
+ return false;
374
+ const at = pairs.get(range);
375
+ if (at === undefined) {
376
+ if (LOCKED_CONTROL.has(control.lock ?? ""))
377
+ return false;
378
+ continue;
379
+ }
380
+ if (range.to <= span.fromA || range.from >= span.toA)
381
+ continue;
382
+ const now = after.ranges[at];
383
+ if (contentOf(state.doc, range).eq(contentOf(tr.doc, now)))
384
+ continue;
385
+ // The control itself deleted while tracking: as when it is deleted, what it holds is not edited.
386
+ if (deletedWhole(range, deleted)) {
387
+ if (LOCKED_CONTROL.has(control.lock ?? ""))
388
+ return false;
389
+ continue;
390
+ }
391
+ if (edit === "fields" || edit === "accept" || edit === "reject")
392
+ continue;
393
+ const readOnly = controlIsReadOnly(control);
394
+ if (readOnly || (CHOICE_KINDS.has(control.kind) && !edit)) {
395
+ const was = signature(state.doc, range, innerControls(before.ranges, index), readOnly);
396
+ if (was !== signature(tr.doc, now, innerControls(after.ranges, at), readOnly))
397
+ return false;
398
+ continue;
399
+ }
400
+ if (TEXT_KINDS.has(control.kind) &&
401
+ !holdsText(tr.doc, now, control, inlineNodes(state.doc, range)))
402
+ return false;
403
+ }
404
+ return true;
405
+ }
406
+ // ---------- the placeholder ----------
407
+ function placeholderId(context) {
408
+ return styleNamed(context, "Placeholder Text", "character");
409
+ }
410
+ const placeholderText = (control) => control.placeholder?.text ??
411
+ (control.placeholder?.docPart?.startsWith("DefaultPlaceholder_")
412
+ ? (BUILT_IN[control.kind]?.text ?? BLANK_PLACEHOLDER)
413
+ : BLANK_PLACEHOLDER);
414
+ /** The placeholder's run, and the envelope with its style added when it was missing. */
415
+ function placeholderRun(state, control, envelope) {
416
+ const text = placeholderText(control);
417
+ if (text === BLANK_PLACEHOLDER)
418
+ return { run: state.schema.text(text), envelope };
419
+ const style = ensureStyle({ envelope }, "Placeholder Text", "character");
420
+ const mark = style && state.schema.marks.characterStyle?.create({ id: style.id });
421
+ return {
422
+ run: state.schema.text(text, mark ? [mark] : []),
423
+ envelope: style?.envelope ?? envelope,
424
+ };
425
+ }
426
+ /** Whether `range` of the tree before `tr` has nothing in it now. */
427
+ const isEmpty = (range, tr) => tr.mapping.map(range.contentFrom, 1) >= tr.mapping.map(range.contentTo, -1);
428
+ /** The formatting of text put in a control showing its placeholder (`w:sdtPr/w:rPr`). */
429
+ const formatOf = (state, control) => (control.format ?? []).map((mark) => state.schema.markFromJSON(mark));
430
+ /**
431
+ * The text of `from..to`, put in place of a placeholder: without the placeholder's style (`style`),
432
+ * with the control's `format` where it says nothing of its own on the point.
433
+ */
434
+ function leavePlaceholderLook(tr, from, to, style, format) {
435
+ tr.doc.nodesBetween(from, to, (node, pos) => {
436
+ if (!node.isText)
437
+ return true;
438
+ const end = pos + node.nodeSize;
439
+ const placeholder = (mark) => !!style &&
440
+ ((mark.type.name === "characterStyle" && mark.attrs.id === style) ||
441
+ (mark.type.name === "runExt" && String(mark.attrs.xml).includes(`"${style}"`)));
442
+ for (const mark of node.marks)
443
+ if (placeholder(mark))
444
+ tr.removeMark(pos, end, mark);
445
+ // The text's own marks, the placeholder's style not among them, win over the control's.
446
+ const own = node.marks.filter((m) => !placeholder(m));
447
+ for (const mark of format)
448
+ if (!own.some((m) => m.type === mark.type))
449
+ tr.addMark(pos, end, mark);
450
+ return false;
451
+ });
452
+ }
453
+ /** Whether what a check box shows is its checked state; null when it shows neither. */
454
+ function boxShowsChecked(tree, range, control) {
455
+ const checked = control.checkedState ?? CHECKED;
456
+ const unchecked = control.uncheckedState ?? UNCHECKED;
457
+ const shown = textIn(tree, range);
458
+ if (shown === glyph(checked))
459
+ return true;
460
+ if (shown === glyph(unchecked))
461
+ return false;
462
+ // A symbol font's character is kept as Word's `w:sym`: its code is the state's, moved to U+F0xx.
463
+ for (const node of inlineNodes(tree, range)) {
464
+ const code = /:char="([0-9a-f]+)"/i.exec(String(node.attrs.xml ?? ""))?.[1];
465
+ if (!code || isDeleted(node))
466
+ continue;
467
+ const low = Number.parseInt(code, 16) & 0xff;
468
+ if (low === (Number.parseInt(checked.value, 16) & 0xff))
469
+ return true;
470
+ if (low === (Number.parseInt(unchecked.value, 16) & 0xff))
471
+ return false;
472
+ }
473
+ return null;
474
+ }
475
+ /** The months' names in `locale`, long and short; `null` where the platform has none. */
476
+ function monthNames(locale) {
477
+ try {
478
+ return ["long", "short"].map((month) => {
479
+ const format = new Intl.DateTimeFormat(locale, {
480
+ month: month,
481
+ timeZone: "UTC",
482
+ });
483
+ return Array.from({ length: 12 }, (_, m) => format
484
+ .format(Date.UTC(2024, m, 1))
485
+ .toLowerCase()
486
+ .replace(/\.$/, ""));
487
+ });
488
+ }
489
+ catch {
490
+ return null;
491
+ }
492
+ }
493
+ /**
494
+ * The date `text` says in the control's format and language, as `w:fullDate`; null when it is not
495
+ * one. Word reads a control's text so: a date typed, or brought back by rejecting a change.
496
+ */
497
+ function dateFromText(control, text) {
498
+ const locale = control.ext && /:lid\b[^>]*:val="([^"]+)"/.exec(control.ext)?.[1];
499
+ const names = monthNames(locale || "en-US") ?? [];
500
+ const fields = [];
501
+ const pattern = (control.dateFormat ?? "d MMMM yyyy").replace(/'[^']*'|d+|M+|y+|[Hhms]+|[AaPp]{2}|[.*+?^${}()|[\]\\/]/g, (token) => {
502
+ if (token[0] === "'")
503
+ return token.slice(1, -1).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
504
+ if (/^[.*+?^${}()|[\]\\/]$/.test(token))
505
+ return `\\${token}`;
506
+ if (token[0] === "d" && token.length > 2)
507
+ return "\\p{L}+\\.?";
508
+ if (token[0] === "d" || token[0] === "y" || token[0] === "M")
509
+ fields.push(token);
510
+ if (token[0] === "M" && token.length > 2)
511
+ return "(\\p{L}+)\\.?";
512
+ return token[0] === "d" || token[0] === "M" || token[0] === "y" ? "(\\d+)" : "\\S+";
513
+ });
514
+ const found = new RegExp(`^\\s*${pattern}\\s*$`, "iu").exec(text);
515
+ if (!found)
516
+ return null;
517
+ let [day, month, year] = [0, 0, 0];
518
+ fields.forEach((field, i) => {
519
+ const value = found[i + 1];
520
+ if (field[0] === "d")
521
+ day = Number(value);
522
+ else if (field[0] === "y")
523
+ year = Number(value) + (field.length < 3 ? 2000 : 0);
524
+ else if (field.length < 3)
525
+ month = Number(value);
526
+ else {
527
+ const name = value.toLowerCase();
528
+ for (const list of names)
529
+ if (list.includes(name))
530
+ month = list.indexOf(name) + 1;
531
+ }
532
+ });
533
+ return dayFromParts(year, month, day);
534
+ }
535
+ /** `yyyy-mm-ddT00:00:00Z`, or null for a day the calendar does not have. */
536
+ function dayFromParts(year, month, day) {
537
+ const date = new Date(Date.UTC(2000, month - 1, day));
538
+ date.setUTCFullYear(year, month - 1, day);
539
+ if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
540
+ return null;
541
+ const pad = (n, size = 2) => String(n).padStart(size, "0");
542
+ return `${pad(year, 4)}-${pad(month)}-${pad(day)}T00:00:00Z`;
543
+ }
544
+ /** Gives every text run of a text control the formatting a change gave one of them. */
545
+ function evenMarks(tr, from, to, was) {
546
+ const own = (node) => node.marks.filter((m) => !REVIEW.has(m.type.name));
547
+ const runs = [];
548
+ tr.doc.nodesBetween(from, to, (node, pos) => {
549
+ if (node.isText)
550
+ runs.push({ node, pos });
551
+ return true;
552
+ });
553
+ const sameMarks = (a, b) => a.length === b.length && a.every((m) => b.some((o) => o.eq(m)));
554
+ if (!runs.length)
555
+ return;
556
+ const first = own(runs[0].node);
557
+ if (runs.every((r) => sameMarks(own(r.node), first)))
558
+ return;
559
+ const wanted = runs.map((r) => own(r.node)).find((m) => !was || !sameMarks(m, was)) ?? first;
560
+ for (const { node, pos } of runs) {
561
+ const end = pos + node.nodeSize;
562
+ for (const mark of own(node))
563
+ if (!wanted.some((m) => m.eq(mark)))
564
+ tr.removeMark(pos, end, mark);
565
+ for (const mark of wanted)
566
+ if (!mark.isInSet(node.marks))
567
+ tr.addMark(pos, end, mark);
568
+ }
569
+ }
570
+ /**
571
+ * What follows a change, added to `tr`: placeholders left or come back, what a control says of its
572
+ * content (a date, a check box) after the content moved, even formatting. Returns the controls'
573
+ * properties as `tr` leaves them.
574
+ */
575
+ function reconcile(tr, roots, old, state) {
576
+ const envelopeNow = wordContext(state).envelope;
577
+ const current = envelopeNow.controls;
578
+ const oldControls = wordContext(old)?.envelope.controls;
579
+ const before = controlsIn(old.doc);
580
+ const after = controlsIn(tr.doc);
581
+ if (!oldControls || !before.length || !after.length)
582
+ return current;
583
+ const earlierOf = new Map();
584
+ for (const [range, at] of pairUp(before, after))
585
+ earlierOf.set(after[at], range);
586
+ const span = changedSpan(old.doc, state.doc);
587
+ const mapping = new Mapping(roots.flatMap((t) => t.mapping.maps));
588
+ const edit = roots.map((t) => t.getMeta(controlEdit)).find(Boolean);
589
+ const reviewed = edit === "accept" || edit === "reject";
590
+ const deleted = roots.flatMap((t) => (t.getMeta(trackedDeletes) ?? []));
591
+ let envelope = envelopeNow;
592
+ const controls = { ...current };
593
+ let changed = false;
594
+ const set = (id, control) => {
595
+ controls[id] = control;
596
+ changed = true;
597
+ };
598
+ const showPlaceholder = (range, control) => {
599
+ const made = placeholderRun(state, control, envelope);
600
+ envelope = made.envelope;
601
+ tr.insert(tr.mapping.map(range.contentFrom, -1), made.run);
602
+ if (!control.placeholder?.showing)
603
+ set(range.id, { ...control, placeholder: { ...control.placeholder, showing: true } });
604
+ };
605
+ /** The control goes, what it holds staying. */
606
+ const unwrap = (range) => {
607
+ if (range.level === "inline") {
608
+ tr.delete(tr.mapping.map(range.to, -1) - 1, tr.mapping.map(range.to, -1));
609
+ const start = tr.mapping.map(range.from, 1);
610
+ tr.delete(start, start + 1);
611
+ return;
612
+ }
613
+ const doc = tr.doc;
614
+ doc.nodesBetween(tr.mapping.map(range.from, 1), tr.mapping.map(range.to, -1), (node, pos) => {
615
+ const ids = node.attrs.controls;
616
+ if (ids?.includes(range.id)) {
617
+ const rest = ids.filter((id) => id !== range.id);
618
+ tr.setNodeMarkup(pos, node.type, { ...node.attrs, controls: rest.length ? rest : null });
619
+ }
620
+ return true;
621
+ });
622
+ };
623
+ for (const range of [...after].reverse()) {
624
+ if (range.to <= span.fromB || range.from >= span.toB)
625
+ continue;
626
+ let control = Object.hasOwn(controls, range.id) ? controls[range.id] : undefined;
627
+ const earlier = earlierOf.get(range);
628
+ if (!control || !earlier)
629
+ continue;
630
+ if (contentOf(old.doc, earlier).eq(contentOf(state.doc, range)))
631
+ continue;
632
+ // Deleted whole while tracking: accepting takes the control too, rejecting gives it back.
633
+ if (deletedWhole(earlier, deleted)) {
634
+ if (!control.deleted)
635
+ set(range.id, { ...control, deleted: true });
636
+ continue;
637
+ }
638
+ if (control.deleted && reviewed) {
639
+ const { deleted: _deleted, ...rest } = control;
640
+ if (edit === "accept" && !isEmpty(range, tr))
641
+ continue;
642
+ set(range.id, rest);
643
+ if (edit === "accept") {
644
+ unwrap(range);
645
+ continue;
646
+ }
647
+ control = rest;
648
+ }
649
+ const wasShowing = oldControls[range.id]?.placeholder?.showing === true;
650
+ if (wasShowing) {
651
+ // What remains of the placeholder goes (tracking keeps a deleted copy: Word records none).
652
+ const start = tr.mapping.map(mapping.map(earlier.contentFrom, 1), 1);
653
+ const end = tr.mapping.map(mapping.map(earlier.contentTo, -1), -1);
654
+ if (start < end)
655
+ tr.delete(start, end);
656
+ }
657
+ if (isEmpty(range, tr) && !NO_PLACEHOLDER.has(control.kind)) {
658
+ showPlaceholder(range, control);
659
+ continue;
660
+ }
661
+ if (wasShowing) {
662
+ // The text put there takes the control's formatting, not the placeholder's.
663
+ leavePlaceholderLook(tr, tr.mapping.map(range.contentFrom, -1), tr.mapping.map(range.contentTo, 1), placeholderId({ envelope }), formatOf(state, control));
664
+ if (control.placeholder?.showing) {
665
+ control = { ...control, placeholder: { ...control.placeholder, showing: false } };
666
+ set(range.id, control);
667
+ }
668
+ }
669
+ if (control.kind === "checkbox" && reviewed) {
670
+ const checked = boxShowsChecked(state.doc, range, control);
671
+ if (checked !== null && checked !== control.checked)
672
+ set(range.id, { ...control, checked });
673
+ }
674
+ if (edit === "value" || edit === "fields")
675
+ continue;
676
+ if (control.kind === "date") {
677
+ const text = textIn(state.doc, range);
678
+ if (wasShowing || text !== textIn(old.doc, earlier)) {
679
+ const { date, ...rest } = control;
680
+ const read = dateFromText(control, text);
681
+ if (read !== (date ?? null))
682
+ set(range.id, read ? { ...rest, date: read } : rest);
683
+ }
684
+ }
685
+ if (TEXT_KINDS.has(control.kind) && !wasShowing && !reviewed) {
686
+ const first = inlineNodes(old.doc, earlier).find((n) => n.isText);
687
+ evenMarks(tr, tr.mapping.map(range.contentFrom, -1), tr.mapping.map(range.contentTo, 1), first ? first.marks.filter((m) => !REVIEW.has(m.type.name)) : null);
688
+ }
689
+ }
690
+ if (envelope !== envelopeNow)
691
+ withEnvelope(tr, envelope);
692
+ if (!changed)
693
+ return current;
694
+ setEnvelopeValue(state, tr, "controls", controls);
695
+ return controls;
696
+ }
697
+ /** A caret or range as the controls want it, or null when it may stay. */
698
+ function settle(tree, selection, previous, sameDoc, controls) {
699
+ if (!(selection instanceof TextSelection))
700
+ return null;
701
+ const ranges = controlsIn(tree);
702
+ if (!ranges.length)
703
+ return null;
704
+ let { anchor, head } = selection;
705
+ const within = (r, pos) => r.from < pos && pos < r.to;
706
+ // A range with one end in an inline control and the other outside takes the control whole,
707
+ // unless the outer end is at its edge: the same place on the screen as just inside it.
708
+ if (anchor !== head)
709
+ for (let round = 0, again = true; again && round < 8; round++) {
710
+ again = false;
711
+ for (const r of ranges) {
712
+ if (r.level !== "inline" || within(r, anchor) === within(r, head))
713
+ continue;
714
+ again = true;
715
+ const anchorIn = within(r, anchor);
716
+ const out = anchorIn ? head : anchor;
717
+ const edge = out <= r.from ? r.contentFrom : r.contentTo;
718
+ if (controlSpot(tree, out, edge)) {
719
+ if (anchorIn)
720
+ head = edge;
721
+ else
722
+ anchor = edge;
723
+ }
724
+ else if (anchorIn)
725
+ anchor = out <= r.from ? r.to : r.from;
726
+ else
727
+ head = out <= r.from ? r.to : r.from;
728
+ }
729
+ }
730
+ const from = Math.min(anchor, head);
731
+ const to = Math.max(anchor, head);
732
+ const range = controlAt(tree, from);
733
+ const control = range && Object.hasOwn(controls, range.id) ? controls[range.id] : undefined;
734
+ if (range &&
735
+ control?.placeholder?.showing &&
736
+ to < range.to &&
737
+ range.contentFrom < range.contentTo) {
738
+ const { contentFrom, contentTo } = range;
739
+ const whole = from === contentFrom && to === contentTo;
740
+ const wasWhole = sameDoc && previous.from === contentFrom && previous.to === contentTo;
741
+ if (from === to && wasWhole && (from === contentFrom || from === contentTo)) {
742
+ // Leaving: the arrow keys and the like collapse it to one end.
743
+ if (range.level === "inline") {
744
+ anchor = from === contentTo ? range.to : range.from;
745
+ head = anchor;
746
+ }
747
+ else
748
+ return Selection.near(tree.resolve(from === contentTo ? range.to : range.from), from === contentTo ? 1 : -1);
749
+ }
750
+ else if (!whole) {
751
+ anchor = contentFrom;
752
+ head = contentTo;
753
+ }
754
+ }
755
+ return anchor === selection.anchor && head === selection.head
756
+ ? null
757
+ : TextSelection.create(tree, anchor, head);
758
+ }
759
+ // ---------- keys ----------
760
+ const selectContent = (state, dispatch, range) => {
761
+ dispatch?.(state.tr.setSelection(TextSelection.create(state.doc, range.contentFrom, range.contentTo)));
762
+ return true;
763
+ };
764
+ const showingAt = (state) => {
765
+ const { from, to } = state.selection;
766
+ const range = controlAt(state.doc, from);
767
+ return range &&
768
+ controlProperties(state, range.id)?.placeholder?.showing &&
769
+ from === range.contentFrom &&
770
+ to === range.contentTo
771
+ ? range
772
+ : null;
773
+ };
774
+ /**
775
+ * Backspace (`forward` false) and Delete at a control's edge, as in Word: from inside nothing
776
+ * happens; arriving from outside selects its content; a placeholder is not deleted.
777
+ */
778
+ const edgeKey = (forward) => (state, dispatch) => {
779
+ if (!wordContext(state)?.envelope.controls)
780
+ return false;
781
+ if (showingAt(state))
782
+ return true;
783
+ const { selection, doc } = state;
784
+ if (!selection.empty || !(selection instanceof TextSelection))
785
+ return false;
786
+ const { $from } = selection;
787
+ const next = forward ? $from.nodeAfter : $from.nodeBefore;
788
+ if (isMarkerNode(next)) {
789
+ const entering = next?.type.name === (forward ? "controlStart" : "controlEnd");
790
+ if (!entering)
791
+ return true;
792
+ const range = controlAt(doc, $from.pos + (forward ? 1 : -1));
793
+ return range ? selectContent(state, dispatch, range) : false;
794
+ }
795
+ if (forward ? $from.parentOffset < $from.parent.content.size : $from.parentOffset > 0)
796
+ return false;
797
+ const here = controlsIn(doc).filter((r) => r.level !== "inline");
798
+ if (here.some((r) => (forward ? r.contentTo : r.contentFrom) === $from.pos))
799
+ return true;
800
+ // At the edge of a block next to a control: its content is what the key reaches.
801
+ const beside = forward ? $from.after() : $from.before();
802
+ const range = here.find((r) => (forward ? r.from : r.to) === beside);
803
+ return range ? selectContent(state, dispatch, range) : false;
804
+ };
805
+ const enterKey = (state, dispatch) => {
806
+ const range = controlAt(state.doc, state.selection.from);
807
+ const control = range && controlProperties(state, range.id);
808
+ if (!range || !control)
809
+ return false;
810
+ if (showingAt(state))
811
+ return true;
812
+ if (TEXT_KINDS.has(control.kind))
813
+ return control.multiLine ? insertHardBreak(state, dispatch) : true;
814
+ return range.level === "inline";
815
+ };
816
+ const spaceKey = (state, dispatch) => {
817
+ const range = controlAt(state.doc, state.selection.from);
818
+ const control = range && controlProperties(state, range.id);
819
+ if (!range || control?.kind !== "checkbox")
820
+ return false;
821
+ setControlValue(range.id, !control.checked)(state, dispatch);
822
+ return true;
823
+ };
824
+ /** The rules of content controls (ADR-0007), in every editor of a document. */
825
+ export function controlsPlugin() {
826
+ return new Plugin({
827
+ filterTransaction: allowed,
828
+ appendTransaction(transactions, before, after) {
829
+ const controls = wordContext(after)?.envelope.controls;
830
+ if (!controls)
831
+ return null;
832
+ const tr = after.tr;
833
+ const held = before.doc !== after.doc && !transactions.some((t) => t.getMeta("historyOp"))
834
+ ? reconcile(tr, transactions, before, after)
835
+ : controls;
836
+ const selection = settle(tr.doc, tr.selection, before.selection, before.doc === after.doc, held);
837
+ if (selection)
838
+ tr.setSelection(selection);
839
+ return tr.steps.length || selection ? tr : null;
840
+ },
841
+ keymap: { Backspace: edgeKey(false), Delete: edgeKey(true), Enter: enterKey, " ": spaceKey },
842
+ });
843
+ }
844
+ function textIn(tree, range) {
845
+ let text = "";
846
+ let blocks = 0;
847
+ const visit = (node) => {
848
+ if (node.isTextblock && blocks++)
849
+ text += "\n";
850
+ if (node.isInline) {
851
+ if (isDeleted(node))
852
+ return;
853
+ if (node.isText)
854
+ text += node.text;
855
+ else if (node.type.name === "hardBreak")
856
+ text += "\n";
857
+ else if (node.type.name === "tab")
858
+ text += "\t";
859
+ return;
860
+ }
861
+ node.forEach(visit);
862
+ };
863
+ contentOf(tree, range).forEach(visit);
864
+ return text;
865
+ }
866
+ const shownItem = (control, text) => control.items?.find((item) => (item.display ?? item.value) === text);
867
+ /** The values of the controls of this tree, in document order (each control once). */
868
+ export function controlValues(state) {
869
+ const seen = new Set();
870
+ const out = [];
871
+ for (const range of controlsIn(state.doc)) {
872
+ const control = controlProperties(state, range.id);
873
+ if (!control || seen.has(range.id))
874
+ continue;
875
+ seen.add(range.id);
876
+ const showing = control.placeholder?.showing === true;
877
+ const text = showing ? "" : textIn(state.doc, range);
878
+ let value = showing ? null : text;
879
+ if (control.kind === "checkbox")
880
+ value = control.checked === true;
881
+ else if (showing)
882
+ value = null;
883
+ else if (control.kind === "dropDown" || control.kind === "comboBox")
884
+ value = shownItem(control, text)?.value ?? text;
885
+ else if (control.kind === "date")
886
+ value = control.date?.slice(0, 10) ?? text;
887
+ else if (!["text", "richText"].includes(control.kind))
888
+ value = null;
889
+ out.push({
890
+ id: range.id,
891
+ kind: control.kind,
892
+ ...(control.tag !== undefined ? { tag: control.tag } : {}),
893
+ ...(control.alias !== undefined ? { title: control.alias } : {}),
894
+ showingPlaceholder: showing,
895
+ text,
896
+ value,
897
+ ...(control.kind === "richText" && !showing
898
+ ? {
899
+ content: (range.level === "cell"
900
+ ? state.doc.slice(range.from + 1, range.to - 1).content
901
+ : contentOf(state.doc, range)).toJSON(),
902
+ }
903
+ : {}),
904
+ });
905
+ }
906
+ return out;
907
+ }
908
+ function targets(state, target) {
909
+ const ranges = controlsIn(state.doc);
910
+ const byId = ranges.filter((r) => r.id === target);
911
+ return byId.length ? byId : ranges.filter((r) => controlProperties(state, r.id)?.tag === target);
912
+ }
913
+ /** The `yyyy-mm-dd` of a date given as a `Date` (its local day) or text starting with one. */
914
+ function dayOf(value) {
915
+ if (value instanceof Date) {
916
+ if (Number.isNaN(value.getTime()))
917
+ return null;
918
+ return dayFromParts(value.getFullYear(), value.getMonth() + 1, value.getDate());
919
+ }
920
+ const parts = typeof value === "string" ? /^(\d{4})-(\d{2})-(\d{2})/.exec(value) : null;
921
+ return parts ? dayFromParts(Number(parts[1]), Number(parts[2]), Number(parts[3])) : null;
922
+ }
923
+ function formatDate(control, date) {
924
+ const [y, m, d] = date.slice(0, 10).split("-").map(Number);
925
+ return formatDatePicture(new Date(y, m - 1, d), control.dateFormat ?? "d MMMM yyyy");
926
+ }
927
+ /** A check box state's character; a code that is none shows as Word's box would. */
928
+ function glyph(state) {
929
+ const code = /^[0-9a-f]{1,6}$/i.test(state.value) ? Number.parseInt(state.value, 16) : -1;
930
+ return code >= 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff)
931
+ ? String.fromCodePoint(code)
932
+ : "\u2610";
933
+ }
934
+ /** The inline nodes of `text`: line breaks as breaks where the control takes them. */
935
+ function textNodes(state, text, marks) {
936
+ const { schema } = state;
937
+ return text
938
+ .split("\n")
939
+ .flatMap((line, i) => [
940
+ ...(i ? [schema.nodes.hardBreak?.create(null, null, marks)] : []),
941
+ ...(line ? [schema.text(line, marks)] : []),
942
+ ]);
943
+ }
944
+ /** The first run's formatting: what a new value keeps of the old one. */
945
+ function valueMarks(state, range, control) {
946
+ if (control.placeholder?.showing)
947
+ return formatOf(state, control);
948
+ const run = inlineNodes(state.doc, range).find((n) => n.isText);
949
+ return run ? run.marks.filter((m) => !REVIEW.has(m.type.name)) : [];
950
+ }
951
+ /** The content and properties `value` gives a control; null when it cannot hold it. */
952
+ function valueFor(state, range, control, value) {
953
+ if (!takesText(state.doc, range) && !(control.kind === "richText" && isBlocks(value)))
954
+ return null;
955
+ const marks = valueMarks(state, range, control);
956
+ const shown = control;
957
+ if (value === null || value === "") {
958
+ if (control.kind === "checkbox")
959
+ return null;
960
+ return { nodes: [], control };
961
+ }
962
+ const text = (string) => ({
963
+ nodes: textNodes(state, string, marks),
964
+ control: shown,
965
+ });
966
+ switch (control.kind) {
967
+ case "text":
968
+ if (typeof value !== "string")
969
+ return null;
970
+ return text(control.multiLine ? value : value.replace(/\r\n?|\n/g, " "));
971
+ case "richText": {
972
+ if (typeof value === "string")
973
+ return text(value);
974
+ if (typeof value !== "object" || value instanceof Date)
975
+ return null;
976
+ if (!Array.isArray(value.content) || !safeContent(state, range, value.content))
977
+ return null;
978
+ if (!value.content.length)
979
+ return { nodes: [], control };
980
+ if (range.level === "row") {
981
+ const rows = value.content.map((json) => state.schema.nodeFromJSON(json));
982
+ return rows.every((n) => n.type.name === "tableRow")
983
+ ? { nodes: rows, blocks: true, control: shown }
984
+ : null;
985
+ }
986
+ const nodes = value.content.every((json) => state.schema.nodes[json.type]?.isInline)
987
+ ? value.content.map((json) => state.schema.nodeFromJSON(json))
988
+ : blocksFrom(value.content);
989
+ if (nodes.every((n) => n.isInline))
990
+ return { nodes, control: shown };
991
+ if (range.level === "inline") {
992
+ const only = nodes.length === 1 ? nodes[0] : undefined;
993
+ if (!only?.isTextblock)
994
+ return null;
995
+ const inner = [];
996
+ only.forEach((n) => {
997
+ inner.push(n);
998
+ });
999
+ return { nodes: inner, control: shown };
1000
+ }
1001
+ // Word's rule for what ends a body or a cell.
1002
+ if (nodes.at(-1)?.type.name === "table")
1003
+ return null;
1004
+ return { nodes, blocks: true, control: shown };
1005
+ }
1006
+ case "dropDown":
1007
+ case "comboBox": {
1008
+ if (typeof value !== "string")
1009
+ return null;
1010
+ const item = control.items?.find((i) => i.value === value || i.display === value);
1011
+ if (!item && control.kind === "dropDown")
1012
+ return null;
1013
+ return text(item ? (item.display ?? item.value) : value);
1014
+ }
1015
+ case "date": {
1016
+ const day = dayOf(value);
1017
+ if (day) {
1018
+ return { ...text(formatDate(control, day)), control: { ...shown, date: day } };
1019
+ }
1020
+ if (typeof value !== "string")
1021
+ return null;
1022
+ const { date: _date, ...rest } = shown;
1023
+ return { ...text(value), control: rest };
1024
+ }
1025
+ case "checkbox": {
1026
+ if (typeof value !== "boolean")
1027
+ return null;
1028
+ const state2 = value
1029
+ ? (control.checkedState ?? CHECKED)
1030
+ : (control.uncheckedState ?? UNCHECKED);
1031
+ const type = state.schema.marks.font;
1032
+ const font = type && state2.font ? fontMark(type, state2.font) : null;
1033
+ const kept = marks.filter((m) => m.type !== type);
1034
+ return {
1035
+ nodes: [state.schema.text(glyph(state2), font ? font.addToSet(kept) : marks)],
1036
+ control: { ...control, checked: value },
1037
+ };
1038
+ }
1039
+ default:
1040
+ return null;
1041
+ }
1042
+ }
1043
+ /** The ids a block, row or cell of `range` lists, up to the control's own. */
1044
+ function controlChain(tree, range) {
1045
+ const ids = (tree.nodeAt(range.from)?.attrs.controls ?? []);
1046
+ return ids.slice(0, ids.indexOf(range.id) + 1);
1047
+ }
1048
+ /** The caret positions of a control's text are in sibling paragraphs: a value can go there. */
1049
+ function takesText(tree, range) {
1050
+ if (range.level === "inline")
1051
+ return true;
1052
+ if (range.level === "row")
1053
+ return false;
1054
+ const $from = tree.resolve(range.contentFrom);
1055
+ const $to = tree.resolve(range.contentTo);
1056
+ return ($from.parent.isTextblock &&
1057
+ $to.parent.isTextblock &&
1058
+ $from.depth === $to.depth &&
1059
+ $from.node($from.depth - 1) === $to.node($to.depth - 1));
1060
+ }
1061
+ const isBlocks = (value) => typeof value === "object" && value !== null && "content" in value;
1062
+ function blocksFrom(content) {
1063
+ const blocks = [];
1064
+ parseContent({ type: "doc", content }, "content", true).forEach((node) => {
1065
+ blocks.push(node);
1066
+ });
1067
+ return blocks;
1068
+ }
1069
+ /**
1070
+ * Whether rich content from outside can go into `range`: nothing naming what the document does not
1071
+ * hold (a control that is not there or stands elsewhere, a comment, a note), no unsafe link, and in
1072
+ * a cell nothing a cell cannot hold. Its nodes are checked by the schema when they are made.
1073
+ */
1074
+ function safeContent(state, range, content) {
1075
+ const controls = wordContext(state)?.envelope.controls ?? {};
1076
+ const elsewhere = new Set(controlsIn(state.doc)
1077
+ .filter((r) => r === range || r.from < range.from || r.to > range.to)
1078
+ .map((r) => r.id));
1079
+ const usable = (id) => typeof id === "string" && Object.hasOwn(controls, id) && !elsewhere.has(id);
1080
+ // What `controlValues` reads of a block control lists the controls it stands in.
1081
+ const chain = range.level === "inline" ? [] : controlChain(state.doc, range);
1082
+ const $at = state.doc.resolve(range.contentFrom);
1083
+ let inCell = false;
1084
+ for (let d = $at.depth; d > 0; d--)
1085
+ inCell ||= $at.node(d).type.name === "tableCell";
1086
+ const open = new Map();
1087
+ const check = (json) => {
1088
+ if (typeof json !== "object" || json === null || typeof json.type !== "string")
1089
+ return false;
1090
+ const attrs = json.attrs;
1091
+ if (COMMENT_ANCHORS.has(json.type) || json.type === "noteReference" || json.type === "noteMark")
1092
+ return false;
1093
+ if (inCell && (json.type === "pageBreak" || json.type === "columnBreak"))
1094
+ return false;
1095
+ if (attrs?.section)
1096
+ return false;
1097
+ if (json.type === "controlStart" || json.type === "controlEnd") {
1098
+ if (!usable(attrs?.id))
1099
+ return false;
1100
+ const id = attrs?.id;
1101
+ open.set(id, (open.get(id) ?? 0) + (json.type === "controlStart" ? 1 : -1));
1102
+ }
1103
+ const ids = attrs?.controls;
1104
+ if (ids != null && !(Array.isArray(ids) && ids.every((c) => chain.includes(c) || usable(c))))
1105
+ return false;
1106
+ if (json.marks?.some((m) => m.type === "link" && !isSafeLink(m.attrs)))
1107
+ return false;
1108
+ return json.content === undefined || (Array.isArray(json.content) && json.content.every(check));
1109
+ };
1110
+ return content.every(check) && [...open.values()].every((n) => n === 0);
1111
+ }
1112
+ function fontMark(type, font) {
1113
+ return type.create({
1114
+ ascii: font,
1115
+ hAnsi: font,
1116
+ eastAsia: font,
1117
+ ...(font === "MS Gothic" ? { hint: "eastAsia" } : {}),
1118
+ });
1119
+ }
1120
+ /**
1121
+ * Fills the controls with id or tag `target` in this tree: text, a list item (its value or shown
1122
+ * text), a date (`Date` or `yyyy-mm-dd`), checked or not, rich content; null or "" empties one,
1123
+ * bringing its placeholder back. Tracked when tracking is on. What cannot take it (a locked or bound
1124
+ * control, an item not in a drop-down list) stays; false when nothing could. `join`: one undo step
1125
+ * with the change before it.
1126
+ */
1127
+ export function setControlValue(target, value, join = false) {
1128
+ return (state, dispatch) => {
1129
+ const context = wordContext(state);
1130
+ if (!context?.envelope.controls)
1131
+ return false;
1132
+ const found = [];
1133
+ try {
1134
+ for (const range of targets(state, target)) {
1135
+ const control = controlProperties(state, range.id);
1136
+ if (!control || controlIsReadOnly(control))
1137
+ continue;
1138
+ const next = valueFor(state, range, control, value);
1139
+ if (next)
1140
+ found.push({ range, next });
1141
+ }
1142
+ }
1143
+ catch (error) {
1144
+ if (error instanceof FoliDocumentError)
1145
+ return false;
1146
+ throw error;
1147
+ }
1148
+ if (!found.length)
1149
+ return false;
1150
+ const tr = state.tr;
1151
+ tr.setMeta(controlEdit, "value").setMeta(join ? joinHistory : closeHistory, true);
1152
+ const controls = { ...context.envelope.controls };
1153
+ try {
1154
+ for (const { range, next } of [...found].reverse()) {
1155
+ controls[range.id] = next.control;
1156
+ if (next.blocks) {
1157
+ const prefix = controlChain(state.doc, range);
1158
+ const inCell = range.level === "cell";
1159
+ const nodes = next.nodes.map((n) => inCell
1160
+ ? n
1161
+ : n.type.create({
1162
+ ...n.attrs,
1163
+ controls: [
1164
+ ...prefix,
1165
+ ...(n.attrs.controls ?? []).filter((id) => !prefix.includes(id)),
1166
+ ],
1167
+ }, n.content, n.marks));
1168
+ const [from, to] = inCell ? [range.from + 1, range.to - 1] : [range.from, range.to];
1169
+ tr.replace(from, to, new Slice(Fragment.fromArray(nodes), 0, 0));
1170
+ }
1171
+ else {
1172
+ if (range.contentTo > range.contentFrom)
1173
+ tr.delete(range.contentFrom, range.contentTo);
1174
+ if (next.nodes.length)
1175
+ tr.insert(range.contentFrom, next.nodes);
1176
+ }
1177
+ }
1178
+ }
1179
+ catch (error) {
1180
+ if (error instanceof TransformError)
1181
+ return false;
1182
+ throw error;
1183
+ }
1184
+ setEnvelopeValue(state, tr, "controls", controls);
1185
+ // Whether it holds: what the document's rules refuse is not reported as done.
1186
+ const tracked = trackTransaction(state, tr);
1187
+ if (!tracked || !state.applyTransaction(tracked).transactions.length)
1188
+ return false;
1189
+ dispatch?.(tr);
1190
+ return true;
1191
+ };
1192
+ }
1193
+ /** A control's properties for a copy of it: Word gives the copy a `w:id` of its own. */
1194
+ export function copiedControl(control) {
1195
+ return control.ext
1196
+ ? { ...control, ext: control.ext.replace(/<[\w.-]+:id\b[^>]*\/>/, "") }
1197
+ : control;
1198
+ }
1199
+ /** An id no control of `controls` has. */
1200
+ export function freshControlId(controls) {
1201
+ let n = Object.keys(controls ?? {}).length + 1;
1202
+ while (Object.hasOwn(controls ?? {}, `control-${n}`))
1203
+ n++;
1204
+ return `control-${n}`;
1205
+ }
1206
+ function newControl(kind, options) {
1207
+ const built = BUILT_IN[kind];
1208
+ return {
1209
+ kind,
1210
+ ...(options.tag ? { tag: options.tag } : {}),
1211
+ ...(options.title ? { alias: options.title } : {}),
1212
+ ...(options.lock && options.lock !== "unlocked" ? { lock: options.lock } : {}),
1213
+ ...(kind === "dropDown" || kind === "comboBox" ? { items: options.items ?? [] } : {}),
1214
+ ...(kind === "date" ? { dateFormat: options.dateFormat ?? "d MMMM yyyy" } : {}),
1215
+ ...(kind === "text" && options.multiLine ? { multiLine: true } : {}),
1216
+ ...(kind === "checkbox"
1217
+ ? { checked: options.checked === true, checkedState: CHECKED, uncheckedState: UNCHECKED }
1218
+ : {}),
1219
+ ...(built
1220
+ ? {
1221
+ placeholder: {
1222
+ showing: true,
1223
+ docPart: built.docPart,
1224
+ ...(options.placeholder ? { text: options.placeholder } : {}),
1225
+ },
1226
+ }
1227
+ : {}),
1228
+ };
1229
+ }
1230
+ /** The blocks from `$from`'s to `$to`'s, as positions in their common parent. */
1231
+ function blocksOf(state) {
1232
+ const { $from, $to } = state.selection;
1233
+ if (!$from.parent.isTextblock || !$to.parent.isTextblock || $from.depth !== $to.depth)
1234
+ return null;
1235
+ if ($from.node($from.depth - 1) !== $to.node($to.depth - 1))
1236
+ return null;
1237
+ return { from: $from.before(), to: $to.after() };
1238
+ }
1239
+ function addToBlocks(tr, from, to, ids) {
1240
+ tr.doc.nodesBetween(from, to, (node, pos) => {
1241
+ if (pos < from)
1242
+ return true;
1243
+ const controls = [...(node.attrs.controls ?? []), ...ids];
1244
+ tr.setNodeMarkup(pos, node.type, { ...node.attrs, controls });
1245
+ return false;
1246
+ });
1247
+ }
1248
+ /**
1249
+ * Inserts a control of `kind` at the selection, as Word: at a caret an inline one showing its
1250
+ * placeholder; rich or plain text around selected text of one paragraph; rich text around whole
1251
+ * paragraphs selected; a repeating section (with its first item) around the caret's paragraphs; a
1252
+ * picture control around a selected picture.
1253
+ */
1254
+ export function insertControl(kind, options = {}) {
1255
+ return (state, dispatch) => {
1256
+ const context = wordContext(state);
1257
+ if (!context || kind === "other" || kind === "repeatingItem")
1258
+ return false;
1259
+ const { selection, schema } = state;
1260
+ const { controlStart, controlEnd } = schema.nodes;
1261
+ if (!controlStart || !controlEnd)
1262
+ return false;
1263
+ const { envelope } = context;
1264
+ const id = freshControlId(envelope.controls);
1265
+ const control = newControl(kind, options);
1266
+ const add = (extra) => ({
1267
+ ...(envelope.controls ?? {}),
1268
+ ...extra,
1269
+ });
1270
+ return attempt(state, dispatch, (tr) => {
1271
+ tr.setMeta(closeHistory, true);
1272
+ const start = controlStart.create({ id });
1273
+ const end = controlEnd.create({ id });
1274
+ const { from, to, $from, $to } = selection;
1275
+ const blocks = blocksOf(state);
1276
+ if (kind === "repeating") {
1277
+ if (!blocks)
1278
+ throw new TransformError("A repeating section goes around paragraphs");
1279
+ const item = `${id}-item`;
1280
+ addToBlocks(tr, blocks.from, blocks.to, [id, item]);
1281
+ setEnvelopeValue(state, tr, "controls", add({ [id]: control, [item]: { kind: "repeatingItem" } }));
1282
+ return;
1283
+ }
1284
+ const filled = () => ({
1285
+ ...control,
1286
+ ...(control.placeholder ? { placeholder: { ...control.placeholder, showing: false } } : {}),
1287
+ });
1288
+ if (kind === "richText" && blocks && $from.parent !== $to.parent) {
1289
+ addToBlocks(tr, blocks.from, blocks.to, [id]);
1290
+ setEnvelopeValue(state, tr, "controls", add({ [id]: filled() }));
1291
+ return;
1292
+ }
1293
+ if (kind === "picture") {
1294
+ const node = state.doc.nodeAt(from);
1295
+ if (node?.type.name !== "picture" || to !== from + node.nodeSize)
1296
+ throw new TransformError("A picture control goes around a picture");
1297
+ tr.insert(to, end).insert(from, start);
1298
+ setEnvelopeValue(state, tr, "controls", add({ [id]: control }));
1299
+ return;
1300
+ }
1301
+ const wraps = !selection.empty && $from.parent === $to.parent && $from.parent.isTextblock;
1302
+ if (wraps && (kind === "richText" || kind === "text")) {
1303
+ tr.insert(to, end).insert(from, start);
1304
+ setEnvelopeValue(state, tr, "controls", add({ [id]: filled() }));
1305
+ tr.setSelection(TextSelection.create(tr.doc, from + 1, to + 1));
1306
+ return;
1307
+ }
1308
+ if (!selection.empty)
1309
+ tr.deleteSelection();
1310
+ const at = tr.selection.from;
1311
+ if (!tr.doc.resolve(at).parent.isTextblock)
1312
+ throw new TransformError("No paragraph here");
1313
+ let inside;
1314
+ let nextEnvelope = envelope;
1315
+ if (kind === "checkbox") {
1316
+ const state2 = control.checked ? CHECKED : UNCHECKED;
1317
+ inside = schema.text(glyph(state2), [fontMark(schema.marks.font, state2.font)]);
1318
+ }
1319
+ else {
1320
+ const made = placeholderRun(state, control, envelope);
1321
+ inside = made.run;
1322
+ nextEnvelope = made.envelope;
1323
+ }
1324
+ tr.insert(at, [start, inside, end]);
1325
+ if (nextEnvelope !== envelope)
1326
+ withEnvelope(tr, nextEnvelope);
1327
+ setEnvelopeValue(state, tr, "controls", add({ [id]: control }));
1328
+ tr.setSelection(TextSelection.create(tr.doc, at + 1, at + 1 + inside.nodeSize));
1329
+ });
1330
+ };
1331
+ }
1332
+ /** Changes the properties of the control with id or tag `target` (the first such). */
1333
+ export function setControlProperties(target, patch) {
1334
+ return (state, dispatch) => {
1335
+ const context = wordContext(state);
1336
+ const range = targets(state, target)[0];
1337
+ const control = range && controlProperties(state, range.id);
1338
+ if (!context || !range || !control)
1339
+ return false;
1340
+ const { alias: _alias, tag: _tag, lock: _lock, ...rest } = control;
1341
+ const title = patch.title ?? control.alias;
1342
+ const tag = patch.tag ?? control.tag;
1343
+ const lock = patch.lock ?? control.lock;
1344
+ const next = {
1345
+ ...rest,
1346
+ ...(tag ? { tag } : {}),
1347
+ ...(title ? { alias: title } : {}),
1348
+ ...(lock && lock !== "unlocked" ? { lock } : {}),
1349
+ ...(patch.items && (control.kind === "dropDown" || control.kind === "comboBox")
1350
+ ? { items: patch.items }
1351
+ : {}),
1352
+ ...(patch.dateFormat && control.kind === "date" ? { dateFormat: patch.dateFormat } : {}),
1353
+ ...(patch.multiLine !== undefined && control.kind === "text"
1354
+ ? { multiLine: patch.multiLine }
1355
+ : {}),
1356
+ };
1357
+ return attempt(state, dispatch, (tr) => {
1358
+ tr.setMeta(closeHistory, true).setMeta(controlEdit, "value");
1359
+ setEnvelopeValue(state, tr, "controls", {
1360
+ ...context.envelope.controls,
1361
+ [range.id]: next,
1362
+ });
1363
+ // A date picked shows in its new format, where the content may change.
1364
+ if (next.date &&
1365
+ next.dateFormat !== control.dateFormat &&
1366
+ !controlIsReadOnly(next) &&
1367
+ !next.placeholder?.showing) {
1368
+ const marks = valueMarks(state, range, control);
1369
+ tr.delete(range.contentFrom, range.contentTo);
1370
+ tr.insert(range.contentFrom, textNodes(state, formatDate(next, next.date), marks));
1371
+ }
1372
+ });
1373
+ };
1374
+ }
1375
+ const ONCE = new Set([...COMMENT_ANCHORS, "bookmarkStart", "bookmarkEnd"]);
1376
+ /**
1377
+ * A repeating section gets another item after the caret's (or its last), a copy of it as in Word,
1378
+ * the controls in it copied too under new ids. Not where the section forbids it
1379
+ * (`w15:doNotAllowInsertDeleteSection`).
1380
+ */
1381
+ export function addRepeatingItem(target) {
1382
+ return (state, dispatch) => {
1383
+ const context = wordContext(state);
1384
+ const controls = context?.envelope.controls;
1385
+ if (!controls)
1386
+ return false;
1387
+ const ranges = controlsIn(state.doc);
1388
+ const { from } = state.selection;
1389
+ const kindOf = (r) => controls[r.id]?.kind;
1390
+ const section = target
1391
+ ? targets(state, target).find((r) => kindOf(r) === "repeating")
1392
+ : ranges.filter((r) => kindOf(r) === "repeating" && r.from < from && from < r.to).at(-1);
1393
+ if (!section || controls[section.id]?.noInsertDelete)
1394
+ return false;
1395
+ const items = ranges.filter((r) => kindOf(r) === "repeatingItem" && r.from >= section.from && r.to <= section.to);
1396
+ const item = items.filter((r) => r.from < from && from < r.to).at(-1) ?? items.at(-1);
1397
+ if (!item)
1398
+ return false;
1399
+ const copies = new Map();
1400
+ const added = {};
1401
+ const fresh = (id) => {
1402
+ // The section itself and what is around it stay.
1403
+ if (ranges.some((r) => r.id === id && r.from <= item.from && r.to >= item.to && r !== item))
1404
+ return id;
1405
+ let copy = copies.get(id);
1406
+ if (!copy) {
1407
+ copy = freshControlId({ ...controls, ...added });
1408
+ copies.set(id, copy);
1409
+ added[copy] = copiedControl(controls[id]);
1410
+ }
1411
+ return copy;
1412
+ };
1413
+ const renamed = (json) => {
1414
+ const attrs = json.attrs;
1415
+ const marker = json.type === "controlStart" || json.type === "controlEnd";
1416
+ const ids = attrs?.controls;
1417
+ return {
1418
+ ...json,
1419
+ ...(marker ? { attrs: { ...attrs, id: fresh(String(attrs?.id)) } } : {}),
1420
+ ...(ids ? { attrs: { ...attrs, controls: ids.map(fresh) } } : {}),
1421
+ // A bookmark's name and a comment's anchors are the document's once.
1422
+ ...(json.content
1423
+ ? { content: json.content.filter((n) => !ONCE.has(n.type)).map(renamed) }
1424
+ : {}),
1425
+ };
1426
+ };
1427
+ const nodes = [];
1428
+ state.doc.slice(item.from, item.to).content.forEach((node) => {
1429
+ nodes.push(state.schema.nodeFromJSON(renamed(node.toJSON())));
1430
+ });
1431
+ return attempt(state, dispatch, (tr) => {
1432
+ tr.setMeta(closeHistory, true);
1433
+ tr.insert(item.to, Fragment.fromArray(nodes));
1434
+ setEnvelopeValue(state, tr, "controls", { ...controls, ...added });
1435
+ tr.setSelection(Selection.near(tr.doc.resolve(item.to), 1));
1436
+ });
1437
+ };
1438
+ }
1439
+ /**
1440
+ * Pasted or dropped text into a text control: one run, its line breaks kept only where the control
1441
+ * takes them. False when the selection is not in one.
1442
+ */
1443
+ export function insertControlText(text) {
1444
+ return (state, dispatch) => {
1445
+ const range = controlAt(state.doc, state.selection.from);
1446
+ const control = range && controlProperties(state, range.id);
1447
+ if (!range || !control || !TEXT_KINDS.has(control.kind))
1448
+ return false;
1449
+ const line = /\r\n?|\n/;
1450
+ if (!control.multiLine)
1451
+ return insertText(text.split(line).join(" "))(state, dispatch);
1452
+ return attempt(state, dispatch, (tr) => {
1453
+ const marks = state.storedMarks ?? marksAt(state.selection.$from);
1454
+ const nodes = textNodes(state, text.split(line).join("\n"), marks);
1455
+ tr.replaceSelection(new Slice(Fragment.fromArray(nodes), 0, 0));
1456
+ });
1457
+ };
1458
+ }
1459
+ //# sourceMappingURL=controls.js.map