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