docxkeun 0.0.0-stage → 0.1.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 (138) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +252 -2
  4. package/dist/api/editor.d.ts +253 -0
  5. package/dist/api/editor.js +1121 -0
  6. package/dist/api/index.d.ts +3 -0
  7. package/dist/api/index.js +3 -0
  8. package/dist/api/parts.d.ts +21 -0
  9. package/dist/api/parts.js +66 -0
  10. package/dist/api/positions.d.ts +57 -0
  11. package/dist/api/positions.js +229 -0
  12. package/dist/comments/read.d.ts +26 -0
  13. package/dist/comments/read.js +66 -0
  14. package/dist/crypto/aes.d.ts +18 -0
  15. package/dist/crypto/aes.js +229 -0
  16. package/dist/crypto/index.d.ts +4 -0
  17. package/dist/crypto/index.js +8 -0
  18. package/dist/crypto/sha.d.ts +14 -0
  19. package/dist/crypto/sha.js +297 -0
  20. package/dist/fonts/bundled.d.ts +26 -0
  21. package/dist/fonts/bundled.js +41 -0
  22. package/dist/fonts/embedded.d.ts +5 -0
  23. package/dist/fonts/embedded.js +42 -0
  24. package/dist/fonts/index.d.ts +6 -0
  25. package/dist/fonts/index.js +6 -0
  26. package/dist/fonts/odttf.d.ts +7 -0
  27. package/dist/fonts/odttf.js +22 -0
  28. package/dist/fonts/registry.d.ts +57 -0
  29. package/dist/fonts/registry.js +126 -0
  30. package/dist/fonts/sfnt.d.ts +91 -0
  31. package/dist/fonts/sfnt.js +416 -0
  32. package/dist/fonts/subset.d.ts +12 -0
  33. package/dist/fonts/subset.js +143 -0
  34. package/dist/index.d.ts +15 -0
  35. package/dist/index.js +18 -0
  36. package/dist/layout/blocks.d.ts +56 -0
  37. package/dist/layout/blocks.js +422 -0
  38. package/dist/layout/engine.d.ts +13 -0
  39. package/dist/layout/engine.js +471 -0
  40. package/dist/layout/fonts.d.ts +11 -0
  41. package/dist/layout/fonts.js +73 -0
  42. package/dist/layout/index.d.ts +5 -0
  43. package/dist/layout/index.js +4 -0
  44. package/dist/layout/lines.d.ts +194 -0
  45. package/dist/layout/lines.js +511 -0
  46. package/dist/layout/paint.d.ts +38 -0
  47. package/dist/layout/paint.js +217 -0
  48. package/dist/layout/style.d.ts +42 -0
  49. package/dist/layout/style.js +95 -0
  50. package/dist/layout/types.d.ts +172 -0
  51. package/dist/layout/types.js +1 -0
  52. package/dist/model/content.d.ts +218 -0
  53. package/dist/model/content.js +696 -0
  54. package/dist/model/document.d.ts +110 -0
  55. package/dist/model/document.js +275 -0
  56. package/dist/model/fields.d.ts +17 -0
  57. package/dist/model/fields.js +77 -0
  58. package/dist/model/index.d.ts +8 -0
  59. package/dist/model/index.js +8 -0
  60. package/dist/model/numbering.d.ts +53 -0
  61. package/dist/model/numbering.js +245 -0
  62. package/dist/model/props.d.ts +230 -0
  63. package/dist/model/props.js +505 -0
  64. package/dist/model/styles.d.ts +72 -0
  65. package/dist/model/styles.js +178 -0
  66. package/dist/model/theme.d.ts +21 -0
  67. package/dist/model/theme.js +102 -0
  68. package/dist/model/units.d.ts +27 -0
  69. package/dist/model/units.js +81 -0
  70. package/dist/opc/constants.d.ts +53 -0
  71. package/dist/opc/constants.js +70 -0
  72. package/dist/opc/index.d.ts +3 -0
  73. package/dist/opc/index.js +3 -0
  74. package/dist/opc/package.d.ts +66 -0
  75. package/dist/opc/package.js +282 -0
  76. package/dist/opc/paths.d.ts +12 -0
  77. package/dist/opc/paths.js +61 -0
  78. package/dist/pdf/export.d.ts +25 -0
  79. package/dist/pdf/export.js +326 -0
  80. package/dist/pdf/fonts.d.ts +19 -0
  81. package/dist/pdf/fonts.js +122 -0
  82. package/dist/pdf/images.d.ts +13 -0
  83. package/dist/pdf/images.js +264 -0
  84. package/dist/pdf/index.d.ts +4 -0
  85. package/dist/pdf/index.js +4 -0
  86. package/dist/pdf/objects.d.ts +38 -0
  87. package/dist/pdf/objects.js +148 -0
  88. package/dist/pdf/writer.d.ts +19 -0
  89. package/dist/pdf/writer.js +58 -0
  90. package/dist/react/index.d.ts +28 -0
  91. package/dist/react/index.js +39 -0
  92. package/dist/render/canvas-fonts.d.ts +8 -0
  93. package/dist/render/canvas-fonts.js +87 -0
  94. package/dist/render/editing.d.ts +109 -0
  95. package/dist/render/editing.js +830 -0
  96. package/dist/render/index.d.ts +5 -0
  97. package/dist/render/index.js +5 -0
  98. package/dist/render/navigation.d.ts +41 -0
  99. package/dist/render/navigation.js +105 -0
  100. package/dist/render/selection.d.ts +15 -0
  101. package/dist/render/selection.js +50 -0
  102. package/dist/render/svg.d.ts +14 -0
  103. package/dist/render/svg.js +68 -0
  104. package/dist/render/viewer.d.ts +170 -0
  105. package/dist/render/viewer.js +617 -0
  106. package/dist/security/cfb.d.ts +11 -0
  107. package/dist/security/cfb.js +286 -0
  108. package/dist/security/encryption.d.ts +24 -0
  109. package/dist/security/encryption.js +283 -0
  110. package/dist/security/index.d.ts +11 -0
  111. package/dist/security/index.js +21 -0
  112. package/dist/security/pdf.d.ts +29 -0
  113. package/dist/security/pdf.js +114 -0
  114. package/dist/security/policy.d.ts +62 -0
  115. package/dist/security/policy.js +141 -0
  116. package/dist/security/protection.d.ts +49 -0
  117. package/dist/security/protection.js +255 -0
  118. package/dist/util/bytes.d.ts +53 -0
  119. package/dist/util/bytes.js +232 -0
  120. package/dist/util/crc32.d.ts +2 -0
  121. package/dist/util/crc32.js +17 -0
  122. package/dist/util/text.d.ts +10 -0
  123. package/dist/util/text.js +88 -0
  124. package/dist/xml/dom.d.ts +60 -0
  125. package/dist/xml/dom.js +131 -0
  126. package/dist/xml/index.d.ts +4 -0
  127. package/dist/xml/index.js +4 -0
  128. package/dist/xml/ns.d.ts +41 -0
  129. package/dist/xml/ns.js +137 -0
  130. package/dist/xml/parser.d.ts +16 -0
  131. package/dist/xml/parser.js +203 -0
  132. package/dist/xml/serialize.d.ts +6 -0
  133. package/dist/xml/serialize.js +71 -0
  134. package/dist/zip/deflate.d.ts +7 -0
  135. package/dist/zip/deflate.js +42 -0
  136. package/dist/zip/zip.d.ts +33 -0
  137. package/dist/zip/zip.js +216 -0
  138. package/package.json +96 -4
@@ -0,0 +1,1121 @@
1
+ /**
2
+ * DocxEditor: the code API for changing a document. Every change edits the XML directly (so
3
+ * everything docxkeun does not understand is preserved), passes through the access guard, and
4
+ * notifies listeners such as the viewer.
5
+ */
6
+ import { REL } from '../opc/index.js';
7
+ import { attr, el, elements, ensureChild, findAll, firstChild, insertOrdered, removeChildren, textContent } from '../xml/index.js';
8
+ import { ensureNamespaces, ensurePart, randomHexId } from './parts.js';
9
+ import { between, EditError, indexOfChild, isolate, PPR_ORDER, replaceMark, RPR_ORDER, textNode, TreeIndex, } from './positions.js';
10
+ const LOCK_VALUES = { content: 'contentLocked', contentAndControl: 'sdtContentLocked', control: 'sdtLocked' };
11
+ const LOCK_MODES = { contentLocked: 'content', sdtContentLocked: 'contentAndControl', sdtLocked: 'control' };
12
+ /** Tag docxkeun puts on the content controls it creates to lock text. */
13
+ export const LOCK_TAG = 'docxkeun-lock';
14
+ /** An edit touched text inside a locked region. */
15
+ export class LockedRegionError extends EditError {
16
+ region;
17
+ name = 'LockedRegionError';
18
+ constructor(region, title) {
19
+ super(title ? `"${title}" is locked against editing` : 'This text is locked against editing');
20
+ this.region = region;
21
+ }
22
+ }
23
+ /** The lock mode of a content control, if it is locked. */
24
+ export function lockModeOf(sdt) {
25
+ const v = attr(firstChild(firstChild(sdt, 'w:sdtPr'), 'w:lock'), 'w:val');
26
+ return v ? LOCK_MODES[v] : undefined;
27
+ }
28
+ function sdtTitle(sdt) {
29
+ return attr(firstChild(firstChild(sdt, 'w:sdtPr'), 'w:alias'), 'w:val');
30
+ }
31
+ function locksContent(mode) {
32
+ return mode === 'content' || mode === 'contentAndControl';
33
+ }
34
+ /** Every paragraph of a block list (including table cells), in document order. */
35
+ export function paragraphsOf(blocks, out = []) {
36
+ for (const b of blocks) {
37
+ if (b.kind === 'paragraph')
38
+ out.push(b);
39
+ else
40
+ for (const row of b.rows)
41
+ for (const cell of row.cells)
42
+ paragraphsOf(cell.blocks, out);
43
+ }
44
+ return out;
45
+ }
46
+ export function paragraphText(para) {
47
+ let text = '';
48
+ const segments = [];
49
+ const add = (value, node) => {
50
+ segments.push({ start: text.length, end: text.length + value.length, node });
51
+ text += value;
52
+ };
53
+ for (const inline of para.inlines) {
54
+ if (inline.kind === 'text')
55
+ add(inline.text, inline.node);
56
+ else if (inline.kind === 'tab')
57
+ add('\t', inline.node);
58
+ else if (inline.kind === 'break' && inline.type === 'line')
59
+ add('\n', inline.node);
60
+ }
61
+ return { paragraph: para.el, text, segments };
62
+ }
63
+ /**
64
+ * XML position of character offset `k` in a paragraph. With side 'start' the position is at the
65
+ * start of the segment holding character k; with 'end' it is at the end of the segment holding
66
+ * character k-1 (so insertions there inherit the formatting of the text before).
67
+ */
68
+ export function positionAt(pt, k, side) {
69
+ for (const s of pt.segments) {
70
+ const inside = side === 'start' ? k >= s.start && k < s.end : k > s.start && k <= s.end;
71
+ if (inside) {
72
+ if (s.node.name === 'w:t')
73
+ return { node: s.node, offset: k - s.start };
74
+ return { node: s.node, offset: side === 'start' ? 0 : 1 };
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+ /** Run children for a string: text, tabs and line breaks. */
80
+ export function runContent(text) {
81
+ const out = [];
82
+ for (const part of text.split(/(\t|\r?\n)/)) {
83
+ if (part === '')
84
+ continue;
85
+ if (part === '\t')
86
+ out.push(el('w:tab'));
87
+ else if (part === '\n' || part === '\r\n')
88
+ out.push(el('w:br'));
89
+ else
90
+ out.push(textNode(part));
91
+ }
92
+ return out;
93
+ }
94
+ /** Apply TextFormat to a w:rPr element (created when missing). */
95
+ export function applyFormat(run, format) {
96
+ const rPr = firstChild(run, 'w:rPr') ?? (() => {
97
+ const created = el('w:rPr');
98
+ run.children.unshift(created);
99
+ return created;
100
+ })();
101
+ const toggle = (name, value) => {
102
+ if (value === undefined)
103
+ return;
104
+ removeChildren(rPr, name);
105
+ insertOrdered(rPr, el(name, value ? {} : { 'w:val': '0' }), RPR_ORDER);
106
+ };
107
+ const set = (name, attrs) => {
108
+ removeChildren(rPr, name);
109
+ if (attrs)
110
+ insertOrdered(rPr, el(name, attrs), RPR_ORDER);
111
+ };
112
+ toggle('w:b', format.bold);
113
+ toggle('w:bCs', format.bold);
114
+ toggle('w:i', format.italic);
115
+ toggle('w:iCs', format.italic);
116
+ toggle('w:strike', format.strike);
117
+ toggle('w:caps', format.caps);
118
+ toggle('w:smallCaps', format.smallCaps);
119
+ toggle('w:vanish', format.hidden);
120
+ if (format.underline !== undefined)
121
+ set('w:u', { 'w:val': format.underline === true ? 'single' : format.underline === false ? 'none' : format.underline });
122
+ if (format.color !== undefined)
123
+ set('w:color', { 'w:val': format.color.replace(/^#/, '').toUpperCase() });
124
+ if (format.highlight !== undefined)
125
+ set('w:highlight', format.highlight === 'none' ? undefined : { 'w:val': format.highlight });
126
+ if (format.size !== undefined) {
127
+ set('w:sz', { 'w:val': String(Math.round(format.size * 2)) });
128
+ set('w:szCs', { 'w:val': String(Math.round(format.size * 2)) });
129
+ }
130
+ if (format.font !== undefined)
131
+ set('w:rFonts', { 'w:ascii': format.font, 'w:hAnsi': format.font, 'w:cs': format.font, 'w:eastAsia': format.font });
132
+ if (format.style !== undefined)
133
+ set('w:rStyle', { 'w:val': format.style });
134
+ if (format.vertAlign !== undefined)
135
+ set('w:vertAlign', { 'w:val': format.vertAlign });
136
+ if (rPr.children.length === 0)
137
+ run.children.splice(run.children.indexOf(rPr), 1);
138
+ }
139
+ /** Position just after a run's content (its last text node, or after its last item). */
140
+ function endOfRun(run, fallback) {
141
+ const items = run.children.filter((c) => c.type === 'element' && c.name !== 'w:rPr');
142
+ const last = items[items.length - 1];
143
+ if (!last)
144
+ return { node: fallback, offset: 0 };
145
+ return last.name === 'w:t' ? { node: last, offset: textContent(last).length } : { node: last, offset: 1 };
146
+ }
147
+ function newRun(text, template, format) {
148
+ const rPr = template ? firstChild(template, 'w:rPr') : undefined;
149
+ const run = el('w:r', {}, [...(rPr ? [structuredClone(rPr)] : []), ...runContent(text)]);
150
+ if (format)
151
+ applyFormat(run, format);
152
+ return run;
153
+ }
154
+ const BOOKMARK_NAME = /^[\p{L}_][\p{L}\p{N}_]{0,39}$/u;
155
+ export class DocxEditor {
156
+ doc;
157
+ guard;
158
+ constructor(doc, guard) {
159
+ this.doc = doc;
160
+ this.guard = guard;
161
+ }
162
+ get root() {
163
+ return this.doc.documentXml.root;
164
+ }
165
+ get body() {
166
+ const body = firstChild(this.root, 'w:body');
167
+ if (!body)
168
+ throw new EditError('document has no body');
169
+ return body;
170
+ }
171
+ index() {
172
+ return new TreeIndex(this.root);
173
+ }
174
+ changed(part = this.doc.mainPart) {
175
+ this.doc.touch(part);
176
+ }
177
+ check(action, range, detail) {
178
+ this.guard?.assert(action, range, detail);
179
+ if (range && (action === 'edit' || action === 'format' || action === 'link'))
180
+ this.assertUnlocked(range);
181
+ }
182
+ /** The locked content control around a node, if any. */
183
+ lockAround(idx, node) {
184
+ for (let cur = idx.parent.get(node); cur; cur = idx.parent.get(cur)) {
185
+ if (cur.name === 'w:sdt' && locksContent(lockModeOf(cur)))
186
+ return cur;
187
+ }
188
+ return undefined;
189
+ }
190
+ /** Throw LockedRegionError when a range touches a locked region (or would delete one). */
191
+ assertUnlocked(range) {
192
+ if (this.bypassLocks)
193
+ return;
194
+ const idx = this.index();
195
+ for (const pos of [range.start, range.end]) {
196
+ if (!idx.contains(pos.node))
197
+ continue;
198
+ const lock = this.lockAround(idx, pos.node);
199
+ if (lock)
200
+ throw new LockedRegionError(lock, sdtTitle(lock));
201
+ }
202
+ const a = idx.order.get(range.start.node);
203
+ const b = idx.order.get(range.end.node);
204
+ if (a === undefined || b === undefined || (a === b && range.start.offset === range.end.offset))
205
+ return;
206
+ const [lo, hi] = a <= b ? [a, b] : [b, a];
207
+ for (const sdt of findAll(this.root, 'w:sdt')) {
208
+ const o = idx.order.get(sdt);
209
+ if (o > lo && o < hi && lockModeOf(sdt))
210
+ throw new LockedRegionError(sdt, sdtTitle(sdt));
211
+ }
212
+ }
213
+ /** Whether a range touches a locked region. */
214
+ isLocked(range) {
215
+ try {
216
+ this.assertUnlocked(range);
217
+ return false;
218
+ }
219
+ catch (e) {
220
+ if (e instanceof LockedRegionError)
221
+ return true;
222
+ throw e;
223
+ }
224
+ }
225
+ /** Set while filling locked content on purpose (fillTemplate with includeLocked). */
226
+ bypassLocks = false;
227
+ // ---- reading ------------------------------------------------------------------------------
228
+ /** Convert a viewer selection (inline positions) into an editor range. */
229
+ rangeFromSelection(sel) {
230
+ return { start: { node: sel.start.inline.node, offset: sel.start.offset }, end: { node: sel.end.inline.node, offset: sel.end.offset } };
231
+ }
232
+ /** Every paragraph of the body, including those in tables, in document order. */
233
+ paragraphs() {
234
+ return paragraphsOf(this.doc.body().blocks);
235
+ }
236
+ /** Range covering a paragraph's text (undefined for paragraphs without text). */
237
+ paragraphRange(paragraph) {
238
+ const para = 'kind' in paragraph ? paragraph : this.paragraphs().find((p) => p.el === paragraph);
239
+ if (!para)
240
+ return undefined;
241
+ const pt = paragraphText(para);
242
+ const start = positionAt(pt, 0, 'start');
243
+ const end = positionAt(pt, pt.text.length, 'end');
244
+ return start && end ? { start, end } : undefined;
245
+ }
246
+ /** Find text (or a regular expression) within paragraphs, across run boundaries. */
247
+ find(query) {
248
+ const out = [];
249
+ const regex = typeof query === 'string' ? new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g') : new RegExp(query.source, query.flags.includes('g') ? query.flags : query.flags + 'g');
250
+ for (const para of this.paragraphs()) {
251
+ const pt = paragraphText(para);
252
+ if (!pt.text)
253
+ continue;
254
+ regex.lastIndex = 0;
255
+ for (let m = regex.exec(pt.text); m; m = regex.exec(pt.text)) {
256
+ if (m[0].length === 0) {
257
+ regex.lastIndex++;
258
+ continue;
259
+ }
260
+ const start = positionAt(pt, m.index, 'start');
261
+ const end = positionAt(pt, m.index + m[0].length, 'end');
262
+ if (start && end)
263
+ out.push({ start, end, text: m[0], groups: m.slice(1).map((g) => g ?? ''), paragraph: para.el });
264
+ }
265
+ }
266
+ return out;
267
+ }
268
+ /** Text covered by a range. */
269
+ textOf(range) {
270
+ for (const para of this.paragraphs()) {
271
+ const pt = paragraphText(para);
272
+ const s = pt.segments.find((seg) => seg.node === range.start.node);
273
+ const e = pt.segments.find((seg) => seg.node === range.end.node);
274
+ if (s && e) {
275
+ const a = s.start + (s.node.name === 'w:t' ? range.start.offset : range.start.offset ? s.end - s.start : 0);
276
+ const b = e.start + (e.node.name === 'w:t' ? range.end.offset : range.end.offset ? e.end - e.start : 0);
277
+ return pt.text.slice(a, b);
278
+ }
279
+ }
280
+ return '';
281
+ }
282
+ // ---- text edits ---------------------------------------------------------------------------
283
+ /**
284
+ * Insert text at a position, formatted like the run it lands in (plus optional format).
285
+ * Returns the position right after the inserted text. A position whose node is a w:p means
286
+ * "inside this (empty) paragraph".
287
+ */
288
+ insertText(at, text, format) {
289
+ const edge = this.bypassLocks ? undefined : this.lockEdge(at);
290
+ if (edge) {
291
+ // Typing at the very edge of a locked region goes just outside it, as in Word.
292
+ this.guard?.assert('edit', { start: at, end: at });
293
+ const idx = this.index();
294
+ const run = newRun(text, idx.parentOf(at.node), format);
295
+ const parent = idx.parentOf(edge.sdt);
296
+ parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, run);
297
+ this.changed();
298
+ return endOfRun(run, run);
299
+ }
300
+ this.check('edit', { start: at, end: at });
301
+ const plain = !format && !/[\t\r\n]/.test(text);
302
+ // Typing into existing text: change the text node itself instead of adding a run per keystroke.
303
+ if (plain && at.node.name === 'w:t') {
304
+ const current = textContent(at.node);
305
+ const offset = Math.max(0, Math.min(at.offset, current.length));
306
+ const value = current.slice(0, offset) + text + current.slice(offset);
307
+ at.node.children = [{ type: 'text', value }];
308
+ if (/^\s|\s$/.test(value))
309
+ at.node.attrs['xml:space'] = 'preserve';
310
+ this.changed();
311
+ return { node: at.node, offset: offset + text.length };
312
+ }
313
+ if (at.node.name === 'w:p') {
314
+ // An empty paragraph: the new run takes the paragraph mark's formatting.
315
+ const markRPr = firstChild(firstChild(at.node, 'w:pPr'), 'w:rPr');
316
+ const run = el('w:r', {}, [...(markRPr ? [structuredClone(markRPr)] : []), ...runContent(text)]);
317
+ if (format)
318
+ applyFormat(run, format);
319
+ const pPr = firstChild(at.node, 'w:pPr');
320
+ at.node.children.splice(pPr ? at.node.children.indexOf(pPr) + 1 : 0, 0, run);
321
+ this.changed();
322
+ return endOfRun(run, at.node);
323
+ }
324
+ const index = this.index();
325
+ const template = index.parentOf(at.node);
326
+ const { startMark, endMark } = isolate(index, { start: at, end: at });
327
+ const idx = this.index();
328
+ const run = newRun(text, template, format);
329
+ replaceMark(idx, startMark, [run]);
330
+ replaceMark(idx, endMark, []);
331
+ this.changed();
332
+ return endOfRun(run, run);
333
+ }
334
+ /** Join a paragraph with the one right after it (Backspace at the start of the second). */
335
+ mergeParagraphs(first, second) {
336
+ const firstRange = this.paragraphRange(first);
337
+ const secondRange = this.paragraphRange(second);
338
+ this.check('edit', { start: firstRange?.end ?? { node: first, offset: 0 }, end: secondRange?.start ?? { node: second, offset: 0 } });
339
+ const idx = this.index();
340
+ const parent = idx.parentOf(first);
341
+ if (idx.parentOf(second) !== parent)
342
+ throw new EditError('Cannot join paragraphs in different table cells');
343
+ const a = indexOfChild(parent, first);
344
+ const b = indexOfChild(parent, second);
345
+ if (parent.children.slice(a + 1, b).some((n) => n.type === 'element' && (n.name === 'w:p' || n.name === 'w:tbl' || n.name === 'w:sdt'))) {
346
+ throw new EditError('The paragraphs are not next to each other');
347
+ }
348
+ const secondPPr = firstChild(second, 'w:pPr');
349
+ const sectPr = firstChild(secondPPr, 'w:sectPr');
350
+ if (sectPr) {
351
+ // Keep the section break that ended at the second paragraph.
352
+ const pPr = ensureChild(first, 'w:pPr');
353
+ if (first.children[0] !== pPr) {
354
+ first.children.splice(first.children.indexOf(pPr), 1);
355
+ first.children.unshift(pPr);
356
+ }
357
+ removeChildren(pPr, 'w:sectPr');
358
+ insertOrdered(pPr, sectPr, PPR_ORDER);
359
+ }
360
+ first.children.push(...second.children.filter((n) => !(n.type === 'element' && n.name === 'w:pPr')));
361
+ parent.children.splice(indexOfChild(parent, second), 1);
362
+ this.changed();
363
+ }
364
+ /** Split a paragraph at a position (Enter). Returns the new, second paragraph. */
365
+ splitParagraph(at) {
366
+ const blockEdge = this.bypassLocks ? undefined : this.blockLockEdge(at);
367
+ if (blockEdge) {
368
+ // Enter at the start or end of a locked block adds a paragraph outside it.
369
+ this.guard?.assert('edit', { start: at, end: at });
370
+ const idx = this.index();
371
+ const pPr = firstChild(blockEdge.paragraph, 'w:pPr');
372
+ const newPPr = pPr ? structuredClone(pPr) : undefined;
373
+ if (newPPr)
374
+ removeChildren(newPPr, 'w:sectPr');
375
+ const para = el('w:p', {}, newPPr ? [newPPr] : []);
376
+ const parent = idx.parentOf(blockEdge.sdt);
377
+ parent.children.splice(indexOfChild(parent, blockEdge.sdt) + (blockEdge.after ? 1 : 0), 0, para);
378
+ this.changed();
379
+ return para;
380
+ }
381
+ this.check('edit', { start: at, end: at });
382
+ let para;
383
+ let mark;
384
+ let idx;
385
+ if (at.node.name === 'w:p') {
386
+ para = at.node;
387
+ mark = el('docxkeun:split');
388
+ const pPr = firstChild(para, 'w:pPr');
389
+ para.children.splice(pPr ? para.children.indexOf(pPr) + 1 : 0, 0, mark);
390
+ idx = this.index();
391
+ }
392
+ else {
393
+ const index = this.index();
394
+ const marks = isolate(index, { start: at, end: at });
395
+ idx = this.index();
396
+ replaceMark(idx, marks.endMark, []);
397
+ mark = marks.startMark;
398
+ idx = this.index();
399
+ para = idx.ancestor(mark, 'w:p');
400
+ // A split inside a hyperlink or content control happens after it.
401
+ for (let container = idx.parentOf(mark); container !== para; container = idx.parentOf(mark)) {
402
+ container.children.splice(indexOfChild(container, mark), 1);
403
+ const outer = idx.parentOf(container);
404
+ outer.children.splice(indexOfChild(outer, container) + 1, 0, mark);
405
+ idx = this.index();
406
+ }
407
+ }
408
+ const tail = para.children.splice(indexOfChild(para, mark));
409
+ tail.shift();
410
+ const pPr = firstChild(para, 'w:pPr');
411
+ const newPPr = pPr ? structuredClone(pPr) : undefined;
412
+ // The section break stays with the paragraph that now ends the section.
413
+ if (pPr && firstChild(pPr, 'w:sectPr'))
414
+ removeChildren(pPr, 'w:sectPr');
415
+ const tailHasContent = tail.some((n) => n.type === 'element' && (findAll(n, 'w:t').some((t) => textContent(t) !== '') || findAll(n, 'w:tab').length > 0 || findAll(n, 'w:drawing').length > 0));
416
+ if (newPPr && !tailHasContent) {
417
+ // Enter at the end of a heading continues with the style's "next" style.
418
+ const styleId = attr(firstChild(newPPr, 'w:pStyle'), 'w:val');
419
+ const next = this.doc.styles.get(styleId)?.next;
420
+ if (styleId && next && next !== styleId) {
421
+ removeChildren(newPPr, 'w:pStyle');
422
+ if (this.doc.styles.get(next))
423
+ insertOrdered(newPPr, el('w:pStyle', { 'w:val': next }), PPR_ORDER);
424
+ removeChildren(newPPr, 'w:numPr');
425
+ }
426
+ }
427
+ const newPara = el('w:p', {}, [...(newPPr ? [newPPr] : []), ...tail]);
428
+ const parent = idx.parentOf(para);
429
+ parent.children.splice(indexOfChild(parent, para) + 1, 0, newPara);
430
+ this.changed();
431
+ return newPara;
432
+ }
433
+ /** Append text at the end of a paragraph. */
434
+ appendText(paragraph, text, format) {
435
+ const range = this.paragraphRange(paragraph);
436
+ this.check('edit', range);
437
+ const runs = elements(paragraph, 'w:r');
438
+ const run = newRun(text, runs[runs.length - 1], format);
439
+ paragraph.children.push(run);
440
+ this.changed();
441
+ return run;
442
+ }
443
+ /** Delete a range (it may span paragraphs, but not table cells). */
444
+ deleteRange(range) {
445
+ this.check('edit', range);
446
+ // Deleting inside one text node (backspace): edit it in place.
447
+ if (range.start.node === range.end.node && range.start.node.name === 'w:t') {
448
+ const current = textContent(range.start.node);
449
+ const a = Math.min(range.start.offset, range.end.offset);
450
+ const b = Math.max(range.start.offset, range.end.offset);
451
+ range.start.node.children = [{ type: 'text', value: current.slice(0, a) + current.slice(b) }];
452
+ this.changed();
453
+ return;
454
+ }
455
+ this.removeRange(range);
456
+ this.changed();
457
+ }
458
+ /** Replace a range with text formatted like the range's first run. */
459
+ replaceRange(range, text, format) {
460
+ this.check('edit', range);
461
+ const index = this.index();
462
+ const template = index.parentOf(range.start.node);
463
+ const { startMark, endMark, idx } = this.cut(range);
464
+ replaceMark(idx, startMark, text || format ? [newRun(text, template, format)] : []);
465
+ replaceMark(idx, endMark, []);
466
+ this.changed();
467
+ }
468
+ /** Replace every match; returns how many were replaced. */
469
+ replaceAll(query, replacement) {
470
+ const matches = this.find(query);
471
+ // Back to front, so earlier positions stay valid.
472
+ for (const m of matches.reverse()) {
473
+ const value = typeof replacement === 'string' ? replacement.replace(/\$(\d)/g, (_, d) => m.groups[Number(d) - 1] ?? '') : replacement(m);
474
+ this.replaceRange(m, value);
475
+ }
476
+ return matches.length;
477
+ }
478
+ /**
479
+ * Fill `{{name}}` placeholders (and content controls whose tag or title is a key).
480
+ * Returns the keys that were found.
481
+ */
482
+ fillTemplate(data, pattern = /\{\{\s*([\w.-]+)\s*\}\}/g, options = {}) {
483
+ const used = new Set();
484
+ // Back to front, so earlier positions stay valid.
485
+ for (const m of this.find(pattern).reverse()) {
486
+ const key = m.groups[0] ?? '';
487
+ if (!(key in data))
488
+ continue;
489
+ if (!options.includeLocked && this.isLocked(m))
490
+ continue;
491
+ this.withLocks(!!options.includeLocked, () => this.replaceRange(m, String(data[key] ?? '')));
492
+ used.add(key);
493
+ }
494
+ for (const key of this.fillContentControls(data, options))
495
+ used.add(key);
496
+ return [...used];
497
+ }
498
+ withLocks(bypass, fn) {
499
+ const saved = this.bypassLocks;
500
+ this.bypassLocks = saved || bypass;
501
+ try {
502
+ return fn();
503
+ }
504
+ finally {
505
+ this.bypassLocks = saved;
506
+ }
507
+ }
508
+ /** Set the text of content controls (w:sdt) by tag or title. Locked ones are skipped unless `includeLocked`. */
509
+ fillContentControls(data, options = {}) {
510
+ const used = [];
511
+ const idx = this.index();
512
+ for (const sdt of findAll(this.body, 'w:sdt')) {
513
+ const sdtPr = firstChild(sdt, 'w:sdtPr');
514
+ const key = attr(firstChild(sdtPr, 'w:tag'), 'w:val') ?? attr(firstChild(sdtPr, 'w:alias'), 'w:val');
515
+ if (key === undefined || !(key in data))
516
+ continue;
517
+ const content = firstChild(sdt, 'w:sdtContent');
518
+ if (!content)
519
+ continue;
520
+ if (!options.includeLocked && !this.bypassLocks && (locksContent(lockModeOf(sdt)) || this.lockAround(idx, sdt)))
521
+ continue;
522
+ this.check('fillForm');
523
+ const value = String(data[key] ?? '');
524
+ const firstRun = findAll(content, 'w:r')[0];
525
+ if (sdtPr)
526
+ removeChildren(sdtPr, 'w:showingPlcHdr');
527
+ const firstPara = firstChild(content, 'w:p');
528
+ if (firstPara) {
529
+ const pPr = firstChild(firstPara, 'w:pPr');
530
+ content.children = [el('w:p', {}, [...(pPr ? [pPr] : []), newRun(value, firstRun)])];
531
+ }
532
+ else {
533
+ content.children = [newRun(value, firstRun)];
534
+ }
535
+ // Placeholder text usually uses the "PlaceholderText" style; drop it from the new run.
536
+ for (const run of findAll(content, 'w:r')) {
537
+ const rStyle = firstChild(firstChild(run, 'w:rPr'), 'w:rStyle');
538
+ if (attr(rStyle, 'w:val') === 'PlaceholderText')
539
+ removeChildren(firstChild(run, 'w:rPr'), 'w:rStyle');
540
+ }
541
+ used.push(key);
542
+ }
543
+ if (used.length)
544
+ this.changed();
545
+ return used;
546
+ }
547
+ /** Apply character formatting to a range. */
548
+ formatRange(range, format) {
549
+ this.check('format', range);
550
+ const index = this.index();
551
+ const { startMark, endMark } = isolate(index, range);
552
+ const idx = this.index();
553
+ for (const run of between(idx, startMark, endMark, 'w:r'))
554
+ applyFormat(run, format);
555
+ replaceMark(idx, startMark, []);
556
+ replaceMark(idx, endMark, []);
557
+ this.changed();
558
+ }
559
+ /** Remove the content of a range, returning the sentinels at its (now adjacent) ends. */
560
+ cut(range) {
561
+ const index = this.index();
562
+ const { startMark, endMark } = isolate(index, range);
563
+ let idx = this.index();
564
+ const startCell = idx.ancestor(startMark, 'w:tc');
565
+ const endCell = idx.ancestor(endMark, 'w:tc');
566
+ if (startCell !== endCell) {
567
+ replaceMark(idx, startMark, []);
568
+ replaceMark(idx, endMark, []);
569
+ throw new EditError('The range crosses table cells');
570
+ }
571
+ const startPara = idx.ancestor(startMark, 'w:p');
572
+ const endPara = idx.ancestor(endMark, 'w:p');
573
+ // Remove runs between the marks, then whole paragraphs and tables in between.
574
+ for (const run of between(idx, startMark, endMark, 'w:r')) {
575
+ const parent = idx.parent.get(run);
576
+ if (parent)
577
+ parent.children.splice(parent.children.indexOf(run), 1);
578
+ }
579
+ if (startPara !== endPara) {
580
+ idx = this.index();
581
+ for (const node of between(idx, startMark, endMark)) {
582
+ if ((node.name === 'w:p' || node.name === 'w:tbl') && node !== endPara && !idx.ancestor(node, 'w:p')) {
583
+ const parent = idx.parent.get(node);
584
+ if (parent && parent.children.includes(node) && !isAncestor(idx, node, endMark))
585
+ parent.children.splice(parent.children.indexOf(node), 1);
586
+ }
587
+ }
588
+ // Merge the end paragraph's remaining content into the start paragraph.
589
+ idx = this.index();
590
+ const endContainer = idx.parentOf(endMark);
591
+ const tail = endContainer.children.splice(indexOfChild(endContainer, endMark));
592
+ startPara.children.push(...tail.filter((n) => !(n.type === 'element' && n.name === 'w:pPr')));
593
+ const endParent = idx.parent.get(endPara);
594
+ if (endParent)
595
+ endParent.children.splice(endParent.children.indexOf(endPara), 1);
596
+ }
597
+ return { startMark, endMark, idx: this.index() };
598
+ }
599
+ removeRange(range) {
600
+ const { startMark, endMark, idx } = this.cut(range);
601
+ replaceMark(idx, startMark, []);
602
+ replaceMark(idx, endMark, []);
603
+ }
604
+ // ---- paragraphs ---------------------------------------------------------------------------
605
+ /** Insert a paragraph before or after a block (or at the start/end of the body). */
606
+ insertParagraph(where, text = '', options = {}) {
607
+ const ref = typeof where === 'object' ? (where.before ?? where.after) : undefined;
608
+ this.check('edit', ref ? { start: { node: ref, offset: 0 }, end: { node: ref, offset: 0 } } : undefined);
609
+ const pPr = options.style ? [el('w:pPr', {}, [el('w:pStyle', { 'w:val': options.style })])] : [];
610
+ const para = el('w:p', {}, [...pPr, ...(text ? [newRun(text, undefined, options.format)] : [])]);
611
+ const body = this.body;
612
+ if (where === 'start')
613
+ body.children.unshift(para);
614
+ else if (where === 'end') {
615
+ const sect = firstChild(body, 'w:sectPr');
616
+ body.children.splice(sect ? body.children.indexOf(sect) : body.children.length, 0, para);
617
+ }
618
+ else {
619
+ const ref = where.before ?? where.after;
620
+ if (!ref)
621
+ throw new EditError('insertParagraph needs a reference block');
622
+ const idx = this.index();
623
+ const parent = idx.parentOf(ref);
624
+ parent.children.splice(indexOfChild(parent, ref) + (where.after ? 1 : 0), 0, para);
625
+ }
626
+ this.changed();
627
+ return para;
628
+ }
629
+ deleteParagraph(paragraph) {
630
+ this.check('edit', this.paragraphRange(paragraph) ?? { start: { node: paragraph, offset: 0 }, end: { node: paragraph, offset: 0 } });
631
+ const idx = this.index();
632
+ const parent = idx.parentOf(paragraph);
633
+ // A table cell must keep at least one paragraph.
634
+ if (parent.name === 'w:tc' && elements(parent, 'w:p').length === 1) {
635
+ paragraph.children = paragraph.children.filter((c) => c.type === 'element' && c.name === 'w:pPr');
636
+ }
637
+ else
638
+ parent.children.splice(indexOfChild(parent, paragraph), 1);
639
+ this.changed();
640
+ }
641
+ setParagraphStyle(paragraph, styleId) {
642
+ this.check('format', this.paragraphRange(paragraph));
643
+ const pPr = ensureChild(paragraph, 'w:pPr');
644
+ if (paragraph.children[0] !== pPr) {
645
+ paragraph.children.splice(paragraph.children.indexOf(pPr), 1);
646
+ paragraph.children.unshift(pPr);
647
+ }
648
+ removeChildren(pPr, 'w:pStyle');
649
+ insertOrdered(pPr, el('w:pStyle', { 'w:val': styleId }), PPR_ORDER);
650
+ this.changed();
651
+ }
652
+ // ---- hyperlinks and bookmarks -------------------------------------------------------------
653
+ /** Turn a range (within one paragraph) into a hyperlink to a URL or a bookmark. */
654
+ async addHyperlink(range, target, tooltip) {
655
+ this.check('link', range);
656
+ if ('url' in target && !/^(https?|mailto|tel|ftp):/i.test(target.url))
657
+ throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
658
+ const attrs = {};
659
+ if ('url' in target) {
660
+ attrs['r:id'] = await this.doc.pkg.addRelationship(this.doc.mainPart, REL.hyperlink, target.url, true);
661
+ await this.doc.refreshRels(this.doc.mainPart);
662
+ }
663
+ else
664
+ attrs['w:anchor'] = target.bookmark;
665
+ if (tooltip)
666
+ attrs['w:tooltip'] = tooltip;
667
+ attrs['w:history'] = '1';
668
+ await this.ensureCharacterStyle('Hyperlink', 'Hyperlink', '<w:color w:val="0563C1" w:themeColor="hyperlink"/><w:u w:val="single"/>');
669
+ const index = this.index();
670
+ const { startMark, endMark } = isolate(index, range);
671
+ const idx = this.index();
672
+ const container = idx.parentOf(startMark);
673
+ if (idx.parentOf(endMark) !== container) {
674
+ replaceMark(idx, startMark, []);
675
+ replaceMark(idx, endMark, []);
676
+ throw new EditError('A hyperlink must start and end in the same paragraph (and not cut across another link or field)');
677
+ }
678
+ const a = indexOfChild(container, startMark);
679
+ const b = indexOfChild(container, endMark);
680
+ const inner = container.children.slice(a + 1, b);
681
+ const link = el('w:hyperlink', attrs, inner);
682
+ for (const run of findAll(link, 'w:r')) {
683
+ const rPr = firstChild(run, 'w:rPr');
684
+ if (!firstChild(rPr, 'w:rStyle'))
685
+ applyFormat(run, { style: 'Hyperlink' });
686
+ }
687
+ container.children.splice(a, b - a + 1, link);
688
+ this.changed();
689
+ return link;
690
+ }
691
+ /** Unwrap a w:hyperlink, keeping its text. */
692
+ removeHyperlink(link) {
693
+ this.check('link');
694
+ const idx = this.index();
695
+ const parent = idx.parentOf(link);
696
+ const runs = link.children;
697
+ for (const run of findAll(link, 'w:r')) {
698
+ const rPr = firstChild(run, 'w:rPr');
699
+ const rStyle = firstChild(rPr, 'w:rStyle');
700
+ if (attr(rStyle, 'w:val') === 'Hyperlink')
701
+ removeChildren(rPr, 'w:rStyle');
702
+ }
703
+ parent.children.splice(indexOfChild(parent, link), 1, ...runs);
704
+ this.changed();
705
+ }
706
+ /** Every w:hyperlink in the body with its target. */
707
+ hyperlinks() {
708
+ const rels = this.doc.rels(this.doc.mainPart);
709
+ return findAll(this.body, 'w:hyperlink').map((h) => {
710
+ const rId = attr(h, 'r:id');
711
+ return { el: h, url: rId ? rels.get(rId)?.target : undefined, anchor: attr(h, 'w:anchor'), tooltip: attr(h, 'w:tooltip'), text: textContent(h) };
712
+ });
713
+ }
714
+ addBookmark(range, name) {
715
+ this.check('bookmark', range);
716
+ if (!BOOKMARK_NAME.test(name))
717
+ throw new EditError('Bookmark names start with a letter and use up to 40 letters, digits or underscores');
718
+ if (this.bookmarks().some((b) => b.name === name))
719
+ throw new EditError(`A bookmark named "${name}" already exists`);
720
+ const id = String(1 + Math.max(-1, ...findAll(this.root, 'w:bookmarkStart').map((b) => Number(attr(b, 'w:id') ?? -1))));
721
+ const index = this.index();
722
+ const { startMark, endMark } = isolate(index, range);
723
+ const idx = this.index();
724
+ replaceMark(idx, startMark, [el('w:bookmarkStart', { 'w:id': id, 'w:name': name })]);
725
+ replaceMark(idx, endMark, [el('w:bookmarkEnd', { 'w:id': id })]);
726
+ this.changed();
727
+ }
728
+ bookmarks() {
729
+ return findAll(this.root, 'w:bookmarkStart').map((b) => ({ id: attr(b, 'w:id') ?? '', name: attr(b, 'w:name') ?? '' }));
730
+ }
731
+ removeBookmark(name) {
732
+ this.check('bookmark');
733
+ const start = findAll(this.root, 'w:bookmarkStart').find((b) => attr(b, 'w:name') === name);
734
+ if (!start)
735
+ return;
736
+ const id = attr(start, 'w:id');
737
+ const idx = this.index();
738
+ for (const node of [start, ...findAll(this.root, 'w:bookmarkEnd').filter((b) => attr(b, 'w:id') === id)]) {
739
+ const parent = idx.parentOf(node);
740
+ parent.children.splice(indexOfChild(parent, node), 1);
741
+ }
742
+ this.changed();
743
+ }
744
+ // ---- editable ranges (exceptions to document protection) ---------------------------------
745
+ /** Let a user (w:ed, e.g. an e-mail or DOMAIN\\user) or a group (w:edGrp, e.g. "everyone") edit a range. */
746
+ addEditableRange(range, who) {
747
+ this.check('protect', range);
748
+ if (!who.editor && !who.group)
749
+ throw new EditError('An editable range needs an editor or a group');
750
+ const id = String(1 + Math.max(0, ...findAll(this.root, 'w:permStart').map((n) => Number(attr(n, 'w:id') ?? 0))));
751
+ const index = this.index();
752
+ const { startMark, endMark } = isolate(index, range);
753
+ const idx = this.index();
754
+ replaceMark(idx, startMark, [el('w:permStart', { 'w:id': id, 'w:ed': who.editor, 'w:edGrp': who.editor ? undefined : who.group })]);
755
+ replaceMark(idx, endMark, [el('w:permEnd', { 'w:id': id })]);
756
+ this.changed();
757
+ return id;
758
+ }
759
+ editableRanges() {
760
+ return findAll(this.root, 'w:permStart').map((n) => ({ id: attr(n, 'w:id') ?? '', editor: attr(n, 'w:ed'), group: attr(n, 'w:edGrp') }));
761
+ }
762
+ removeEditableRange(id) {
763
+ this.check('protect');
764
+ const idx = this.index();
765
+ for (const node of [...findAll(this.root, 'w:permStart'), ...findAll(this.root, 'w:permEnd')]) {
766
+ if (attr(node, 'w:id') !== id)
767
+ continue;
768
+ const parent = idx.parentOf(node);
769
+ parent.children.splice(indexOfChild(parent, node), 1);
770
+ }
771
+ this.changed();
772
+ }
773
+ // ---- locked regions (content controls that cannot be edited) ------------------------------
774
+ /** The locked inline region whose first or last character is at `pos`. */
775
+ lockEdge(pos) {
776
+ const idx = this.index();
777
+ if (!idx.contains(pos.node) || pos.node.name === 'w:p')
778
+ return undefined;
779
+ const sdt = this.lockAround(idx, pos.node);
780
+ const content = firstChild(sdt, 'w:sdtContent');
781
+ if (!sdt || !content || firstChild(content, 'w:p'))
782
+ return undefined;
783
+ const items = findAll(content, 'w:r').flatMap((r) => elements(r).filter((c) => c.name !== 'w:rPr'));
784
+ const first = items[0];
785
+ const last = items[items.length - 1];
786
+ if (pos.node === first && pos.offset === 0)
787
+ return { sdt, after: false };
788
+ const end = last?.name === 'w:t' ? textContent(last).length : 1;
789
+ if (pos.node === last && pos.offset >= end)
790
+ return { sdt, after: true };
791
+ return undefined;
792
+ }
793
+ /** A locked block of paragraphs that `pos` sits at the very start or end of. */
794
+ blockLockEdge(pos) {
795
+ const idx = this.index();
796
+ if (!idx.contains(pos.node))
797
+ return undefined;
798
+ const paragraph = pos.node.name === 'w:p' ? pos.node : idx.ancestor(pos.node, 'w:p');
799
+ if (!paragraph)
800
+ return undefined;
801
+ const content = idx.parent.get(paragraph);
802
+ const sdt = content?.name === 'w:sdtContent' ? idx.parent.get(content) : undefined;
803
+ if (!sdt || !locksContent(lockModeOf(sdt)))
804
+ return undefined;
805
+ const paras = elements(content, 'w:p');
806
+ const range = this.paragraphRange(paragraph);
807
+ const atStart = !range || (pos.node === range.start.node && pos.offset === range.start.offset);
808
+ const atEnd = !range || (pos.node === range.end.node && pos.offset === range.end.offset);
809
+ if (atEnd && paragraph === paras[paras.length - 1])
810
+ return { sdt, paragraph, after: true };
811
+ if (atStart && paragraph === paras[0])
812
+ return { sdt, paragraph, after: false };
813
+ return undefined;
814
+ }
815
+ /**
816
+ * Lock a range against editing. Inside one paragraph the exact text is locked; a range that
817
+ * spans paragraphs locks those whole paragraphs. Stored as a Word content control, so Word
818
+ * enforces the lock too. Returns the region's id.
819
+ */
820
+ lockRange(range, options = {}) {
821
+ this.check('protect', range);
822
+ const mode = options.mode ?? 'content';
823
+ const used = new Set(findAll(this.root, 'w:id').map((n) => attr(n, 'w:val')));
824
+ let id;
825
+ do
826
+ id = String(1 + Math.floor(Math.random() * 0x7ffffffe));
827
+ while (used.has(id));
828
+ const sdtPr = el('w:sdtPr', {}, [
829
+ ...(options.title ? [el('w:alias', { 'w:val': options.title })] : []),
830
+ el('w:tag', { 'w:val': options.tag ?? LOCK_TAG }),
831
+ el('w:id', { 'w:val': id }),
832
+ el('w:lock', { 'w:val': LOCK_VALUES[mode] }),
833
+ ]);
834
+ let idx = this.index();
835
+ const paraOf = (node) => (node.name === 'w:p' ? node : idx.ancestor(node, 'w:p'));
836
+ const startPara = paraOf(range.start.node);
837
+ const endPara = paraOf(range.end.node);
838
+ if (!startPara || !endPara)
839
+ throw new EditError('The range is not inside a paragraph');
840
+ if (startPara === endPara && range.start.node.name !== 'w:p') {
841
+ const { startMark, endMark } = isolate(idx, range);
842
+ idx = this.index();
843
+ const container = idx.parentOf(startMark);
844
+ if (idx.parentOf(endMark) !== container) {
845
+ replaceMark(idx, startMark, []);
846
+ replaceMark(idx, endMark, []);
847
+ throw new EditError('A locked region inside a paragraph must not cut across a link or field');
848
+ }
849
+ const a = indexOfChild(container, startMark);
850
+ const b = indexOfChild(container, endMark);
851
+ const inner = container.children.slice(a + 1, b);
852
+ if (!inner.length) {
853
+ container.children.splice(a, b - a + 1);
854
+ throw new EditError('Select some text to lock');
855
+ }
856
+ container.children.splice(a, b - a + 1, el('w:sdt', {}, [sdtPr, el('w:sdtContent', {}, inner)]));
857
+ }
858
+ else {
859
+ const parent = idx.parentOf(startPara);
860
+ if (idx.parentOf(endPara) !== parent)
861
+ throw new EditError('A locked region must not cross table cells');
862
+ const a = indexOfChild(parent, startPara);
863
+ const b = indexOfChild(parent, endPara);
864
+ const [lo, hi] = a <= b ? [a, b] : [b, a];
865
+ const blocks = parent.children.slice(lo, hi + 1);
866
+ parent.children.splice(lo, hi - lo + 1, el('w:sdt', {}, [sdtPr, el('w:sdtContent', {}, blocks)]));
867
+ }
868
+ this.changed();
869
+ return id;
870
+ }
871
+ /** Lock whole paragraphs (from `first` to `last`). */
872
+ lockParagraphs(first, last = first, options = {}) {
873
+ return this.lockRange({ start: { node: first, offset: 0 }, end: { node: last, offset: 0 } }, options);
874
+ }
875
+ /** Every locked content control in the body. */
876
+ lockedRegions() {
877
+ return findAll(this.body, 'w:sdt')
878
+ .filter((sdt) => lockModeOf(sdt))
879
+ .map((sdt) => {
880
+ const sdtPr = firstChild(sdt, 'w:sdtPr');
881
+ const content = firstChild(sdt, 'w:sdtContent');
882
+ return {
883
+ id: attr(firstChild(sdtPr, 'w:id'), 'w:val') ?? '',
884
+ mode: lockModeOf(sdt),
885
+ title: sdtTitle(sdt),
886
+ tag: attr(firstChild(sdtPr, 'w:tag'), 'w:val'),
887
+ text: content ? findAll(content, 'w:p').length ? findAll(content, 'w:p').map((p) => textContent(p)).join('\n') : textContent(content) : '',
888
+ block: !!firstChild(content, 'w:p'),
889
+ el: sdt,
890
+ };
891
+ });
892
+ }
893
+ /**
894
+ * Remove a lock. Regions docxkeun created are unwrapped completely; other content controls
895
+ * keep their control and only lose the lock.
896
+ */
897
+ unlock(id) {
898
+ this.check('protect');
899
+ const region = this.lockedRegions().find((r) => r.id === id);
900
+ if (!region)
901
+ throw new EditError(`No locked region with id ${id}`);
902
+ if (region.tag === LOCK_TAG) {
903
+ const idx = this.index();
904
+ const parent = idx.parentOf(region.el);
905
+ parent.children.splice(indexOfChild(parent, region.el), 1, ...(firstChild(region.el, 'w:sdtContent')?.children ?? []));
906
+ }
907
+ else {
908
+ removeChildren(firstChild(region.el, 'w:sdtPr'), 'w:lock');
909
+ }
910
+ this.changed();
911
+ }
912
+ // ---- comments -----------------------------------------------------------------------------
913
+ /** Add a comment anchored to a range. Returns the new comment id. */
914
+ async addComment(range, input) {
915
+ this.check('comment', range);
916
+ const id = await this.writeComment(input);
917
+ const index = this.index();
918
+ const { startMark, endMark } = isolate(index, range);
919
+ const idx = this.index();
920
+ replaceMark(idx, startMark, [el('w:commentRangeStart', { 'w:id': id })]);
921
+ replaceMark(idx, endMark, [el('w:commentRangeEnd', { 'w:id': id }), referenceRun(id)]);
922
+ this.changed();
923
+ return id;
924
+ }
925
+ /** Reply to a comment (Word threads replies on the same anchor). */
926
+ async replyToComment(parentId, input) {
927
+ this.check('reply');
928
+ const parent = await this.commentElement(parentId);
929
+ if (!parent)
930
+ throw new EditError(`No comment with id ${parentId}`);
931
+ const id = await this.writeComment(input, parentId);
932
+ const idx = this.index();
933
+ const start = findAll(this.root, 'w:commentRangeStart').find((n) => attr(n, 'w:id') === parentId);
934
+ const end = findAll(this.root, 'w:commentRangeEnd').find((n) => attr(n, 'w:id') === parentId);
935
+ if (start) {
936
+ const p = idx.parentOf(start);
937
+ p.children.splice(indexOfChild(p, start) + 1, 0, el('w:commentRangeStart', { 'w:id': id }));
938
+ }
939
+ const refRun = findAll(this.root, 'w:commentReference').find((n) => attr(n, 'w:id') === parentId);
940
+ const anchorNode = refRun ? idx.parentOf(refRun) : end;
941
+ if (anchorNode) {
942
+ const p = idx.parentOf(anchorNode);
943
+ p.children.splice(indexOfChild(p, anchorNode) + 1, 0, el('w:commentRangeEnd', { 'w:id': id }), referenceRun(id));
944
+ }
945
+ this.changed();
946
+ return id;
947
+ }
948
+ /** Mark a comment thread resolved (done) or open again. */
949
+ async resolveComment(id, resolved = true) {
950
+ this.check('resolveComment');
951
+ const comment = await this.commentElement(id);
952
+ if (!comment)
953
+ throw new EditError(`No comment with id ${id}`);
954
+ const paraId = this.ensureParaId(comment);
955
+ const { name, xml } = await ensurePart(this.doc, 'commentsExtended');
956
+ let entry = findAll(xml.root, 'w15:commentEx').find((e) => attr(e, 'w15:paraId')?.toUpperCase() === paraId);
957
+ if (!entry) {
958
+ entry = el('w15:commentEx', { 'w15:paraId': paraId, 'w15:done': '0' });
959
+ xml.root.children.push(entry);
960
+ }
961
+ entry.attrs['w15:done'] = resolved ? '1' : '0';
962
+ this.doc.touch(name);
963
+ this.doc.touch(this.doc.parts.comments);
964
+ }
965
+ /** Replace a comment's text. */
966
+ async editComment(id, text) {
967
+ const comment = await this.commentElement(id);
968
+ if (!comment)
969
+ throw new EditError(`No comment with id ${id}`);
970
+ this.check('editComment', undefined, { commentAuthor: attr(comment, 'w:author') });
971
+ const paraId = this.ensureParaId(comment);
972
+ comment.children = [commentParagraph(text, paraId)];
973
+ this.doc.touch(this.doc.parts.comments);
974
+ }
975
+ /** Delete a comment, its replies and its anchors. */
976
+ async deleteComment(id) {
977
+ const comment = await this.commentElement(id);
978
+ if (!comment)
979
+ return;
980
+ this.check('deleteComment', undefined, { commentAuthor: attr(comment, 'w:author') });
981
+ const { readComments } = await import('../comments/read.js');
982
+ const all = readComments(this.doc);
983
+ const doomed = new Set([id]);
984
+ for (let grew = true; grew;) {
985
+ grew = false;
986
+ for (const c of all)
987
+ if (c.parentId && doomed.has(c.parentId) && !doomed.has(c.id)) {
988
+ doomed.add(c.id);
989
+ grew = true;
990
+ }
991
+ }
992
+ const paraIds = new Set(all.filter((c) => doomed.has(c.id) && c.paraId).map((c) => c.paraId));
993
+ const durableIds = new Set(all.filter((c) => doomed.has(c.id) && c.durableId).map((c) => c.durableId));
994
+ const commentsXml = this.doc.xmlSync(this.doc.parts.comments);
995
+ commentsXml.root.children = commentsXml.root.children.filter((n) => !(n.type === 'element' && n.name === 'w:comment' && doomed.has(attr(n, 'w:id') ?? '')));
996
+ this.doc.touch(this.doc.parts.comments);
997
+ const prune = async (kind, test) => {
998
+ const part = this.doc.parts[kind];
999
+ const xml = this.doc.xmlSync(part);
1000
+ if (!part || !xml)
1001
+ return;
1002
+ xml.root.children = xml.root.children.filter((n) => !(n.type === 'element' && test(n)));
1003
+ this.doc.touch(part);
1004
+ };
1005
+ await prune('commentsExtended', (n) => paraIds.has(attr(n, 'w15:paraId')?.toUpperCase() ?? ''));
1006
+ await prune('commentsIds', (n) => paraIds.has(attr(n, 'w16cid:paraId')?.toUpperCase() ?? ''));
1007
+ await prune('commentsExtensible', (n) => durableIds.has(attr(n, 'w16cex:durableId') ?? ''));
1008
+ // Anchors in the body: range markers and the runs holding references.
1009
+ const idx = this.index();
1010
+ for (const name of ['w:commentRangeStart', 'w:commentRangeEnd']) {
1011
+ for (const n of findAll(this.root, name)) {
1012
+ if (!doomed.has(attr(n, 'w:id') ?? ''))
1013
+ continue;
1014
+ const parent = idx.parentOf(n);
1015
+ parent.children.splice(indexOfChild(parent, n), 1);
1016
+ }
1017
+ }
1018
+ for (const ref of findAll(this.root, 'w:commentReference')) {
1019
+ if (!doomed.has(attr(ref, 'w:id') ?? ''))
1020
+ continue;
1021
+ const run = idx.parentOf(ref);
1022
+ const parent = idx.parentOf(run);
1023
+ run.children.splice(indexOfChild(run, ref), 1);
1024
+ if (!run.children.some((c) => c.type === 'element' && c.name !== 'w:rPr'))
1025
+ parent.children.splice(indexOfChild(parent, run), 1);
1026
+ }
1027
+ this.changed();
1028
+ }
1029
+ async commentElement(id) {
1030
+ const xml = this.doc.xmlSync(this.doc.parts.comments);
1031
+ return xml ? elements(xml.root, 'w:comment').find((c) => attr(c, 'w:id') === id) : undefined;
1032
+ }
1033
+ ensureParaId(comment) {
1034
+ const paras = elements(comment, 'w:p');
1035
+ let last = paras[paras.length - 1];
1036
+ if (!last) {
1037
+ last = el('w:p');
1038
+ comment.children.push(last);
1039
+ }
1040
+ let paraId = attr(last, 'w14:paraId')?.toUpperCase();
1041
+ if (!paraId) {
1042
+ paraId = randomHexId();
1043
+ last.attrs['w14:paraId'] = paraId;
1044
+ last.attrs['w14:textId'] = '77777777';
1045
+ }
1046
+ return paraId;
1047
+ }
1048
+ async writeComment(input, parentId) {
1049
+ if (!input.author.trim())
1050
+ throw new EditError('A comment needs an author');
1051
+ const comments = await ensurePart(this.doc, 'comments');
1052
+ ensureNamespaces(comments.xml);
1053
+ const ids = elements(comments.xml.root, 'w:comment').map((c) => Number(attr(c, 'w:id') ?? -1));
1054
+ // Comment ids share a space with other annotation ids in Word; stay above all of them.
1055
+ const bodyIds = findAll(this.root, 'w:commentRangeStart').map((c) => Number(attr(c, 'w:id') ?? -1));
1056
+ const id = String(1 + Math.max(-1, ...ids, ...bodyIds));
1057
+ const date = input.date ?? new Date();
1058
+ const paraId = randomHexId();
1059
+ const initials = input.initials ?? input.author.split(/\s+/).map((w) => w[0] ?? '').join('').slice(0, 3).toUpperCase();
1060
+ comments.xml.root.children.push(el('w:comment', { 'w:id': id, 'w:author': input.author, 'w:date': localDate(date), 'w:initials': initials }, [commentParagraph(input.text, paraId)]));
1061
+ this.doc.touch(comments.name);
1062
+ let parentParaId;
1063
+ if (parentId) {
1064
+ const parent = elements(comments.xml.root, 'w:comment').find((c) => attr(c, 'w:id') === parentId);
1065
+ if (parent)
1066
+ parentParaId = this.ensureParaId(parent);
1067
+ }
1068
+ const ext = await ensurePart(this.doc, 'commentsExtended');
1069
+ ext.xml.root.children.push(el('w15:commentEx', { 'w15:paraId': paraId, 'w15:paraIdParent': parentParaId, 'w15:done': '0' }));
1070
+ this.doc.touch(ext.name);
1071
+ const durableId = randomHexId();
1072
+ const idsPart = await ensurePart(this.doc, 'commentsIds');
1073
+ idsPart.xml.root.children.push(el('w16cid:commentId', { 'w16cid:paraId': paraId, 'w16cid:durableId': durableId }));
1074
+ this.doc.touch(idsPart.name);
1075
+ const extensible = await ensurePart(this.doc, 'commentsExtensible');
1076
+ extensible.xml.root.children.push(el('w16cex:commentExtensible', { 'w16cex:durableId': durableId, 'w16cex:dateUtc': date.toISOString().replace(/\.\d{3}Z$/, 'Z') }));
1077
+ this.doc.touch(extensible.name);
1078
+ const people = await ensurePart(this.doc, 'people');
1079
+ if (!elements(people.xml.root, 'w15:person').some((p) => attr(p, 'w15:author') === input.author)) {
1080
+ people.xml.root.children.push(el('w15:person', { 'w15:author': input.author }, [el('w15:presenceInfo', { 'w15:providerId': 'None', 'w15:userId': input.author })]));
1081
+ this.doc.touch(people.name);
1082
+ }
1083
+ return id;
1084
+ }
1085
+ // ---- styles -------------------------------------------------------------------------------
1086
+ async ensureCharacterStyle(id, name, rPrXml) {
1087
+ if (this.doc.styles.get(id))
1088
+ return;
1089
+ const styles = await ensurePart(this.doc, 'styles');
1090
+ const { parseXml } = await import('../xml/index.js');
1091
+ const fragment = parseXml(`<w:style xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="character" w:styleId="${id}"><w:name w:val="${name}"/><w:uiPriority w:val="99"/><w:unhideWhenUsed/><w:rPr>${rPrXml}</w:rPr></w:style>`).root;
1092
+ delete fragment.attrs['xmlns:w'];
1093
+ styles.xml.root.children.push(fragment);
1094
+ this.doc.touch(styles.name);
1095
+ }
1096
+ }
1097
+ function isAncestor(idx, node, descendant) {
1098
+ let cur = idx.parent.get(descendant);
1099
+ while (cur) {
1100
+ if (cur === node)
1101
+ return true;
1102
+ cur = idx.parent.get(cur);
1103
+ }
1104
+ return false;
1105
+ }
1106
+ function referenceRun(id) {
1107
+ return el('w:r', {}, [el('w:rPr', {}, [el('w:rStyle', { 'w:val': 'CommentReference' })]), el('w:commentReference', { 'w:id': id })]);
1108
+ }
1109
+ function commentParagraph(text, paraId) {
1110
+ return el('w:p', { 'w14:paraId': paraId, 'w14:textId': '77777777' }, [
1111
+ el('w:pPr', {}, [el('w:pStyle', { 'w:val': 'CommentText' })]),
1112
+ el('w:r', {}, [el('w:rPr', {}, [el('w:rStyle', { 'w:val': 'CommentReference' })]), el('w:annotationRef')]),
1113
+ el('w:r', {}, runContent(text)),
1114
+ ]);
1115
+ }
1116
+ /** Word writes w:date as local time without a zone designator. */
1117
+ function localDate(d) {
1118
+ const pad = (n) => String(n).padStart(2, '0');
1119
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}Z`;
1120
+ }
1121
+ export { EditError };