docxkeun 0.1.2 → 0.2.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 (197) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +139 -16
  3. package/dist/api/editor.d.ts +172 -5
  4. package/dist/api/editor.js +814 -24
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +5 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +390 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/charts/color.d.ts +45 -0
  18. package/dist/charts/color.js +322 -0
  19. package/dist/charts/format.d.ts +12 -0
  20. package/dist/charts/format.js +459 -0
  21. package/dist/charts/index.d.ts +11 -0
  22. package/dist/charts/index.js +8 -0
  23. package/dist/charts/model.d.ts +225 -0
  24. package/dist/charts/model.js +758 -0
  25. package/dist/charts/outline.d.ts +17 -0
  26. package/dist/charts/outline.js +214 -0
  27. package/dist/charts/render.d.ts +20 -0
  28. package/dist/charts/render.js +1772 -0
  29. package/dist/drawing/arrows.d.ts +37 -0
  30. package/dist/drawing/arrows.js +99 -0
  31. package/dist/drawing/formula.d.ts +40 -0
  32. package/dist/drawing/formula.js +159 -0
  33. package/dist/drawing/geometry.d.ts +61 -0
  34. package/dist/drawing/geometry.js +286 -0
  35. package/dist/drawing/index.d.ts +12 -0
  36. package/dist/drawing/index.js +8 -0
  37. package/dist/drawing/presets.d.ts +72 -0
  38. package/dist/drawing/presets.js +2874 -0
  39. package/dist/fonts/shaping/apply.d.ts +94 -0
  40. package/dist/fonts/shaping/apply.js +349 -0
  41. package/dist/fonts/shaping/arabic.d.ts +28 -0
  42. package/dist/fonts/shaping/arabic.js +235 -0
  43. package/dist/fonts/shaping/buffer.d.ts +53 -0
  44. package/dist/fonts/shaping/buffer.js +95 -0
  45. package/dist/fonts/shaping/gdef.d.ts +30 -0
  46. package/dist/fonts/shaping/gdef.js +66 -0
  47. package/dist/fonts/shaping/gpos.d.ts +86 -0
  48. package/dist/fonts/shaping/gpos.js +428 -0
  49. package/dist/fonts/shaping/gsub.d.ts +65 -0
  50. package/dist/fonts/shaping/gsub.js +313 -0
  51. package/dist/fonts/shaping/index.d.ts +32 -0
  52. package/dist/fonts/shaping/index.js +402 -0
  53. package/dist/fonts/shaping/indic.d.ts +6 -0
  54. package/dist/fonts/shaping/indic.js +805 -0
  55. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  56. package/dist/fonts/shaping/layout-common.js +349 -0
  57. package/dist/fonts/shaping/plan.d.ts +87 -0
  58. package/dist/fonts/shaping/plan.js +152 -0
  59. package/dist/fonts/shaping/scripts.d.ts +26 -0
  60. package/dist/fonts/shaping/scripts.js +160 -0
  61. package/dist/fonts/shaping/shaper.d.ts +23 -0
  62. package/dist/fonts/shaping/shaper.js +5 -0
  63. package/dist/fonts/shaping/unicode.d.ts +34 -0
  64. package/dist/fonts/shaping/unicode.js +138 -0
  65. package/dist/images/bmp.d.ts +9 -0
  66. package/dist/images/bmp.js +234 -0
  67. package/dist/images/gif.d.ts +9 -0
  68. package/dist/images/gif.js +215 -0
  69. package/dist/images/index.d.ts +18 -0
  70. package/dist/images/index.js +63 -0
  71. package/dist/images/png-encode.d.ts +4 -0
  72. package/dist/images/png-encode.js +73 -0
  73. package/dist/images/size.d.ts +10 -0
  74. package/dist/images/size.js +83 -0
  75. package/dist/images/tiff.d.ts +14 -0
  76. package/dist/images/tiff.js +407 -0
  77. package/dist/index.d.ts +7 -2
  78. package/dist/index.js +5 -0
  79. package/dist/layout/bidi.d.ts +18 -0
  80. package/dist/layout/bidi.js +71 -0
  81. package/dist/layout/blocks.d.ts +20 -3
  82. package/dist/layout/blocks.js +88 -58
  83. package/dist/layout/cache.d.ts +31 -0
  84. package/dist/layout/cache.js +38 -0
  85. package/dist/layout/drawing.d.ts +30 -0
  86. package/dist/layout/drawing.js +120 -0
  87. package/dist/layout/engine.d.ts +3 -0
  88. package/dist/layout/engine.js +218 -11
  89. package/dist/layout/index.d.ts +1 -0
  90. package/dist/layout/index.js +1 -0
  91. package/dist/layout/lines.d.ts +63 -5
  92. package/dist/layout/lines.js +245 -20
  93. package/dist/layout/paint.d.ts +25 -3
  94. package/dist/layout/paint.js +26 -10
  95. package/dist/layout/shapes.d.ts +7 -0
  96. package/dist/layout/shapes.js +338 -0
  97. package/dist/layout/style.d.ts +4 -0
  98. package/dist/layout/style.js +2 -0
  99. package/dist/layout/types.d.ts +89 -2
  100. package/dist/math/boxes.d.ts +88 -0
  101. package/dist/math/boxes.js +166 -0
  102. package/dist/math/index.d.ts +29 -0
  103. package/dist/math/index.js +44 -0
  104. package/dist/math/layout.d.ts +13 -0
  105. package/dist/math/layout.js +771 -0
  106. package/dist/math/linear.d.ts +3 -0
  107. package/dist/math/linear.js +152 -0
  108. package/dist/math/omml.d.ts +15 -0
  109. package/dist/math/omml.js +57 -0
  110. package/dist/math/paths.d.ts +61 -0
  111. package/dist/math/paths.js +450 -0
  112. package/dist/math/symbols.d.ts +49 -0
  113. package/dist/math/symbols.js +269 -0
  114. package/dist/math/text.d.ts +53 -0
  115. package/dist/math/text.js +316 -0
  116. package/dist/metafile/canvas.d.ts +80 -0
  117. package/dist/metafile/canvas.js +515 -0
  118. package/dist/metafile/dib.d.ts +27 -0
  119. package/dist/metafile/dib.js +300 -0
  120. package/dist/metafile/emf.d.ts +31 -0
  121. package/dist/metafile/emf.js +591 -0
  122. package/dist/metafile/geometry.d.ts +49 -0
  123. package/dist/metafile/geometry.js +85 -0
  124. package/dist/metafile/index.d.ts +27 -0
  125. package/dist/metafile/index.js +34 -0
  126. package/dist/metafile/reader.d.ts +28 -0
  127. package/dist/metafile/reader.js +59 -0
  128. package/dist/metafile/state.d.ts +118 -0
  129. package/dist/metafile/state.js +172 -0
  130. package/dist/metafile/text.d.ts +17 -0
  131. package/dist/metafile/text.js +130 -0
  132. package/dist/metafile/wmf.d.ts +33 -0
  133. package/dist/metafile/wmf.js +395 -0
  134. package/dist/model/content.d.ts +92 -7
  135. package/dist/model/content.js +251 -17
  136. package/dist/model/document.d.ts +34 -1
  137. package/dist/model/document.js +80 -1
  138. package/dist/model/fields.d.ts +4 -0
  139. package/dist/model/fields.js +10 -0
  140. package/dist/model/numbering.d.ts +2 -0
  141. package/dist/model/numbering.js +22 -0
  142. package/dist/model/props.d.ts +2 -0
  143. package/dist/model/props.js +3 -0
  144. package/dist/opc/index.d.ts +1 -1
  145. package/dist/opc/package.d.ts +34 -0
  146. package/dist/opc/package.js +58 -4
  147. package/dist/pdf/export.js +97 -6
  148. package/dist/pdf/images.d.ts +7 -0
  149. package/dist/pdf/images.js +39 -2
  150. package/dist/render/activity.d.ts +138 -0
  151. package/dist/render/activity.js +794 -0
  152. package/dist/render/clipboard.d.ts +29 -0
  153. package/dist/render/clipboard.js +401 -0
  154. package/dist/render/comments.d.ts +166 -0
  155. package/dist/render/comments.js +779 -0
  156. package/dist/render/context-menu.d.ts +124 -0
  157. package/dist/render/context-menu.js +525 -0
  158. package/dist/render/editing.d.ts +146 -5
  159. package/dist/render/editing.js +678 -53
  160. package/dist/render/index.d.ts +12 -0
  161. package/dist/render/index.js +11 -0
  162. package/dist/render/navigation-panel.d.ts +76 -0
  163. package/dist/render/navigation-panel.js +431 -0
  164. package/dist/render/selection.js +5 -0
  165. package/dist/render/svg.d.ts +4 -6
  166. package/dist/render/svg.js +69 -7
  167. package/dist/render/toolbar.d.ts +83 -0
  168. package/dist/render/toolbar.js +505 -0
  169. package/dist/render/ui/comment-layout.d.ts +39 -0
  170. package/dist/render/ui/comment-layout.js +79 -0
  171. package/dist/render/ui/icons.d.ts +6 -0
  172. package/dist/render/ui/icons.js +38 -0
  173. package/dist/render/ui/menu.d.ts +38 -0
  174. package/dist/render/ui/menu.js +274 -0
  175. package/dist/render/ui/nav-model.d.ts +11 -0
  176. package/dist/render/ui/nav-model.js +34 -0
  177. package/dist/render/ui/overflow.d.ts +5 -0
  178. package/dist/render/ui/overflow.js +18 -0
  179. package/dist/render/ui/popover.d.ts +18 -0
  180. package/dist/render/ui/popover.js +109 -0
  181. package/dist/render/ui/theme.d.ts +2 -0
  182. package/dist/render/ui/theme.js +29 -0
  183. package/dist/render/undo.d.ts +76 -0
  184. package/dist/render/undo.js +144 -0
  185. package/dist/render/viewer.d.ts +100 -7
  186. package/dist/render/viewer.js +302 -92
  187. package/dist/security/policy.d.ts +3 -0
  188. package/dist/security/policy.js +6 -2
  189. package/dist/security/protection.d.ts +1 -0
  190. package/dist/security/protection.js +1 -1
  191. package/dist/text/bidi-data.d.ts +53 -0
  192. package/dist/text/bidi-data.js +318 -0
  193. package/dist/text/bidi.d.ts +37 -0
  194. package/dist/text/bidi.js +508 -0
  195. package/dist/xml/ns.d.ts +5 -0
  196. package/dist/xml/ns.js +7 -0
  197. package/package.json +9 -2
@@ -3,9 +3,14 @@
3
3
  * everything docxkeun does not understand is preserved), passes through the access guard, and
4
4
  * notifies listeners such as the viewer.
5
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';
6
+ import { CONTENT_TYPE, IMAGE_CONTENT_TYPES, REL } from '../opc/index.js';
7
+ import { imageInfo } from '../images/size.js';
8
+ import { hasEvenPages, hasFirstPage, headerParagraphs, headerText, referencesOf, sectionProperties, SECTPR_ORDER, textWidth } from './headers.js';
9
+ import { attr, el, elements, ensureChild, findAll, firstChild, insertOrdered, NS, removeChildren, textContent } from '../xml/index.js';
10
+ import { createList, listItems } from './lists.js';
11
+ import { acceptRevisions, cleanRunProps, deleteRun, insertedRuns, listRevisions, markParagraph, nextRevisionId, paragraphMarkRevision, recordParagraphFormat, recordRunFormat, rejectRevisions, revisionStamp, runRevision, } from './revisions.js';
12
+ import { SETTINGS_ORDER } from '../security/protection.js';
13
+ import { ensureNamespaces, ensurePart, randomHexId, ROOT_NAMESPACES } from './parts.js';
9
14
  import { between, EditError, indexOfChild, isolate, PPR_ORDER, replaceMark, RPR_ORDER, textNode, TreeIndex, } from './positions.js';
10
15
  const LOCK_VALUES = { content: 'contentLocked', contentAndControl: 'sdtContentLocked', control: 'sdtLocked' };
11
16
  const LOCK_MODES = { contentLocked: 'content', sdtContentLocked: 'contentAndControl', sdtLocked: 'control' };
@@ -31,6 +36,18 @@ function sdtTitle(sdt) {
31
36
  function locksContent(mode) {
32
37
  return mode === 'content' || mode === 'contentAndControl';
33
38
  }
39
+ /** Whether Word would record changes in this document: Track Changes on, or protected for tracked changes. */
40
+ export function documentTracksChanges(doc) {
41
+ const settings = doc.parts.settings ? doc.xmlSync(doc.parts.settings)?.root : undefined;
42
+ if (!settings)
43
+ return false;
44
+ const track = firstChild(settings, 'w:trackRevisions');
45
+ if (track && attr(track, 'w:val') !== 'false' && attr(track, 'w:val') !== '0')
46
+ return true;
47
+ const protection = firstChild(settings, 'w:documentProtection');
48
+ const enforced = attr(protection, 'w:enforcement');
49
+ return attr(protection, 'w:edit') === 'trackedChanges' && (enforced === '1' || enforced === 'true' || enforced === 'on');
50
+ }
34
51
  /** Every paragraph of a block list (including table cells), in document order. */
35
52
  export function paragraphsOf(blocks, out = []) {
36
53
  for (const b of blocks) {
@@ -43,7 +60,7 @@ export function paragraphsOf(blocks, out = []) {
43
60
  }
44
61
  return out;
45
62
  }
46
- export function paragraphText(para) {
63
+ export function paragraphText(para, options = {}) {
47
64
  let text = '';
48
65
  const segments = [];
49
66
  const add = (value, node) => {
@@ -57,9 +74,21 @@ export function paragraphText(para) {
57
74
  add('\t', inline.node);
58
75
  else if (inline.kind === 'break' && inline.type === 'line')
59
76
  add('\n', inline.node);
77
+ else if (options.objects && inline.kind === 'image' && !inline.float) {
78
+ // An inline picture or shape is one character (U+FFFC) the caret can step over and delete.
79
+ const node = objectNode(inline);
80
+ if (node)
81
+ add(OBJECT_CHAR, node);
82
+ }
60
83
  }
61
84
  return { paragraph: para.el, text, segments };
62
85
  }
86
+ /** Stands for an inline picture, shape or chart in `paragraphText(p, { objects: true })`. */
87
+ export const OBJECT_CHAR = '\ufffc';
88
+ /** The run child (w:drawing, w:pict, mc:AlternateContent) holding an inline object. */
89
+ export function objectNode(inline) {
90
+ return elements(inline.run).find((c) => c === inline.drawing || findAll(c, inline.drawing.name).includes(inline.drawing));
91
+ }
63
92
  /**
64
93
  * XML position of character offset `k` in a paragraph. With side 'start' the position is at the
65
94
  * start of the segment holding character k; with 'end' it is at the end of the segment holding
@@ -147,6 +176,8 @@ function endOfRun(run, fallback) {
147
176
  function newRun(text, template, format) {
148
177
  const rPr = template ? firstChild(template, 'w:rPr') : undefined;
149
178
  const run = el('w:r', {}, [...(rPr ? [structuredClone(rPr)] : []), ...runContent(text)]);
179
+ // A new run starts with no revision history of its own.
180
+ cleanRunProps(run);
150
181
  if (format)
151
182
  applyFormat(run, format);
152
183
  return run;
@@ -155,14 +186,129 @@ const BOOKMARK_NAME = /^[\p{L}_][\p{L}\p{N}_]{0,39}$/u;
155
186
  export class DocxEditor {
156
187
  doc;
157
188
  guard;
158
- constructor(doc, guard) {
189
+ trackOverride;
190
+ authorName;
191
+ /** The part being edited. */
192
+ part;
193
+ constructor(doc, guard, options = {}) {
159
194
  this.doc = doc;
160
195
  this.guard = guard;
196
+ this.trackOverride = options.trackChanges;
197
+ this.authorName = options.author;
198
+ this.part = options.part ?? doc.mainPart;
199
+ if (this.part !== doc.mainPart && !doc.xmlSync(this.part))
200
+ throw new EditError(`No part "${this.part}" to edit`);
201
+ }
202
+ /** Whether this editor works on a header, footer or notes part rather than the main document. */
203
+ get isStory() {
204
+ return this.part !== this.doc.mainPart;
205
+ }
206
+ // ---- tracked changes ----------------------------------------------------------------------
207
+ /** Whether edits are recorded as tracked changes (default: the document's Track Changes setting). */
208
+ get trackChanges() {
209
+ return this.trackOverride ?? documentTracksChanges(this.doc);
210
+ }
211
+ set trackChanges(on) {
212
+ this.trackOverride = on;
213
+ }
214
+ /** The author tracked changes are recorded under. */
215
+ get author() {
216
+ const user = this.guard?.user;
217
+ return this.authorName ?? user?.name ?? user?.id ?? 'docxkeun';
218
+ }
219
+ /** Revision stamp and id source for one edit, or undefined when not tracking. */
220
+ tracking() {
221
+ if (!this.trackChanges)
222
+ return undefined;
223
+ return { who: revisionStamp(this.author), nextId: nextRevisionId(this.root) };
224
+ }
225
+ /** Turn Word's own Track Changes setting (settings.xml w:trackRevisions) on or off. */
226
+ async setTrackChangesSetting(on) {
227
+ this.guard?.assert('edit');
228
+ const { name, xml } = await ensurePart(this.doc, 'settings');
229
+ removeChildren(xml.root, 'w:trackRevisions');
230
+ if (on)
231
+ insertOrdered(xml.root, el('w:trackRevisions'), SETTINGS_ORDER);
232
+ this.trackOverride = undefined;
233
+ this.doc.touch(name);
234
+ }
235
+ /** Tracked changes in the main document, in document order. */
236
+ revisions() {
237
+ return listRevisions(this.root);
238
+ }
239
+ /** Accept tracked changes (all, or those matching ids / author). Returns how many. */
240
+ acceptRevisions(filter) {
241
+ this.guard?.assert('review');
242
+ const n = acceptRevisions(this.root, filter);
243
+ if (n)
244
+ this.changed();
245
+ return n;
246
+ }
247
+ /** Reject tracked changes (all, or those matching ids / author). Returns how many. */
248
+ rejectRevisions(filter) {
249
+ this.guard?.assert('review');
250
+ const n = rejectRevisions(this.root, filter);
251
+ if (n)
252
+ this.changed();
253
+ return n;
254
+ }
255
+ /** The new run as it goes into the document: wrapped in a w:ins when tracking. */
256
+ placed(run, track) {
257
+ return track ? insertedRuns([run], track.nextId(), track.who) : run;
258
+ }
259
+ /** Whether a run sits in an insertion by the current author (edits to it need no new revision). */
260
+ inOwnInsertion(run, idx) {
261
+ const rev = runRevision(run, (n) => idx.parent.get(n));
262
+ return !!rev && (rev.name === 'w:ins' || rev.name === 'w:moveTo') && attr(rev, 'w:author') === this.author;
263
+ }
264
+ /**
265
+ * A sentinel inside someone else's w:ins cannot take a nested w:ins: split that insertion at the
266
+ * sentinel so the new one goes between its two halves.
267
+ */
268
+ liftOutOfInsertion(mark, idx) {
269
+ const container = idx.parent.get(mark);
270
+ if (!container || (container.name !== 'w:ins' && container.name !== 'w:moveTo'))
271
+ return;
272
+ const outer = idx.parentOf(container);
273
+ const at = container.children.indexOf(mark);
274
+ const tail = container.children.splice(at);
275
+ tail.shift();
276
+ const pos = outer.children.indexOf(container);
277
+ const pieces = [mark];
278
+ if (tail.some((n) => n.type === 'element'))
279
+ pieces.push(el(container.name, { ...container.attrs }, tail));
280
+ outer.children.splice(pos + 1, 0, ...pieces);
281
+ if (!container.children.some((n) => n.type === 'element'))
282
+ outer.children.splice(outer.children.indexOf(container), 1);
283
+ }
284
+ /** Mark the runs of a range as deleted (and the paragraph marks inside it), keeping the text. */
285
+ trackedCut(range, track) {
286
+ const index = this.index();
287
+ const { startMark, endMark } = isolate(index, range);
288
+ let idx = this.index();
289
+ const startCell = idx.ancestor(startMark, 'w:tc');
290
+ const endCell = idx.ancestor(endMark, 'w:tc');
291
+ if (startCell !== endCell) {
292
+ replaceMark(idx, startMark, []);
293
+ replaceMark(idx, endMark, []);
294
+ throw new EditError('The range crosses table cells');
295
+ }
296
+ const startPara = idx.ancestor(startMark, 'w:p');
297
+ const endPara = idx.ancestor(endMark, 'w:p');
298
+ const paragraphs = startPara === endPara ? [] : [startPara, ...between(idx, startMark, endMark, 'w:p').filter((p) => p !== endPara)];
299
+ for (const run of between(idx, startMark, endMark, 'w:r'))
300
+ deleteRun(run, (n) => idx.parent.get(n), track.nextId, track.who);
301
+ for (const p of paragraphs)
302
+ markParagraph(p, 'del', track.nextId(), track.who);
303
+ idx = this.index();
304
+ return { startMark, endMark, idx };
161
305
  }
162
306
  get root() {
163
- return this.doc.documentXml.root;
307
+ return this.isStory ? this.doc.xmlSync(this.part).root : this.doc.documentXml.root;
164
308
  }
165
309
  get body() {
310
+ if (this.isStory)
311
+ return this.root;
166
312
  const body = firstChild(this.root, 'w:body');
167
313
  if (!body)
168
314
  throw new EditError('document has no body');
@@ -171,11 +317,12 @@ export class DocxEditor {
171
317
  index() {
172
318
  return new TreeIndex(this.root);
173
319
  }
174
- changed(part = this.doc.mainPart) {
320
+ changed(part = this.part) {
175
321
  this.doc.touch(part);
176
322
  }
177
323
  check(action, range, detail) {
178
- this.guard?.assert(action, range, detail);
324
+ const tracked = this.trackChanges && (action === 'edit' || action === 'format' || action === 'fillForm');
325
+ this.guard?.assert(action, range, tracked ? { ...detail, tracked: true } : detail);
179
326
  if (range && (action === 'edit' || action === 'format' || action === 'link'))
180
327
  this.assertUnlocked(range);
181
328
  }
@@ -229,9 +376,18 @@ export class DocxEditor {
229
376
  rangeFromSelection(sel) {
230
377
  return { start: { node: sel.start.inline.node, offset: sel.start.offset }, end: { node: sel.end.inline.node, offset: sel.end.offset } };
231
378
  }
232
- /** Every paragraph of the body, including those in tables, in document order. */
379
+ /** Every paragraph of the story (the body by default), including those in tables, in document order. */
233
380
  paragraphs() {
234
- return paragraphsOf(this.doc.body().blocks);
381
+ if (!this.isStory)
382
+ return paragraphsOf(this.doc.body().blocks);
383
+ const root = this.root;
384
+ if (root.name === 'w:footnotes' || root.name === 'w:endnotes') {
385
+ // Separator notes (w:type) are not content.
386
+ return elements(root)
387
+ .filter((n) => !attr(n, 'w:type') || attr(n, 'w:type') === 'normal')
388
+ .flatMap((n) => paragraphsOf(this.doc.readBlocks(this.part, n)));
389
+ }
390
+ return paragraphsOf(this.doc.headerFooter(this.part).blocks);
235
391
  }
236
392
  /** Range covering a paragraph's text (undefined for paragraphs without text). */
237
393
  paragraphRange(paragraph) {
@@ -287,20 +443,22 @@ export class DocxEditor {
287
443
  */
288
444
  insertText(at, text, format) {
289
445
  const edge = this.bypassLocks ? undefined : this.lockEdge(at);
446
+ const track = this.tracking();
290
447
  if (edge) {
291
448
  // 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 });
449
+ this.guard?.assert('edit', { start: at, end: at }, track ? { tracked: true } : undefined);
293
450
  const idx = this.index();
294
451
  const run = newRun(text, idx.parentOf(at.node), format);
295
452
  const parent = idx.parentOf(edge.sdt);
296
- parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, run);
453
+ parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, this.placed(run, track));
297
454
  this.changed();
298
455
  return endOfRun(run, run);
299
456
  }
300
457
  this.check('edit', { start: at, end: at });
301
458
  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') {
459
+ // Typing into existing text: change the text node itself instead of adding a run per keystroke
460
+ // (when tracking, only inside the author's own insertion).
461
+ if (plain && at.node.name === 'w:t' && (!track || this.inOwnInsertion(this.index().parentOf(at.node), this.index()))) {
304
462
  const current = textContent(at.node);
305
463
  const offset = Math.max(0, Math.min(at.offset, current.length));
306
464
  const value = current.slice(0, offset) + text + current.slice(offset);
@@ -314,28 +472,366 @@ export class DocxEditor {
314
472
  // An empty paragraph: the new run takes the paragraph mark's formatting.
315
473
  const markRPr = firstChild(firstChild(at.node, 'w:pPr'), 'w:rPr');
316
474
  const run = el('w:r', {}, [...(markRPr ? [structuredClone(markRPr)] : []), ...runContent(text)]);
475
+ // The paragraph mark's own revision markers do not belong on a text run.
476
+ const runPr = firstChild(run, 'w:rPr');
477
+ if (runPr)
478
+ for (const n of ['w:ins', 'w:del', 'w:moveFrom', 'w:moveTo', 'w:rPrChange'])
479
+ removeChildren(runPr, n);
317
480
  if (format)
318
481
  applyFormat(run, format);
319
482
  const pPr = firstChild(at.node, 'w:pPr');
320
- at.node.children.splice(pPr ? at.node.children.indexOf(pPr) + 1 : 0, 0, run);
483
+ at.node.children.splice(pPr ? at.node.children.indexOf(pPr) + 1 : 0, 0, this.placed(run, track));
321
484
  this.changed();
322
485
  return endOfRun(run, at.node);
323
486
  }
324
487
  const index = this.index();
325
488
  const template = index.parentOf(at.node);
326
489
  const { startMark, endMark } = isolate(index, { start: at, end: at });
327
- const idx = this.index();
490
+ let idx = this.index();
328
491
  const run = newRun(text, template, format);
329
- replaceMark(idx, startMark, [run]);
330
492
  replaceMark(idx, endMark, []);
493
+ idx = this.index();
494
+ if (track && !this.inOwnInsertion(template, index))
495
+ this.liftOutOfInsertion(startMark, idx);
496
+ idx = this.index();
497
+ replaceMark(idx, startMark, [track && !this.inOwnInsertion(template, index) ? this.placed(run, track) : run]);
331
498
  this.changed();
332
499
  return endOfRun(run, run);
333
500
  }
501
+ /** Insert a run holding `content` (a drawing, a note reference) at a position; returns the run. */
502
+ insertRunContent(at, content, rPr) {
503
+ // Insert a placeholder character in a run of its own (a format forces a new run), then swap in the content.
504
+ const end = this.insertText(at, '\u2063', {});
505
+ const t = end.node;
506
+ const run = this.index().parentOf(t);
507
+ run.children.splice(run.children.indexOf(t), 1, ...content);
508
+ if (rPr) {
509
+ removeChildren(run, 'w:rPr');
510
+ run.children.unshift(rPr);
511
+ }
512
+ this.changed();
513
+ return run;
514
+ }
515
+ /**
516
+ * Insert a picture (PNG, JPEG, GIF, BMP, TIFF, EMF or WMF) inline at a position. Without a size it
517
+ * gets its natural size, shrunk to `maxWidth` (default 468pt, a Letter page's text width).
518
+ */
519
+ async insertImage(at, bytes, options = {}) {
520
+ this.check('edit', { start: at, end: at });
521
+ const info = imageInfo(bytes);
522
+ if (!info)
523
+ throw new EditError('Unsupported image: use PNG, JPEG, GIF, BMP, TIFF, EMF or WMF');
524
+ let { width, height } = options;
525
+ if (width === undefined && height === undefined) {
526
+ width = info.width;
527
+ height = info.height;
528
+ const max = options.maxWidth ?? 468;
529
+ if (width > max) {
530
+ height = (height * max) / width;
531
+ width = max;
532
+ }
533
+ }
534
+ else if (width === undefined)
535
+ width = (info.width * height) / info.height;
536
+ else if (height === undefined)
537
+ height = (info.height * width) / info.width;
538
+ const ext = info.kind === 'jpeg' ? 'jpeg' : info.kind;
539
+ let n = 1;
540
+ while (this.doc.pkg.has(`word/media/image${n}.${ext}`))
541
+ n++;
542
+ const part = `word/media/image${n}.${ext}`;
543
+ this.doc.pkg.setBytes(part, bytes, IMAGE_CONTENT_TYPES[ext]);
544
+ const rId = await this.doc.pkg.addRelationship(this.part, REL.image, part);
545
+ await this.doc.refreshRels(this.part);
546
+ // Drawing ids must be unique in the document.
547
+ let id = 0;
548
+ for (const root of [this.doc.documentXml.root, this.root])
549
+ for (const d of findAll(root, 'wp:docPr'))
550
+ id = Math.max(id, Number(attr(d, 'id') ?? 0));
551
+ id++;
552
+ const name = options.name ?? `Picture ${id}`;
553
+ const cx = String(Math.round(width * 12700));
554
+ const cy = String(Math.round(height * 12700));
555
+ if (this.root.attrs['xmlns:wp'] === undefined)
556
+ this.root.attrs['xmlns:wp'] = NS.wp;
557
+ if (this.root.attrs['xmlns:r'] === undefined)
558
+ this.root.attrs['xmlns:r'] = NS.r;
559
+ const docPr = { id: String(id), name };
560
+ if (options.alt)
561
+ docPr.descr = options.alt;
562
+ const drawing = el('w:drawing', {}, [
563
+ el('wp:inline', { distT: '0', distB: '0', distL: '0', distR: '0' }, [
564
+ el('wp:extent', { cx, cy }),
565
+ el('wp:effectExtent', { l: '0', t: '0', r: '0', b: '0' }),
566
+ el('wp:docPr', docPr),
567
+ el('wp:cNvGraphicFramePr', {}, [el('a:graphicFrameLocks', { 'xmlns:a': NS.a, noChangeAspect: '1' })]),
568
+ el('a:graphic', { 'xmlns:a': NS.a }, [
569
+ el('a:graphicData', { uri: 'http://schemas.openxmlformats.org/drawingml/2006/picture' }, [
570
+ el('pic:pic', { 'xmlns:pic': NS.pic }, [
571
+ el('pic:nvPicPr', {}, [el('pic:cNvPr', { id: '0', name }), el('pic:cNvPicPr')]),
572
+ el('pic:blipFill', {}, [el('a:blip', { 'r:embed': rId }), el('a:stretch', {}, [el('a:fillRect')])]),
573
+ el('pic:spPr', {}, [el('a:xfrm', {}, [el('a:off', { x: '0', y: '0' }), el('a:ext', { cx, cy })]), el('a:prstGeom', { prst: 'rect' }, [el('a:avLst')])]),
574
+ ]),
575
+ ]),
576
+ ]),
577
+ ]),
578
+ ]);
579
+ this.insertRunContent(at, [drawing]);
580
+ return drawing;
581
+ }
582
+ /** Add a footnote whose reference mark goes at a position. Returns the note's id. */
583
+ async addFootnote(at, text) {
584
+ this.check('edit', { start: at, end: at });
585
+ if (this.isStory)
586
+ throw new EditError('Footnotes can only be added to the main document');
587
+ let part = this.doc.parts.footnotes;
588
+ if (!part || !this.doc.xmlSync(part)) {
589
+ part = 'word/footnotes.xml';
590
+ for (let n = 2; this.doc.pkg.has(part); n++)
591
+ part = `word/footnotes${n}.xml`;
592
+ const separator = (type, id, mark) => el('w:footnote', { 'w:type': type, 'w:id': id }, [el('w:p', {}, [el('w:pPr', {}, [el('w:spacing', { 'w:after': '0', 'w:line': '240', 'w:lineRule': 'auto' })]), el('w:r', {}, [el(mark)])])]);
593
+ const xml = { declaration: null, prolog: [], epilog: [], root: el('w:footnotes', { ...ROOT_NAMESPACES }, [separator('separator', '-1', 'w:separator'), separator('continuationSeparator', '0', 'w:continuationSeparator')]) };
594
+ this.doc.pkg.setXml(part, xml, CONTENT_TYPE.footnotes);
595
+ await this.doc.pkg.addRelationship(this.doc.mainPart, REL.footnotes, part);
596
+ await this.doc.refreshRels(this.doc.mainPart);
597
+ this.doc.parts.footnotes = part;
598
+ }
599
+ const notes = this.doc.xmlSync(part).root;
600
+ const id = String(Math.max(0, ...elements(notes, 'w:footnote').map((n) => Number(attr(n, 'w:id') ?? 0))) + 1);
601
+ const styled = (styleId, fallback) => (this.doc.styles.get(styleId) ? [el('w:rStyle', { 'w:val': styleId })] : fallback);
602
+ const refPr = () => el('w:rPr', {}, styled('FootnoteReference', [el('w:vertAlign', { 'w:val': 'superscript' })]));
603
+ const pPr = this.doc.styles.get('FootnoteText') ? [el('w:pPr', {}, [el('w:pStyle', { 'w:val': 'FootnoteText' })])] : [el('w:pPr', {}, [el('w:spacing', { 'w:after': '0' })])];
604
+ const textPr = this.doc.styles.get('FootnoteText') ? [] : [el('w:rPr', {}, [el('w:sz', { 'w:val': '20' })])];
605
+ notes.children.push(el('w:footnote', { 'w:id': id }, [
606
+ el('w:p', {}, [...pPr, el('w:r', {}, [refPr(), el('w:footnoteRef')]), el('w:r', {}, [...textPr, ...runContent(` ${text}`)])]),
607
+ ]));
608
+ this.doc.touch(part);
609
+ this.insertRunContent(at, [el('w:footnoteReference', { 'w:id': id })], refPr());
610
+ return id;
611
+ }
612
+ // ---- headers and footers -----------------------------------------------------------------
613
+ /** Headers and footers by section and page type, with their text ({PAGE} for page fields). */
614
+ headersAndFooters() {
615
+ const sections = sectionProperties(this.mainBody());
616
+ const out = [];
617
+ sections.forEach((sp, i) => {
618
+ for (const kind of ['header', 'footer']) {
619
+ for (const ref of referencesOf(sp, kind)) {
620
+ const part = this.doc.headerFooterPart(attr(ref, 'r:id') ?? '');
621
+ if (!part)
622
+ continue;
623
+ const type = (attr(ref, 'w:type') ?? 'default');
624
+ const known = out.find((h) => h.part === part && h.type === type && h.kind === kind);
625
+ if (known)
626
+ known.sections.push(i + 1);
627
+ else
628
+ out.push({ kind, type, sections: [i + 1], part, text: headerText(this.doc.xmlSync(part)?.root ?? el('w:hdr')) });
629
+ }
630
+ }
631
+ });
632
+ return out;
633
+ }
634
+ /** Give the document's sections a header (see `setHeaderFooter`). Returns the part name. */
635
+ setHeader(text, options = {}) {
636
+ return this.setHeaderFooter('header', text, options);
637
+ }
638
+ /** Give the document's sections a footer (see `setHeaderFooter`). Returns the part name. */
639
+ setFooter(text, options = {}) {
640
+ return this.setHeaderFooter('footer', text, options);
641
+ }
642
+ /**
643
+ * Create or replace a header or footer. `text`: lines become paragraphs, tabs split it into
644
+ * left / centre / right parts, and {PAGE}, {NUMPAGES}, {SECTIONPAGES} become page number fields
645
+ * ("Page {PAGE} of {NUMPAGES}"). Every section by default, or one (`section`, from 1); all pages,
646
+ * the first page or even pages (`type`). A part used only by these sections is rewritten in place,
647
+ * otherwise a new part is made, so other sections keep theirs. With Track Changes on, the text
648
+ * changes are recorded.
649
+ */
650
+ async setHeaderFooter(kind, text, options = {}) {
651
+ if (this.isStory)
652
+ throw new EditError('Headers and footers are set from an editor of the main document');
653
+ this.check('edit');
654
+ const type = options.type ?? 'default';
655
+ const body = this.mainBody();
656
+ let sections = sectionProperties(body);
657
+ if (!sections.length) {
658
+ body.children.push(el('w:sectPr', {}, [el('w:pgSz', { 'w:w': '12240', 'w:h': '15840' }), el('w:pgMar', { 'w:top': '1440', 'w:right': '1440', 'w:bottom': '1440', 'w:left': '1440', 'w:header': '720', 'w:footer': '720', 'w:gutter': '0' })]));
659
+ sections = sectionProperties(body);
660
+ }
661
+ const targets = this.sectionTargets(sections, options.section);
662
+ const refOf = (sp) => referencesOf(sp, kind).find((r) => (attr(r, 'w:type') ?? 'default') === type);
663
+ const partOf = (r) => (r ? this.doc.headerFooterPart(attr(r, 'r:id') ?? '') : undefined);
664
+ // Rewrite in place only when the targets share one part that nothing else uses.
665
+ const current = targets.map((sp) => partOf(refOf(sp)));
666
+ const shared = current[0] && current.every((p) => p === current[0]) ? current[0] : undefined;
667
+ const usedElsewhere = shared &&
668
+ sections.some((sp) => {
669
+ const refs = [...referencesOf(sp, 'header'), ...referencesOf(sp, 'footer')];
670
+ return refs.some((r) => partOf(r) === shared && (!targets.includes(sp) || r.name !== (kind === 'header' ? 'w:headerReference' : 'w:footerReference') || (attr(r, 'w:type') ?? 'default') !== type));
671
+ });
672
+ const paragraphs = headerParagraphs(this.doc, kind, text, options.align, textWidth(targets[0]));
673
+ const track = this.tracking();
674
+ if (track) {
675
+ for (const p of paragraphs) {
676
+ const pPr = firstChild(p, 'w:pPr');
677
+ const content = p.children.filter((c) => c.type === 'element' && c !== pPr);
678
+ p.children = [...(pPr ? [pPr] : []), ...(content.length ? [el('w:ins', insertedRuns([], track.nextId(), track.who).attrs, content)] : [])];
679
+ markParagraph(p, 'ins', track.nextId(), track.who);
680
+ }
681
+ }
682
+ let part;
683
+ if (shared && !usedElsewhere && this.doc.xmlSync(shared)) {
684
+ part = shared;
685
+ const root = this.doc.xmlSync(part).root;
686
+ if (track) {
687
+ // The old text stays, marked deleted.
688
+ const idx = new TreeIndex(root);
689
+ for (const run of findAll(root, 'w:r'))
690
+ deleteRun(run, (n) => idx.parent.get(n), track.nextId, track.who);
691
+ for (const p of findAll(root, 'w:p'))
692
+ markParagraph(p, 'del', track.nextId(), track.who);
693
+ root.children.push(...paragraphs);
694
+ }
695
+ else
696
+ root.children = paragraphs;
697
+ }
698
+ else {
699
+ let n = 1;
700
+ while (this.doc.pkg.has(`word/${kind}${n}.xml`))
701
+ n++;
702
+ part = `word/${kind}${n}.xml`;
703
+ const root = el(kind === 'header' ? 'w:hdr' : 'w:ftr', { ...ROOT_NAMESPACES }, paragraphs);
704
+ this.doc.pkg.setXml(part, { declaration: null, prolog: [], root, epilog: [] }, CONTENT_TYPE[kind]);
705
+ const rId = await this.doc.pkg.addRelationship(this.doc.mainPart, REL[kind], part);
706
+ await this.doc.refreshRels(this.doc.mainPart);
707
+ await this.doc.refreshRels(part);
708
+ for (const sp of targets) {
709
+ const ref = refOf(sp);
710
+ if (ref)
711
+ ref.attrs['r:id'] = rId;
712
+ else
713
+ insertOrdered(sp, el(kind === 'header' ? 'w:headerReference' : 'w:footerReference', { 'w:type': type, 'r:id': rId }), SECTPR_ORDER);
714
+ }
715
+ if (!this.root.attrs['xmlns:r'])
716
+ this.root.attrs['xmlns:r'] = NS.r;
717
+ await this.dropUnusedParts(current.filter((p) => !!p));
718
+ }
719
+ if (type === 'first')
720
+ for (const sp of targets)
721
+ if (!firstChild(sp, 'w:titlePg'))
722
+ insertOrdered(sp, el('w:titlePg'), SECTPR_ORDER);
723
+ if (type === 'even')
724
+ await this.setEvenAndOdd(true);
725
+ this.doc.touch(part);
726
+ this.changed();
727
+ return part;
728
+ }
729
+ /** Remove headers (see `removeHeaderFooter`). Returns how many references were removed. */
730
+ removeHeader(options = {}) {
731
+ return this.removeHeaderFooter('header', options);
732
+ }
733
+ /** Remove footers (see `removeHeaderFooter`). Returns how many references were removed. */
734
+ removeFooter(options = {}) {
735
+ return this.removeHeaderFooter('footer', options);
736
+ }
737
+ /**
738
+ * Remove headers or footers: of every type unless `type` says which, from every section unless
739
+ * `section` says which (a later section without its own then shows the previous section's). Parts
740
+ * nothing uses any more are deleted. Not recorded as a tracked change.
741
+ */
742
+ async removeHeaderFooter(kind, options = {}) {
743
+ if (this.isStory)
744
+ throw new EditError('Headers and footers are removed from an editor of the main document');
745
+ this.guard?.assert('edit');
746
+ const type = options.type ?? 'all';
747
+ const sections = sectionProperties(this.mainBody());
748
+ const targets = this.sectionTargets(sections, options.section);
749
+ const removed = [];
750
+ let count = 0;
751
+ let firstGone = false;
752
+ let evenGone = false;
753
+ for (const sp of targets) {
754
+ for (const ref of referencesOf(sp, kind)) {
755
+ const t = attr(ref, 'w:type') ?? 'default';
756
+ if (type !== 'all' && t !== type)
757
+ continue;
758
+ sp.children.splice(sp.children.indexOf(ref), 1);
759
+ const part = this.doc.headerFooterPart(attr(ref, 'r:id') ?? '');
760
+ if (part)
761
+ removed.push(part);
762
+ if (t === 'first')
763
+ firstGone = true;
764
+ if (t === 'even')
765
+ evenGone = true;
766
+ count++;
767
+ }
768
+ if (firstGone && !hasFirstPage(sp))
769
+ removeChildren(sp, 'w:titlePg');
770
+ }
771
+ if (!count)
772
+ return 0;
773
+ if (evenGone && !hasEvenPages(sections))
774
+ await this.setEvenAndOdd(false);
775
+ await this.dropUnusedParts(removed);
776
+ this.changed();
777
+ return count;
778
+ }
779
+ mainBody() {
780
+ const body = firstChild(this.doc.documentXml.root, 'w:body');
781
+ if (!body)
782
+ throw new EditError('document has no body');
783
+ return body;
784
+ }
785
+ sectionTargets(sections, section) {
786
+ if (section === undefined)
787
+ return sections;
788
+ const sp = sections[section - 1];
789
+ if (!sp)
790
+ throw new EditError(`There is no section ${section}; the document has ${sections.length}`);
791
+ return [sp];
792
+ }
793
+ /** Delete header/footer parts (and their relationships) that no section refers to any more. */
794
+ async dropUnusedParts(parts) {
795
+ const sections = sectionProperties(this.mainBody());
796
+ const inUse = new Set();
797
+ for (const sp of sections)
798
+ for (const r of [...referencesOf(sp, 'header'), ...referencesOf(sp, 'footer')])
799
+ inUse.add(attr(r, 'r:id') ?? '');
800
+ for (const part of new Set(parts)) {
801
+ const rels = [...this.doc.rels(this.doc.mainPart)].filter(([, rel]) => rel.target === part);
802
+ if (rels.some(([id]) => inUse.has(id)))
803
+ continue;
804
+ for (const [id] of rels)
805
+ await this.doc.pkg.removeRelationship(this.doc.mainPart, id);
806
+ if (this.doc.pkg.has(part))
807
+ this.doc.pkg.removePart(part);
808
+ }
809
+ await this.doc.refreshRels(this.doc.mainPart);
810
+ }
811
+ async setEvenAndOdd(on) {
812
+ const { name, xml } = await ensurePart(this.doc, 'settings');
813
+ const has = !!firstChild(xml.root, 'w:evenAndOddHeaders');
814
+ if (on === has)
815
+ return;
816
+ if (on)
817
+ insertOrdered(xml.root, el('w:evenAndOddHeaders'), SETTINGS_ORDER);
818
+ else
819
+ removeChildren(xml.root, 'w:evenAndOddHeaders');
820
+ this.doc.touch(name);
821
+ }
334
822
  /** Join a paragraph with the one right after it (Backspace at the start of the second). */
335
823
  mergeParagraphs(first, second) {
336
824
  const firstRange = this.paragraphRange(first);
337
825
  const secondRange = this.paragraphRange(second);
338
826
  this.check('edit', { start: firstRange?.end ?? { node: first, offset: 0 }, end: secondRange?.start ?? { node: second, offset: 0 } });
827
+ const track = this.tracking();
828
+ const mark = paragraphMarkRevision(first);
829
+ if (track && !(mark?.kind === 'ins' && attr(mark.el, 'w:author') === this.author)) {
830
+ // Deleting a paragraph mark is recorded; the paragraphs join when the change is accepted.
831
+ markParagraph(first, 'del', track.nextId(), track.who);
832
+ this.changed();
833
+ return;
834
+ }
339
835
  const idx = this.index();
340
836
  const parent = idx.parentOf(first);
341
837
  if (idx.parentOf(second) !== parent)
@@ -427,6 +923,16 @@ export class DocxEditor {
427
923
  const newPara = el('w:p', {}, [...(newPPr ? [newPPr] : []), ...tail]);
428
924
  const parent = idx.parentOf(para);
429
925
  parent.children.splice(indexOfChild(parent, para) + 1, 0, newPara);
926
+ const track = this.tracking();
927
+ // Enter inserts a paragraph mark: the first half's mark is the new one.
928
+ if (track) {
929
+ const newPr = firstChild(newPara, 'w:pPr');
930
+ const newMark = firstChild(newPr, 'w:rPr');
931
+ if (newMark)
932
+ for (const n of ['w:ins', 'w:del'])
933
+ removeChildren(newMark, n);
934
+ markParagraph(para, 'ins', track.nextId(), track.who);
935
+ }
430
936
  this.changed();
431
937
  return newPara;
432
938
  }
@@ -436,13 +942,21 @@ export class DocxEditor {
436
942
  this.check('edit', range);
437
943
  const runs = elements(paragraph, 'w:r');
438
944
  const run = newRun(text, runs[runs.length - 1], format);
439
- paragraph.children.push(run);
945
+ paragraph.children.push(this.placed(run, this.tracking()));
440
946
  this.changed();
441
947
  return run;
442
948
  }
443
949
  /** Delete a range (it may span paragraphs, but not table cells). */
444
950
  deleteRange(range) {
445
951
  this.check('edit', range);
952
+ const track = this.tracking();
953
+ if (track) {
954
+ const { startMark, endMark, idx } = this.trackedCut(range, track);
955
+ replaceMark(idx, startMark, []);
956
+ replaceMark(this.index(), endMark, []);
957
+ this.changed();
958
+ return;
959
+ }
446
960
  // Deleting inside one text node (backspace): edit it in place.
447
961
  if (range.start.node === range.end.node && range.start.node.name === 'w:t') {
448
962
  const current = textContent(range.start.node);
@@ -460,6 +974,16 @@ export class DocxEditor {
460
974
  this.check('edit', range);
461
975
  const index = this.index();
462
976
  const template = index.parentOf(range.start.node);
977
+ const track = this.tracking();
978
+ if (track) {
979
+ // The old text stays as a deletion; the new text follows it as an insertion.
980
+ const { startMark, endMark } = this.trackedCut(range, track);
981
+ replaceMark(this.index(), startMark, []);
982
+ this.liftOutOfInsertion(endMark, this.index());
983
+ replaceMark(this.index(), endMark, text || format ? [this.placed(newRun(text, template, format), track)] : []);
984
+ this.changed();
985
+ return;
986
+ }
463
987
  const { startMark, endMark, idx } = this.cut(range);
464
988
  replaceMark(idx, startMark, text || format ? [newRun(text, template, format)] : []);
465
989
  replaceMark(idx, endMark, []);
@@ -550,8 +1074,34 @@ export class DocxEditor {
550
1074
  const index = this.index();
551
1075
  const { startMark, endMark } = isolate(index, range);
552
1076
  const idx = this.index();
553
- for (const run of between(idx, startMark, endMark, 'w:r'))
1077
+ const track = this.tracking();
1078
+ for (const run of between(idx, startMark, endMark, 'w:r')) {
1079
+ if (track && !this.inOwnInsertion(run, idx))
1080
+ recordRunFormat(run, track.nextId(), track.who);
554
1081
  applyFormat(run, format);
1082
+ }
1083
+ replaceMark(idx, startMark, []);
1084
+ replaceMark(idx, endMark, []);
1085
+ this.changed();
1086
+ }
1087
+ /** Remove direct character formatting (and character styles, except Hyperlink) from a range. */
1088
+ clearFormatting(range) {
1089
+ this.check('format', range);
1090
+ const index = this.index();
1091
+ const { startMark, endMark } = isolate(index, range);
1092
+ const idx = this.index();
1093
+ const track = this.tracking();
1094
+ for (const run of between(idx, startMark, endMark, 'w:r')) {
1095
+ if (track && !this.inOwnInsertion(run, idx))
1096
+ recordRunFormat(run, track.nextId(), track.who);
1097
+ const rPr = firstChild(run, 'w:rPr');
1098
+ if (!rPr)
1099
+ continue;
1100
+ const keep = rPr.children.filter((c) => c.type === 'element' && ((c.name === 'w:rStyle' && attr(c, 'w:val') === 'Hyperlink') || c.name === 'w:rPrChange'));
1101
+ rPr.children = keep;
1102
+ if (!keep.length)
1103
+ run.children.splice(run.children.indexOf(rPr), 1);
1104
+ }
555
1105
  replaceMark(idx, startMark, []);
556
1106
  replaceMark(idx, endMark, []);
557
1107
  this.changed();
@@ -607,7 +1157,10 @@ export class DocxEditor {
607
1157
  const ref = typeof where === 'object' ? (where.before ?? where.after) : undefined;
608
1158
  this.check('edit', ref ? { start: { node: ref, offset: 0 }, end: { node: ref, offset: 0 } } : undefined);
609
1159
  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)] : [])]);
1160
+ const track = this.tracking();
1161
+ const para = el('w:p', {}, [...pPr, ...(text ? [this.placed(newRun(text, undefined, options.format), track)] : [])]);
1162
+ if (track)
1163
+ markParagraph(para, 'ins', track.nextId(), track.who);
611
1164
  const body = this.body;
612
1165
  if (where === 'start')
613
1166
  body.children.unshift(para);
@@ -628,6 +1181,18 @@ export class DocxEditor {
628
1181
  }
629
1182
  deleteParagraph(paragraph) {
630
1183
  this.check('edit', this.paragraphRange(paragraph) ?? { start: { node: paragraph, offset: 0 }, end: { node: paragraph, offset: 0 } });
1184
+ const track = this.tracking();
1185
+ const mark = paragraphMarkRevision(paragraph);
1186
+ const ownNew = mark?.kind === 'ins' && attr(mark.el, 'w:author') === this.author;
1187
+ if (track && !ownNew) {
1188
+ // The text is marked deleted and so is the paragraph mark; Word joins them away on accept.
1189
+ const tidx = this.index();
1190
+ for (const run of findAll(paragraph, 'w:r'))
1191
+ deleteRun(run, (n) => tidx.parent.get(n), track.nextId, track.who);
1192
+ markParagraph(paragraph, 'del', track.nextId(), track.who);
1193
+ this.changed();
1194
+ return;
1195
+ }
631
1196
  const idx = this.index();
632
1197
  const parent = idx.parentOf(paragraph);
633
1198
  // A table cell must keep at least one paragraph.
@@ -640,6 +1205,9 @@ export class DocxEditor {
640
1205
  }
641
1206
  setParagraphStyle(paragraph, styleId) {
642
1207
  this.check('format', this.paragraphRange(paragraph));
1208
+ const track = this.tracking();
1209
+ if (track)
1210
+ recordParagraphFormat(paragraph, track.nextId(), track.who, PPR_ORDER);
643
1211
  const pPr = ensureChild(paragraph, 'w:pPr');
644
1212
  if (paragraph.children[0] !== pPr) {
645
1213
  paragraph.children.splice(paragraph.children.indexOf(pPr), 1);
@@ -649,6 +1217,177 @@ export class DocxEditor {
649
1217
  insertOrdered(pPr, el('w:pStyle', { 'w:val': styleId }), PPR_ORDER);
650
1218
  this.changed();
651
1219
  }
1220
+ /** Change paragraph formatting: alignment, direction, indents, spacing and keep rules. */
1221
+ formatParagraph(paragraph, format) {
1222
+ this.check('format', this.paragraphRange(paragraph));
1223
+ const track = this.tracking();
1224
+ if (track)
1225
+ recordParagraphFormat(paragraph, track.nextId(), track.who, PPR_ORDER);
1226
+ const pPr = ensureChild(paragraph, 'w:pPr');
1227
+ if (paragraph.children[0] !== pPr) {
1228
+ paragraph.children.splice(paragraph.children.indexOf(pPr), 1);
1229
+ paragraph.children.unshift(pPr);
1230
+ }
1231
+ const twips = (pt) => String(Math.round(pt * 20));
1232
+ const onOff = (name, on) => {
1233
+ if (on === undefined)
1234
+ return;
1235
+ removeChildren(pPr, name);
1236
+ insertOrdered(pPr, on ? el(name) : el(name, { 'w:val': '0' }), PPR_ORDER);
1237
+ };
1238
+ onOff('w:keepNext', format.keepWithNext);
1239
+ onOff('w:keepLines', format.keepLinesTogether);
1240
+ onOff('w:pageBreakBefore', format.pageBreakBefore);
1241
+ if (format.direction)
1242
+ onOff('w:bidi', format.direction === 'rtl');
1243
+ if (format.align) {
1244
+ removeChildren(pPr, 'w:jc');
1245
+ // In a right-to-left paragraph Word reads left and right as start and end, so a visually
1246
+ // right-aligned RTL paragraph is stored as "left".
1247
+ const bidi = firstChild(pPr, 'w:bidi');
1248
+ const rtl = !!bidi && attr(bidi, 'w:val') !== '0' && attr(bidi, 'w:val') !== 'false';
1249
+ const visual = format.align === 'justify' ? 'both' : format.align;
1250
+ const jc = rtl && visual === 'left' ? 'right' : rtl && visual === 'right' ? 'left' : visual;
1251
+ insertOrdered(pPr, el('w:jc', { 'w:val': jc }), PPR_ORDER);
1252
+ }
1253
+ if (format.indentLeft !== undefined || format.indentRight !== undefined || format.indentFirstLine !== undefined) {
1254
+ const ind = ensureOrdered(pPr, 'w:ind', PPR_ORDER);
1255
+ if (format.indentLeft !== undefined) {
1256
+ delete ind.attrs['w:start'];
1257
+ ind.attrs['w:left'] = twips(format.indentLeft);
1258
+ }
1259
+ if (format.indentRight !== undefined) {
1260
+ delete ind.attrs['w:end'];
1261
+ ind.attrs['w:right'] = twips(format.indentRight);
1262
+ }
1263
+ if (format.indentFirstLine !== undefined) {
1264
+ delete ind.attrs['w:firstLine'];
1265
+ delete ind.attrs['w:hanging'];
1266
+ if (format.indentFirstLine >= 0)
1267
+ ind.attrs['w:firstLine'] = twips(format.indentFirstLine);
1268
+ else
1269
+ ind.attrs['w:hanging'] = twips(-format.indentFirstLine);
1270
+ }
1271
+ }
1272
+ if (format.spaceBefore !== undefined || format.spaceAfter !== undefined || format.lineSpacing !== undefined) {
1273
+ const sp = ensureOrdered(pPr, 'w:spacing', PPR_ORDER);
1274
+ if (format.spaceBefore !== undefined) {
1275
+ delete sp.attrs['w:beforeAutospacing'];
1276
+ sp.attrs['w:before'] = twips(format.spaceBefore);
1277
+ }
1278
+ if (format.spaceAfter !== undefined) {
1279
+ delete sp.attrs['w:afterAutospacing'];
1280
+ sp.attrs['w:after'] = twips(format.spaceAfter);
1281
+ }
1282
+ if (format.lineSpacing !== undefined) {
1283
+ sp.attrs['w:line'] = String(Math.round(format.lineSpacing * 240));
1284
+ sp.attrs['w:lineRule'] = 'auto';
1285
+ }
1286
+ }
1287
+ this.changed();
1288
+ }
1289
+ // ---- lists --------------------------------------------------------------------------------
1290
+ /** The list paragraphs of the body with their labels ("1.", "a)", "•"), keyed by w:p. */
1291
+ listItems() {
1292
+ return listItems(this.doc, this.paragraphs());
1293
+ }
1294
+ /**
1295
+ * Change list formatting of paragraphs:
1296
+ * - `format`: make them one list in that format ('bullet', 'decimal' 1., 'decimalParen' 1),
1297
+ * 'lowerLetter' a., 'upperLetter' A., 'lowerRoman' i., 'upperRoman' I.), numbered from `start`
1298
+ * (default 1). Paragraphs already in a list keep its indentation and their level. 'none' takes
1299
+ * them out of their list.
1300
+ * - `start` alone: restart the numbering, keeping the format.
1301
+ * - `level` (0–8): the list level (indent); alone, only the level changes.
1302
+ * - `sameListAs`: join the list of that paragraph, continuing its numbering.
1303
+ * Returns the numId the paragraphs now use (undefined after 'none').
1304
+ */
1305
+ async setList(paragraphs, options) {
1306
+ const { format, level, start, sameListAs } = options;
1307
+ if (paragraphs.length === 0)
1308
+ throw new EditError('setList needs at least one paragraph');
1309
+ if (level !== undefined && (!Number.isInteger(level) || level < 0 || level > 8))
1310
+ throw new EditError('List levels go from 0 to 8');
1311
+ if (start !== undefined && (!Number.isInteger(start) || start < 0 || start > 32767))
1312
+ throw new EditError('start must be a whole number from 0 to 32767');
1313
+ const all = new Map(this.paragraphs().map((p) => [p.el, p]));
1314
+ const paras = paragraphs.map((el) => {
1315
+ const p = all.get(el);
1316
+ if (!p)
1317
+ throw new EditError('setList only works on paragraphs of the document body');
1318
+ return p;
1319
+ });
1320
+ for (const p of paras)
1321
+ this.check('format', this.paragraphRange(p) ?? { start: { node: p.el, offset: 0 }, end: { node: p.el, offset: 0 } });
1322
+ if (format === 'none') {
1323
+ if (sameListAs || start !== undefined || level !== undefined)
1324
+ throw new EditError("format 'none' cannot be combined with other list options");
1325
+ for (const p of paras)
1326
+ this.writeNumPr(p, undefined);
1327
+ this.changed();
1328
+ return undefined;
1329
+ }
1330
+ if (sameListAs) {
1331
+ if (format !== undefined || start !== undefined)
1332
+ throw new EditError('sameListAs cannot be combined with format or start');
1333
+ const target = all.get(sameListAs)?.numbering;
1334
+ if (!target)
1335
+ throw new EditError('The paragraph to join is not in a list');
1336
+ for (const p of paras)
1337
+ this.writeNumPr(p, { numId: target.numId, ilvl: level ?? (p.numbering ? p.numbering.ilvl : target.ilvl) });
1338
+ this.changed();
1339
+ return target.numId;
1340
+ }
1341
+ const first = paras.find((p) => p.numbering)?.numbering;
1342
+ if (format === undefined) {
1343
+ if (!first)
1344
+ throw new EditError('These paragraphs are not in a list; pass a format to make them one');
1345
+ if (start === undefined) {
1346
+ if (level === undefined)
1347
+ throw new EditError('Nothing to change: pass format, level, start or sameListAs');
1348
+ for (const p of paras) {
1349
+ if (!p.numbering)
1350
+ throw new EditError('Some of these paragraphs are not in a list; pass a format to make them one');
1351
+ this.writeNumPr(p, { numId: p.numbering.numId, ilvl: level });
1352
+ }
1353
+ this.changed();
1354
+ return first.numId;
1355
+ }
1356
+ }
1357
+ const ilvlOf = (p) => level ?? p.numbering?.ilvl ?? 0;
1358
+ const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
1359
+ const base = first ? { numId: first.numId, abstractId: this.doc.numbering.abstractFor(first.numId, styleNumId)?.id } : undefined;
1360
+ const numId = await createList(this.doc, {
1361
+ format: format ?? 'keep',
1362
+ levels: new Set(paras.map(ilvlOf)),
1363
+ ...(start !== undefined ? { start } : {}),
1364
+ ...(base ? { base } : {}),
1365
+ });
1366
+ for (const p of paras)
1367
+ this.writeNumPr(p, { numId, ilvl: ilvlOf(p) });
1368
+ this.changed();
1369
+ return numId;
1370
+ }
1371
+ /** Set or clear a paragraph's w:numPr (clearing style-given numbering with numId 0). */
1372
+ writeNumPr(para, num) {
1373
+ const p = para.el;
1374
+ const track = this.tracking();
1375
+ if (track)
1376
+ recordParagraphFormat(p, track.nextId(), track.who, PPR_ORDER);
1377
+ const pPr = ensureChild(p, 'w:pPr');
1378
+ if (p.children[0] !== pPr) {
1379
+ p.children.splice(p.children.indexOf(pPr), 1);
1380
+ p.children.unshift(pPr);
1381
+ }
1382
+ removeChildren(pPr, 'w:numPr');
1383
+ if (num) {
1384
+ insertOrdered(pPr, el('w:numPr', {}, [el('w:ilvl', { 'w:val': String(num.ilvl) }), el('w:numId', { 'w:val': num.numId })]), PPR_ORDER);
1385
+ return;
1386
+ }
1387
+ const styleNum = para.styleId ? this.doc.styles.get(para.styleId)?.pPr.numId : undefined;
1388
+ if (styleNum && styleNum !== '0')
1389
+ insertOrdered(pPr, el('w:numPr', {}, [el('w:numId', { 'w:val': '0' })]), PPR_ORDER);
1390
+ }
652
1391
  // ---- hyperlinks and bookmarks -------------------------------------------------------------
653
1392
  /** Turn a range (within one paragraph) into a hyperlink to a URL or a bookmark. */
654
1393
  async addHyperlink(range, target, tooltip) {
@@ -657,8 +1396,8 @@ export class DocxEditor {
657
1396
  throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
658
1397
  const attrs = {};
659
1398
  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);
1399
+ attrs['r:id'] = await this.doc.pkg.addRelationship(this.part, REL.hyperlink, target.url, true);
1400
+ await this.doc.refreshRels(this.part);
662
1401
  }
663
1402
  else
664
1403
  attrs['w:anchor'] = target.bookmark;
@@ -688,8 +1427,49 @@ export class DocxEditor {
688
1427
  this.changed();
689
1428
  return link;
690
1429
  }
1430
+ /** Point an existing w:hyperlink at another URL or a bookmark (same scheme rules as `addHyperlink`). */
1431
+ async setHyperlinkTarget(hyperlink, target) {
1432
+ this.check('link');
1433
+ if ('url' in target && !/^(https?|mailto|tel|ftp):/i.test(target.url))
1434
+ throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
1435
+ const old = hyperlink.attrs['r:id'];
1436
+ if ('url' in target) {
1437
+ hyperlink.attrs['r:id'] = await this.doc.pkg.addRelationship(this.part, REL.hyperlink, target.url, true);
1438
+ delete hyperlink.attrs['w:anchor'];
1439
+ if (!this.root.attrs['xmlns:r'])
1440
+ this.root.attrs['xmlns:r'] = NS.r;
1441
+ }
1442
+ else {
1443
+ hyperlink.attrs['w:anchor'] = target.bookmark;
1444
+ delete hyperlink.attrs['r:id'];
1445
+ }
1446
+ // The old tooltip described the old target.
1447
+ delete hyperlink.attrs['w:tooltip'];
1448
+ delete hyperlink.attrs['w:docLocation'];
1449
+ await this.dropHyperlinkRel(old);
1450
+ this.changed();
1451
+ }
1452
+ /** Remove a hyperlink relationship that nothing in this part refers to any more. */
1453
+ async dropHyperlinkRel(id) {
1454
+ if (id) {
1455
+ const used = findAll(this.root, 'w:hyperlink').some((h) => h.attrs['r:id'] === id);
1456
+ const rel = this.doc.rels(this.part).get(id);
1457
+ if (!used && rel && rel.external)
1458
+ await this.doc.pkg.removeRelationship(this.part, id);
1459
+ }
1460
+ await this.doc.refreshRels(this.part);
1461
+ }
1462
+ /** Set the alt text (wp:docPr/@descr) of a picture or drawing. */
1463
+ setImageAlt(drawing, text) {
1464
+ this.check('edit');
1465
+ const props = drawing.name === 'wp:docPr' ? drawing : findAll(drawing, 'wp:docPr')[0];
1466
+ if (!props)
1467
+ throw new EditError('This object has no description to edit');
1468
+ props.attrs['descr'] = text;
1469
+ this.changed();
1470
+ }
691
1471
  /** Unwrap a w:hyperlink, keeping its text. */
692
- removeHyperlink(link) {
1472
+ async removeHyperlink(link) {
693
1473
  this.check('link');
694
1474
  const idx = this.index();
695
1475
  const parent = idx.parentOf(link);
@@ -702,10 +1482,11 @@ export class DocxEditor {
702
1482
  }
703
1483
  parent.children.splice(indexOfChild(parent, link), 1, ...runs);
704
1484
  this.changed();
1485
+ await this.dropHyperlinkRel(attr(link, 'r:id'));
705
1486
  }
706
1487
  /** Every w:hyperlink in the body with its target. */
707
1488
  hyperlinks() {
708
- const rels = this.doc.rels(this.doc.mainPart);
1489
+ const rels = this.doc.rels(this.part);
709
1490
  return findAll(this.body, 'w:hyperlink').map((h) => {
710
1491
  const rId = attr(h, 'r:id');
711
1492
  return { el: h, url: rId ? rels.get(rId)?.target : undefined, anchor: attr(h, 'w:anchor'), tooltip: attr(h, 'w:tooltip'), text: textContent(h) };
@@ -1119,3 +1900,12 @@ function localDate(d) {
1119
1900
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}Z`;
1120
1901
  }
1121
1902
  export { EditError };
1903
+ /** The child `name` of `parent`, created in schema order when missing. */
1904
+ function ensureOrdered(parent, name, order) {
1905
+ const existing = firstChild(parent, name);
1906
+ if (existing)
1907
+ return existing;
1908
+ const node = el(name);
1909
+ insertOrdered(parent, node, order);
1910
+ return node;
1911
+ }