docxkeun 0.3.0 → 0.4.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.
@@ -4,6 +4,8 @@
4
4
  * notifies listeners such as the viewer.
5
5
  */
6
6
  import { CONTENT_TYPE, IMAGE_CONTENT_TYPES, REL } from '../opc/index.js';
7
+ import { newChartSpace, patchChartSpace, readChartTable, validateChartData } from '../charts/write.js';
8
+ import { isWorkbook, workbookFor, workbookHasMore } from '../charts/workbook.js';
7
9
  import { imageInfo } from '../images/size.js';
8
10
  import { hasEvenPages, hasFirstPage, headerParagraphs, headerText, referencesOf, sectionProperties, SECTPR_ORDER, textWidth } from './headers.js';
9
11
  import { attr, el, elements, ensureChild, findAll, firstChild, insertOrdered, NS, removeChildren, textContent } from '../xml/index.js';
@@ -13,6 +15,7 @@ import { cloneElement } from '../xml/index.js';
13
15
  import { acceptRevisions, cleanRunProps, deleteRun, insertedRuns, listRevisions, markParagraph, nextRevisionId, paragraphMarkRevision, recordParagraphFormat, recordRunFormat, rejectRevisions, revisionStamp, runRevision, } from './revisions.js';
14
16
  import { SETTINGS_ORDER } from '../security/protection.js';
15
17
  import { ensureNamespaces, ensurePart, randomHexId, ROOT_NAMESPACES } from './parts.js';
18
+ import { addWorkbook, anchorFrame, chartData, chartGraphic, chartKind, chartOf, chartSize, checkPlacement, checkShape, cloneObject, copyPart, dropFallback, frameOf, freePartName, inlineFrame, inTextBox, isPicture, listObjects, nextRelativeHeight, placeFrame, replaceWorkbook, resized, resizeFrame, sectionAt, SHAPE_NAMES, shapeGraphic, takeOut, } from './objects.js';
16
19
  import { between, EditError, indexOfChild, isolate, PPR_ORDER, replaceMark, RPR_ORDER, textNode, TreeIndex, } from './positions.js';
17
20
  const LOCK_VALUES = { content: 'contentLocked', contentAndControl: 'sdtContentLocked', control: 'sdtLocked' };
18
21
  const LOCK_MODES = { contentLocked: 'content', sdtContentLocked: 'contentAndControl', sdtLocked: 'control' };
@@ -50,18 +53,33 @@ export function documentTracksChanges(doc) {
50
53
  const enforced = attr(protection, 'w:enforcement');
51
54
  return attr(protection, 'w:edit') === 'trackedChanges' && (enforced === '1' || enforced === 'true' || enforced === 'on');
52
55
  }
53
- /** Every paragraph of a block list (including table cells), in document order. */
54
- export function paragraphsOf(blocks, out = []) {
56
+ /**
57
+ * Every paragraph of a block list (including table cells), in document order. With `textBoxes`,
58
+ * the paragraphs of the text boxes in a paragraph follow it (a group's boxes depth first).
59
+ */
60
+ export function paragraphsOf(blocks, out = [], options = {}) {
55
61
  for (const b of blocks) {
56
- if (b.kind === 'paragraph')
62
+ if (b.kind === 'paragraph') {
57
63
  out.push(b);
64
+ if (options.textBoxes)
65
+ for (const inline of b.inlines)
66
+ if (inline.kind === 'image' && inline.content)
67
+ boxParagraphs(inline.content, out, options);
68
+ }
58
69
  else
59
70
  for (const row of b.rows)
60
71
  for (const cell of row.cells)
61
- paragraphsOf(cell.blocks, out);
72
+ paragraphsOf(cell.blocks, out, options);
62
73
  }
63
74
  return out;
64
75
  }
76
+ function boxParagraphs(content, out, options) {
77
+ if (content.type === 'shape' && content.shape.text)
78
+ paragraphsOf(content.shape.text.blocks, out, options);
79
+ else if (content.type === 'group')
80
+ for (const child of content.children)
81
+ boxParagraphs(child.content, out, options);
82
+ }
65
83
  export function paragraphText(para, options = {}) {
66
84
  let text = '';
67
85
  const segments = [];
@@ -200,6 +218,19 @@ function newRun(text, template, format) {
200
218
  return run;
201
219
  }
202
220
  const BOOKMARK_NAME = /^[\p{L}_][\p{L}\p{N}_]{0,39}$/u;
221
+ /** Run children that are objects: pictures, charts, shapes and text boxes (DrawingML, VML or with Word's old copy), and embedded OLE objects. */
222
+ const OBJECT_NODES = new Set(['w:drawing', 'w:pict', 'w:object', 'mc:AlternateContent']);
223
+ const OLD_VML = 'This is an old-style (VML) object: it can only be deleted';
224
+ const OLE_OBJECT = 'This is an embedded object (OLE): it can only be deleted';
225
+ /** Old VML objects and embedded OLE objects (w:object) can only be deleted. */
226
+ function onlyDeletable(obj) {
227
+ if (obj.vml)
228
+ throw new EditError(obj.drawing.name === 'w:object' ? OLE_OBJECT : OLD_VML);
229
+ }
230
+ // Word puts only pictures in a text box (no shapes, text boxes, charts or SmartArt), and only inline.
231
+ const SHAPE_IN_BOX = "Shapes and text boxes can't go inside a text box";
232
+ const PICTURES_IN_BOX = 'Only pictures can go inside a text box';
233
+ const INLINE_IN_BOX = 'An object inside a text box can only be inline';
203
234
  export class DocxEditor {
204
235
  doc;
205
236
  guard;
@@ -299,7 +330,7 @@ export class DocxEditor {
299
330
  outer.children.splice(outer.children.indexOf(container), 1);
300
331
  }
301
332
  /** Mark the runs of a range as deleted (and the paragraph marks inside it), keeping the text. */
302
- trackedCut(range, track) {
333
+ trackedCut(range, track, keep) {
303
334
  const index = this.index();
304
335
  const { startMark, endMark } = isolate(index, range);
305
336
  let idx = this.index();
@@ -310,6 +341,10 @@ export class DocxEditor {
310
341
  replaceMark(idx, endMark, []);
311
342
  throw new EditError('The range crosses table cells');
312
343
  }
344
+ if (keep) {
345
+ this.takeObjects(idx, startMark, endMark, keep);
346
+ idx = this.index();
347
+ }
313
348
  const startPara = idx.ancestor(startMark, 'w:p');
314
349
  const endPara = idx.ancestor(endMark, 'w:p');
315
350
  const paragraphs = startPara === endPara ? [] : [startPara, ...between(idx, startMark, endMark, 'w:p').filter((p) => p !== endPara)];
@@ -340,8 +375,41 @@ export class DocxEditor {
340
375
  check(action, range, detail) {
341
376
  const tracked = this.trackChanges && (action === 'edit' || action === 'format' || action === 'fillForm');
342
377
  this.guard?.assert(action, range, tracked ? { ...detail, tracked: true } : detail);
343
- if (range && (action === 'edit' || action === 'format' || action === 'link'))
344
- this.assertUnlocked(range);
378
+ if (!range)
379
+ return;
380
+ const idx = this.index();
381
+ if (action === 'edit' || action === 'format' || action === 'link')
382
+ this.assertUnlocked(range, idx);
383
+ this.dropStaleFallbacks([range.start.node, range.end.node], idx);
384
+ }
385
+ /**
386
+ * Permission for a change Word can't track (an object's size, a floating object's position or
387
+ * wrap, alt text, chart data): it applies directly even with Track Changes on, so it is refused
388
+ * where only tracked changes are allowed. Locks hold as for any edit.
389
+ */
390
+ checkUntracked(range) {
391
+ this.guard?.assert('format', range, { tracked: false });
392
+ const idx = this.index();
393
+ this.assertUnlocked(range, idx);
394
+ this.dropStaleFallbacks([range.start.node, range.end.node], idx);
395
+ }
396
+ /**
397
+ * Word stores a text box twice: DrawingML in mc:Choice and an old VML copy in mc:Fallback. A
398
+ * change inside the box (at any of `nodes`) leaves the copy stale, so it goes.
399
+ */
400
+ dropStaleFallbacks(nodes, idx = this.index()) {
401
+ for (const node of nodes) {
402
+ let inBox = false;
403
+ for (let cur = node; cur; cur = idx.parent.get(cur)) {
404
+ if (cur.name === 'w:txbxContent')
405
+ inBox = true;
406
+ else if (cur.name === 'mc:Choice' && inBox) {
407
+ const alternate = idx.parent.get(cur);
408
+ if (alternate)
409
+ alternate.children = alternate.children.filter((c) => !(c.type === 'element' && c.name === 'mc:Fallback'));
410
+ }
411
+ }
412
+ }
345
413
  }
346
414
  /** The locked content control around a node, if any. */
347
415
  lockAround(idx, node) {
@@ -352,10 +420,9 @@ export class DocxEditor {
352
420
  return undefined;
353
421
  }
354
422
  /** Throw LockedRegionError when a range touches a locked region (or would delete one). */
355
- assertUnlocked(range) {
423
+ assertUnlocked(range, idx = this.index()) {
356
424
  if (this.bypassLocks)
357
425
  return;
358
- const idx = this.index();
359
426
  for (const pos of [range.start, range.end]) {
360
427
  if (!idx.contains(pos.node))
361
428
  continue;
@@ -393,10 +460,13 @@ export class DocxEditor {
393
460
  rangeFromSelection(sel) {
394
461
  return { start: { node: sel.start.inline.node, offset: sel.start.offset }, end: { node: sel.end.inline.node, offset: sel.end.offset } };
395
462
  }
396
- /** Every paragraph of the story (the body by default), including those in tables, in document order. */
463
+ /**
464
+ * Every paragraph of the story (the body by default), including those in tables, in document
465
+ * order. In the body, a text box's paragraphs come right after the paragraph holding the box.
466
+ */
397
467
  paragraphs() {
398
468
  if (!this.isStory)
399
- return paragraphsOf(this.doc.body().blocks);
469
+ return paragraphsOf(this.doc.body().blocks, [], { textBoxes: true });
400
470
  const root = this.root;
401
471
  if (root.name === 'w:footnotes' || root.name === 'w:endnotes') {
402
472
  // Separator notes (w:type) are not content.
@@ -465,6 +535,7 @@ export class DocxEditor {
465
535
  // Typing at the very edge of a locked region goes just outside it, as in Word.
466
536
  this.guard?.assert('edit', { start: at, end: at }, track ? { tracked: true } : undefined);
467
537
  const idx = this.index();
538
+ this.dropStaleFallbacks([at.node], idx);
468
539
  const run = newRun(text, idx.parentOf(at.node), format);
469
540
  const parent = idx.parentOf(edge.sdt);
470
541
  parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, this.placed(run, track));
@@ -560,19 +631,10 @@ export class DocxEditor {
560
631
  this.doc.pkg.setBytes(part, bytes, IMAGE_CONTENT_TYPES[ext]);
561
632
  const rId = await this.doc.pkg.addRelationship(this.part, REL.image, part);
562
633
  await this.doc.refreshRels(this.part);
563
- // Drawing ids must be unique in the document.
564
- let id = 0;
565
- for (const root of [this.doc.documentXml.root, this.root])
566
- for (const d of findAll(root, 'wp:docPr'))
567
- id = Math.max(id, Number(attr(d, 'id') ?? 0));
568
- id++;
634
+ const id = this.newDrawingId();
569
635
  const name = options.name ?? `Picture ${id}`;
570
636
  const cx = String(Math.round(width * 12700));
571
637
  const cy = String(Math.round(height * 12700));
572
- if (this.root.attrs['xmlns:wp'] === undefined)
573
- this.root.attrs['xmlns:wp'] = NS.wp;
574
- if (this.root.attrs['xmlns:r'] === undefined)
575
- this.root.attrs['xmlns:r'] = NS.r;
576
638
  const docPr = { id: String(id), name };
577
639
  if (options.alt)
578
640
  docPr.descr = options.alt;
@@ -596,6 +658,339 @@ export class DocxEditor {
596
658
  this.insertRunContent(at, [drawing]);
597
659
  return drawing;
598
660
  }
661
+ /** Declare namespace prefixes on the story's root element where they are missing. */
662
+ declare(...prefixes) {
663
+ for (const prefix of prefixes)
664
+ if (this.root.attrs[`xmlns:${prefix}`] === undefined)
665
+ this.root.attrs[`xmlns:${prefix}`] = NS[prefix];
666
+ }
667
+ /** An id for a new drawing (wp:docPr ids must be unique in the document); the root gets the prefixes drawings use. */
668
+ newDrawingId() {
669
+ let id = 0;
670
+ for (const root of [this.doc.documentXml.root, this.root])
671
+ for (const d of findAll(root, 'wp:docPr'))
672
+ id = Math.max(id, Number(attr(d, 'id')) || 0);
673
+ this.declare('wp', 'r');
674
+ return id + 1;
675
+ }
676
+ /** Fresh ids for copied content (see `cleanCopy`): tracked changes, drawings and content controls stay unique. */
677
+ copyIds() {
678
+ let drawing = this.newDrawingId() - 1;
679
+ const sdtIds = new Set(findAll(this.root, 'w:sdtPr').map((s) => attr(firstChild(s, 'w:id'), 'w:val')));
680
+ const sdt = () => {
681
+ let id;
682
+ do
683
+ id = String(1 + Math.floor(Math.random() * 2147483646));
684
+ while (sdtIds.has(id));
685
+ sdtIds.add(id);
686
+ return id;
687
+ };
688
+ return { revision: nextRevisionId(this.root), drawing: () => String(++drawing), sdt };
689
+ }
690
+ // ---- objects and charts ---------------------------------------------------------------------
691
+ /** Pictures, charts, SmartArt, shapes, text boxes and groups, numbered from 1 in document order. */
692
+ objects() {
693
+ return listObjects(this.paragraphs());
694
+ }
695
+ /**
696
+ * The run's child holding an object (its w:drawing or w:pict, or the mc:AlternateContent around
697
+ * it), found in the tree as it is now; EditError when the object is no longer in the document or
698
+ * is marked deleted (as the original of a tracked move is).
699
+ */
700
+ objectNodeOf(obj, idx = this.index()) {
701
+ if (!idx.contains(obj.drawing))
702
+ throw new EditError(`Object ${obj.n} is no longer in the document (list the objects again)`);
703
+ if (idx.ancestor(obj.drawing, 'w:del') || idx.ancestor(obj.drawing, 'w:moveFrom'))
704
+ throw new EditError(`Object ${obj.n} is deleted (a tracked change; list the objects again)`);
705
+ return this.runChildHolding(obj.drawing, idx);
706
+ }
707
+ /** The child of the nearest run that holds `node` (or is it). */
708
+ runChildHolding(node, idx) {
709
+ for (let parent = idx.parentOf(node); parent.name !== 'w:r'; parent = idx.parentOf(parent))
710
+ node = parent;
711
+ return node;
712
+ }
713
+ /** The range of an object, for access and lock checks. */
714
+ objectRange(obj, idx = this.index()) {
715
+ const node = this.objectNodeOf(obj, idx);
716
+ return { start: { node, offset: 0 }, end: { node, offset: 1 } };
717
+ }
718
+ /**
719
+ * Insert a chart inline at a position, with its data in an embedded workbook (so Word's "Edit
720
+ * Data" shows it). Without a size it gets Word's 432 × 252 pt, shrunk to the section's text width;
721
+ * with one side, the other keeps those proportions. Not inside a text box (Word puts only pictures
722
+ * there). Returns the w:drawing.
723
+ */
724
+ async insertChart(at, chart) {
725
+ if (inTextBox(this.index(), at.node))
726
+ throw new EditError(PICTURES_IN_BOX);
727
+ this.check('edit', { start: at, end: at });
728
+ validateChartData(chart.type, chart.stacked, chart.categories, chart.series);
729
+ const idx = this.index();
730
+ if (!idx.contains(at.node))
731
+ throw new EditError('That position is not in the document (stale position?)');
732
+ const size = chartSize(chart, textWidth(sectionAt(this.body, idx, at.node)) / 20);
733
+ const { pkg } = this.doc;
734
+ const part = freePartName(pkg, 'word/charts/chart', '.xml');
735
+ const workbook = await addWorkbook(pkg, part, await workbookFor(chart));
736
+ pkg.setXml(part, { declaration: null, prolog: [], root: newChartSpace(chart, workbook), epilog: [] }, CONTENT_TYPE.chart);
737
+ await this.doc.refreshRels(part);
738
+ const rId = await pkg.addRelationship(this.part, REL.chart, part);
739
+ await this.doc.refreshRels(this.part);
740
+ const id = this.newDrawingId();
741
+ const drawing = inlineFrame(id, `Chart ${id}`, size.width, size.height, chartGraphic(rId), chart.alt);
742
+ this.insertRunContent(at, [drawing]);
743
+ return drawing;
744
+ }
745
+ /**
746
+ * Insert a text box or a preset shape at a position, with optional text (each line a paragraph,
747
+ * listed by `paragraphs()` right after the paragraph holding it). By default it floats at the top
748
+ * left of the paragraph with square wrap; see `NewShape` for sizes and colours. Not inside a
749
+ * text box (Word doesn't nest them). Returns the w:drawing.
750
+ */
751
+ async insertShape(at, shape) {
752
+ if (inTextBox(this.index(), at.node))
753
+ throw new EditError(SHAPE_IN_BOX);
754
+ this.check('edit', { start: at, end: at });
755
+ const { width, height, place } = checkShape(shape);
756
+ const graphic = shapeGraphic(shape, width, height, (text, format) => newRun(text, undefined, format));
757
+ const id = this.newDrawingId();
758
+ this.declare('a', 'wps', 'mc');
759
+ const name = `${SHAPE_NAMES[shape.shape]} ${id}`;
760
+ const drawing = 'inline' in place
761
+ ? inlineFrame(id, name, width, height, graphic, shape.alt)
762
+ : anchorFrame(id, name, width, height, place, graphic, shape.alt, nextRelativeHeight([this.doc.documentXml.root, this.root]));
763
+ // Word 2010+ shapes go in mc:Choice; no old VML copy (mc:Fallback) is written.
764
+ this.insertRunContent(at, [el('mc:AlternateContent', {}, [el('mc:Choice', { Requires: 'wps' }, [drawing])])]);
765
+ return drawing;
766
+ }
767
+ /** A chart's data (type, titles, legend, categories, series) and where it comes from. */
768
+ chartInfo(obj) {
769
+ const { part, chartSpace } = chartOf(this.doc, obj);
770
+ return { ...readChartTable(chartSpace), source: chartData(this.doc, part, chartSpace).source };
771
+ }
772
+ /**
773
+ * Change a chart's titles, legend or data, keeping its formatting (see `patchChartSpace`). New
774
+ * data must suit the chart's type, and rewrites the embedded workbook; a chart with an old embedded
775
+ * object or no workbook gets a new one. A chart linked to an outside file only has its cached data
776
+ * changed: the file is not, and Word's refresh brings its numbers back. A chart part other charts
777
+ * share is copied for this chart first (see `ownChart`). Word does not track chart changes, so
778
+ * neither does this.
779
+ */
780
+ async updateChart(obj, changes) {
781
+ chartOf(this.doc, obj);
782
+ this.checkUntracked(this.objectRange(obj));
783
+ const { part, chartSpace } = await this.ownChart(obj);
784
+ const { pkg } = this.doc;
785
+ const data = chartData(this.doc, part, chartSpace);
786
+ const result = { source: data.source, workbookRewritten: false, workbookHadMore: false };
787
+ let rewrite = false;
788
+ if (changes.categories !== undefined || changes.series !== undefined) {
789
+ const current = readChartTable(chartSpace);
790
+ const categories = changes.categories ?? current.categories;
791
+ const series = changes.series ?? current.series;
792
+ const { type, stacked } = chartKind(chartSpace);
793
+ validateChartData(type, stacked, categories, series);
794
+ if (data.source !== 'linked') {
795
+ // What a workbook that can't be read (an old .xls object, broken bytes) held is unknown: it may have held more.
796
+ if (data.workbook) {
797
+ const old = await pkg.getBytes(data.workbook);
798
+ result.workbookHadMore = !isWorkbook(old) || (await workbookHasMore(old, current.categories.length, current.series.length));
799
+ }
800
+ else if (data.source === 'embedded')
801
+ result.workbookHadMore = true;
802
+ rewrite = true;
803
+ }
804
+ }
805
+ patchChartSpace(chartSpace, changes, { keepFormulas: data.source === 'linked' });
806
+ // The workbook holds the chart's data as the chart now caches it, number formats included.
807
+ const workbook = rewrite ? await workbookFor(readChartTable(chartSpace)) : undefined;
808
+ if (workbook) {
809
+ if (data.workbook)
810
+ pkg.setBytes(data.workbook, workbook);
811
+ else
812
+ await replaceWorkbook(this.doc, part, chartSpace, data.relId, workbook);
813
+ result.source = 'embedded';
814
+ result.workbookRewritten = true;
815
+ }
816
+ this.changed(part);
817
+ return result;
818
+ }
819
+ /**
820
+ * The chart part behind a chart object, for this chart alone: a part that other charts point at
821
+ * too (as copies made by docxkeun 0.3.0 and older do) is copied first, with its workbook, and this
822
+ * chart (and `obj.chartPart`) moves to the copy, so changing it leaves the others alone.
823
+ */
824
+ async ownChart(obj) {
825
+ const current = chartOf(this.doc, obj);
826
+ const target = (chart) => this.doc.rels(this.part).get(attr(chart, 'r:id') ?? '')?.target;
827
+ if (findAll(this.root, 'c:chart').filter((c) => target(c) === current.part).length < 2)
828
+ return current;
829
+ await this.copyChartParts([obj.drawing]);
830
+ const own = target(findAll(obj.drawing, 'c:chart')[0]);
831
+ if (own)
832
+ obj.chartPart = own;
833
+ this.changed();
834
+ return chartOf(this.doc, obj);
835
+ }
836
+ /**
837
+ * Give every chart under `nodes` (c:chart, and Word 2016's cx:chart) its own copy of its chart part
838
+ * (and workbook), so copies change independently.
839
+ */
840
+ async copyChartParts(nodes) {
841
+ const { pkg } = this.doc;
842
+ let copied = false;
843
+ for (const chart of nodes.flatMap((n) => [...findAll(n, 'c:chart'), ...findAll(n, 'cx:chart')])) {
844
+ const rel = await pkg.relationshipById(this.part, attr(chart, 'r:id') ?? '');
845
+ if (!rel || rel.external || !pkg.has(pkg.resolve(this.part, rel)))
846
+ continue;
847
+ const copy = await copyPart(pkg, pkg.resolve(this.part, rel));
848
+ await this.doc.refreshRels(copy);
849
+ chart.attrs['r:id'] = await pkg.addRelationship(this.part, rel.type, copy);
850
+ copied = true;
851
+ }
852
+ if (copied)
853
+ await this.doc.refreshRels(this.part);
854
+ }
855
+ /**
856
+ * Resize an object (points). With one side given, the other keeps the object's proportions. A
857
+ * group's shapes scale with it; a chart redraws to fit. Word doesn't track size, so this applies
858
+ * directly, and is refused where only tracked changes are allowed.
859
+ */
860
+ resizeObject(obj, size) {
861
+ onlyDeletable(obj);
862
+ const range = this.objectRange(obj);
863
+ const frame = frameOf(obj.drawing);
864
+ const { width, height } = resized(frame, size);
865
+ this.checkUntracked(range);
866
+ resizeFrame(frame, width, height);
867
+ dropFallback(range.start.node);
868
+ this.changed();
869
+ }
870
+ /** Set an object's alt text (empty removes it). Not tracked, as in Word (see `resizeObject`). */
871
+ setObjectAlt(obj, alt) {
872
+ onlyDeletable(obj);
873
+ const range = this.objectRange(obj);
874
+ const docPr = firstChild(frameOf(obj.drawing), 'wp:docPr');
875
+ if (!docPr)
876
+ throw new EditError('This object has no description to edit');
877
+ this.checkUntracked(range);
878
+ if (alt)
879
+ docPr.attrs['descr'] = alt;
880
+ else
881
+ delete docPr.attrs['descr'];
882
+ dropFallback(range.start.node);
883
+ this.changed();
884
+ }
885
+ /** Delete an object. With Track Changes on the deletion is tracked: its run (and any text in it) is marked deleted. */
886
+ deleteObject(obj) {
887
+ const range = this.objectRange(obj);
888
+ this.deleteRange(range);
889
+ // What a tracked deletion keeps is the object, not Word's old copy of it.
890
+ dropFallback(range.start.node);
891
+ }
892
+ /**
893
+ * Move an object to `at`, keeping its size and placement (a floating object is anchored there
894
+ * instead). With Track Changes on this is tracked as Word tracks a cut and paste: the original is
895
+ * marked deleted and a copy inserted (a chart's copy gets its own chart part and workbook). Only
896
+ * pictures can go inside a text box, and an object there can only be inline.
897
+ */
898
+ async moveObject(obj, at) {
899
+ onlyDeletable(obj);
900
+ const idx = this.index();
901
+ const range = this.objectRange(obj, idx);
902
+ const node = range.start.node;
903
+ if (!idx.contains(at.node))
904
+ throw new EditError('That position is not in the document (stale position?)');
905
+ // Right before or after itself: already there.
906
+ if (at.node === node)
907
+ return;
908
+ for (let cur = idx.parent.get(at.node); cur; cur = idx.parent.get(cur))
909
+ if (cur === node)
910
+ throw new EditError("An object can't move inside itself");
911
+ if (inTextBox(idx, at.node)) {
912
+ if (obj.kind === 'shape' || obj.kind === 'textBox' || obj.kind === 'group')
913
+ throw new EditError(SHAPE_IN_BOX);
914
+ if (!isPicture(obj.drawing))
915
+ throw new EditError(PICTURES_IN_BOX);
916
+ if (frameOf(obj.drawing).name === 'wp:anchor')
917
+ throw new EditError(INLINE_IN_BOX);
918
+ }
919
+ this.check('edit', range);
920
+ if (this.trackChanges) {
921
+ await this.replaceTracked(obj, node, at);
922
+ return;
923
+ }
924
+ const run = this.objectRun(at, idx.parentOf(node));
925
+ takeOut(this.index(), node);
926
+ run.children.push(node);
927
+ dropFallback(node);
928
+ this.changed();
929
+ }
930
+ /**
931
+ * Place an object inline, or floating at a position with a wrap style. Moving or re-wrapping a
932
+ * floating object (what `place` leaves out of x, y, `from` and `wrap`, it keeps) isn't tracked by Word, so it applies
933
+ * directly and is refused where only tracked changes are allowed. Switching between inline and
934
+ * floating is tracked like a move when Track Changes is on: the original is marked deleted and a
935
+ * copy inserted right after it.
936
+ */
937
+ async placeObject(obj, place) {
938
+ onlyDeletable(obj);
939
+ const floating = frameOf(obj.drawing).name === 'wp:anchor';
940
+ checkPlacement(place, floating);
941
+ const idx = this.index();
942
+ const range = this.objectRange(obj, idx);
943
+ const node = range.start.node;
944
+ const relativeHeight = () => nextRelativeHeight([this.doc.documentXml.root, this.root]);
945
+ if ('inline' in place && !floating)
946
+ return;
947
+ if (!('inline' in place) && floating) {
948
+ // Moving or re-wrapping a floating object: Word doesn't track it.
949
+ this.checkUntracked(range);
950
+ }
951
+ else {
952
+ // Switching between inline and floating.
953
+ if (!floating && inTextBox(idx, node))
954
+ throw new EditError(INLINE_IN_BOX);
955
+ this.check('edit', range);
956
+ if (this.trackChanges) {
957
+ await this.replaceTracked(obj, node, { node, offset: 1 }, (drawing) => placeFrame(drawing, place, relativeHeight));
958
+ return;
959
+ }
960
+ }
961
+ placeFrame(obj.drawing, place, relativeHeight);
962
+ dropFallback(node);
963
+ this.changed();
964
+ }
965
+ /** A new, empty run at `at` (a tracked insertion when tracking) formatted like `like`, for an object. */
966
+ objectRun(at, like) {
967
+ const run = this.insertRunContent(at, []);
968
+ removeChildren(run, 'w:rPr');
969
+ const rPr = firstChild(like, 'w:rPr');
970
+ if (rPr) {
971
+ run.children.unshift(cloneElement(rPr));
972
+ cleanRunProps(run);
973
+ }
974
+ return run;
975
+ }
976
+ /**
977
+ * A tracked move: a copy of the object (`node` is the run's child holding it), changed by
978
+ * `change`, goes in at `at` as an insertion, with its own drawing id and chart part; the original
979
+ * is marked deleted.
980
+ */
981
+ async replaceTracked(obj, node, at, change) {
982
+ const idx = this.index();
983
+ const original = idx.parentOf(node);
984
+ const { copy, drawing } = cloneObject(idx, node, obj.drawing);
985
+ change?.(drawing);
986
+ const run = this.objectRun(at, original);
987
+ await this.copyChartParts([copy]);
988
+ // Ids from the tree as it is now, with the new insertion in it.
989
+ cleanCopy(copy, this.copyIds(), { comments: 0, notes: 0, bookmarks: 0 });
990
+ run.children.push(copy);
991
+ this.deleteRange({ start: { node, offset: 0 }, end: { node, offset: 1 } });
992
+ dropFallback(node);
993
+ }
599
994
  /** Add a footnote whose reference mark goes at a position. Returns the note's id. */
600
995
  async addFootnote(at, text) {
601
996
  this.check('edit', { start: at, end: at });
@@ -881,6 +1276,7 @@ export class DocxEditor {
881
1276
  // Enter at the start or end of a locked block adds a paragraph outside it.
882
1277
  this.guard?.assert('edit', { start: at, end: at });
883
1278
  const idx = this.index();
1279
+ this.dropStaleFallbacks([at.node], idx);
884
1280
  const pPr = firstChild(blockEdge.paragraph, 'w:pPr');
885
1281
  const newPPr = pPr ? structuredClone(pPr) : undefined;
886
1282
  if (newPPr)
@@ -969,8 +1365,16 @@ export class DocxEditor {
969
1365
  const track = this.tracking();
970
1366
  if (track) {
971
1367
  const { startMark, endMark, idx } = this.trackedCut(range, track);
1368
+ const holders = new Set([idx.parentOf(startMark), idx.parentOf(endMark)]);
972
1369
  replaceMark(idx, startMark, []);
973
1370
  replaceMark(this.index(), endMark, []);
1371
+ // Deleting all of the author's own insertion takes it out, w:ins and all.
1372
+ const after = this.index();
1373
+ for (const holder of holders) {
1374
+ const parent = after.parent.get(holder);
1375
+ if (parent && (holder.name === 'w:ins' || holder.name === 'w:moveTo') && !elements(holder).length)
1376
+ parent.children.splice(parent.children.indexOf(holder), 1);
1377
+ }
974
1378
  this.changed();
975
1379
  return;
976
1380
  }
@@ -989,9 +1393,12 @@ export class DocxEditor {
989
1393
  /**
990
1394
  * Replace a range with text formatted like the range's first run, or with pieces of text that are
991
1395
  * each formatted like their own `like` run (for example to rewrite a sentence and keep which words
992
- * were bold). `format` is applied on top.
1396
+ * were bold). `format` is applied on top. Objects in the range (pictures, charts, shapes, text
1397
+ * boxes) go with the old text, as when a user selects and types over them; with `keepObjects` they
1398
+ * stay, right after the new text in their original order (not marked deleted when tracking).
1399
+ * Returns how many objects were kept.
993
1400
  */
994
- replaceRange(range, text, format) {
1401
+ replaceRange(range, text, format, options = {}) {
995
1402
  this.check('edit', range);
996
1403
  const index = this.index();
997
1404
  const template = index.parentOf(range.start.node);
@@ -1002,19 +1409,47 @@ export class DocxEditor {
1002
1409
  : []
1003
1410
  : text.filter((p) => p.text).map((p) => newRun(p.text, p.like ?? template, format || p.format ? { ...format, ...p.format } : undefined));
1004
1411
  const track = this.tracking();
1412
+ const keep = options.keepObjects ? { runs: [], count: 0, nextId: track?.nextId ?? nextRevisionId(this.root) } : undefined;
1005
1413
  if (track) {
1006
1414
  // The old text stays as a deletion; the new text follows it as an insertion.
1007
- const { startMark, endMark } = this.trackedCut(range, track);
1415
+ const { startMark, endMark } = this.trackedCut(range, track, keep);
1008
1416
  replaceMark(this.index(), startMark, []);
1009
1417
  this.liftOutOfInsertion(endMark, this.index());
1010
- replaceMark(this.index(), endMark, runs.length ? [insertedRuns(runs, track.nextId(), track.who)] : []);
1418
+ replaceMark(this.index(), endMark, [...(runs.length ? [insertedRuns(runs, track.nextId(), track.who)] : []), ...(keep?.runs ?? [])]);
1011
1419
  this.changed();
1012
- return;
1420
+ return keep?.count ?? 0;
1013
1421
  }
1014
- const { startMark, endMark, idx } = this.cut(range);
1015
- replaceMark(idx, startMark, runs);
1422
+ const { startMark, endMark, idx } = this.cut(range, keep);
1423
+ replaceMark(idx, startMark, [...runs, ...(keep?.runs ?? [])]);
1016
1424
  replaceMark(idx, endMark, []);
1017
1425
  this.changed();
1426
+ return keep?.count ?? 0;
1427
+ }
1428
+ /**
1429
+ * Take the objects (see OBJECT_NODES) between two marks out of their runs, for `replaceRange`
1430
+ * with keepObjects: they come back in `keep.runs`, in a run like the one they were in, and still in
1431
+ * a tracked insertion when they were in one. Objects already marked deleted, and anything inside an
1432
+ * object in the range (a text box's own runs), are left alone. A range inside a text box keeps the
1433
+ * objects of its own runs: those share the range's holding run.
1434
+ */
1435
+ takeObjects(idx, startMark, endMark, keep) {
1436
+ const holder = idx.ancestor(startMark, 'w:r');
1437
+ for (const run of between(idx, startMark, endMark, 'w:r')) {
1438
+ if (idx.ancestor(run, 'w:r') !== holder || idx.ancestor(run, 'w:del') || idx.ancestor(run, 'w:moveFrom'))
1439
+ continue;
1440
+ const objects = elements(run).filter((c) => OBJECT_NODES.has(c.name));
1441
+ if (!objects.length)
1442
+ continue;
1443
+ const rPr = firstChild(run, 'w:rPr');
1444
+ const copy = el('w:r', {}, [...(rPr ? [cloneElement(rPr)] : []), ...objects]);
1445
+ const revision = runRevision(run, (n) => idx.parent.get(n));
1446
+ for (const node of objects)
1447
+ takeOut(idx, node);
1448
+ keep.count += objects.length;
1449
+ keep.runs.push(revision && (revision.name === 'w:ins' || revision.name === 'w:moveTo')
1450
+ ? el('w:ins', { 'w:id': keep.nextId(), 'w:author': attr(revision, 'w:author') ?? '', ...(attr(revision, 'w:date') ? { 'w:date': attr(revision, 'w:date') } : {}) }, [copy])
1451
+ : copy);
1452
+ }
1018
1453
  }
1019
1454
  /** Replace every match; returns how many were replaced. */
1020
1455
  replaceAll(query, replacement) {
@@ -1134,7 +1569,7 @@ export class DocxEditor {
1134
1569
  this.changed();
1135
1570
  }
1136
1571
  /** Remove the content of a range, returning the sentinels at its (now adjacent) ends. */
1137
- cut(range) {
1572
+ cut(range, keep) {
1138
1573
  const index = this.index();
1139
1574
  const { startMark, endMark } = isolate(index, range);
1140
1575
  let idx = this.index();
@@ -1145,6 +1580,10 @@ export class DocxEditor {
1145
1580
  replaceMark(idx, endMark, []);
1146
1581
  throw new EditError('The range crosses table cells');
1147
1582
  }
1583
+ if (keep) {
1584
+ this.takeObjects(idx, startMark, endMark, keep);
1585
+ idx = this.index();
1586
+ }
1148
1587
  const startPara = idx.ancestor(startMark, 'w:p');
1149
1588
  const endPara = idx.ancestor(endMark, 'w:p');
1150
1589
  // Remove runs between the marks, then whole paragraphs and tables in between.
@@ -1222,8 +1661,8 @@ export class DocxEditor {
1222
1661
  }
1223
1662
  const idx = this.index();
1224
1663
  const parent = idx.parentOf(paragraph);
1225
- // A table cell must keep at least one paragraph.
1226
- if (parent.name === 'w:tc' && elements(parent, 'w:p').length === 1) {
1664
+ // A table cell, and a text box, must keep at least one paragraph.
1665
+ if ((parent.name === 'w:tc' || parent.name === 'w:txbxContent') && elements(parent, 'w:p').length === 1) {
1227
1666
  paragraph.children = paragraph.children.filter((c) => c.type === 'element' && c.name === 'w:pPr');
1228
1667
  }
1229
1668
  else
@@ -1285,23 +1724,10 @@ export class DocxEditor {
1285
1724
  throw new EditError('The last paragraph to copy comes before the first');
1286
1725
  const originals = kids.slice(first, last + 1).filter((c) => c.type === 'element' && c.name !== 'w:sectPr');
1287
1726
  const copies = originals.map(cloneElement);
1288
- // Ids that must stay unique in the document.
1289
- const revision = nextRevisionId(this.root);
1290
- let drawing = 0;
1291
- for (const d of findAll(this.root, 'wp:docPr'))
1292
- drawing = Math.max(drawing, Number(attr(d, 'id')) || 0);
1293
- const sdtIds = new Set(findAll(this.root, 'w:sdtPr').map((s) => attr(firstChild(s, 'w:id'), 'w:val')));
1294
- const sdt = () => {
1295
- let id;
1296
- do
1297
- id = String(1 + Math.floor(Math.random() * 2147483646));
1298
- while (sdtIds.has(id));
1299
- sdtIds.add(id);
1300
- return id;
1301
- };
1727
+ const ids = this.copyIds();
1302
1728
  const dropped = { comments: 0, notes: 0, bookmarks: 0 };
1303
1729
  for (const c of copies)
1304
- cleanCopy(c, { revision, drawing: () => String(++drawing), sdt }, dropped);
1730
+ cleanCopy(c, ids, dropped);
1305
1731
  // Lists in the copy: a new list of the same look for each list copied, so numbering restarts.
1306
1732
  if (options.restartLists ?? true) {
1307
1733
  const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
@@ -1344,6 +1770,7 @@ export class DocxEditor {
1344
1770
  else
1345
1771
  blocks.unshift(el('w:p', {}, [el('w:pPr', {}, [el('w:pageBreakBefore')])]));
1346
1772
  }
1773
+ await this.copyChartParts(copies);
1347
1774
  const track = this.tracking();
1348
1775
  if (track)
1349
1776
  for (const b of blocks)
@@ -1486,8 +1913,8 @@ export class DocxEditor {
1486
1913
  const idx = this.index();
1487
1914
  const parent = idx.parentOf(table);
1488
1915
  parent.children.splice(indexOfChild(parent, table), 1);
1489
- // A table cell, and the body, must keep a paragraph.
1490
- if (parent.name === 'w:tc' && !elements(parent, 'w:p').length)
1916
+ // A table cell, a text box, and the body, must keep a paragraph.
1917
+ if ((parent.name === 'w:tc' || parent.name === 'w:txbxContent') && !elements(parent, 'w:p').length)
1491
1918
  parent.children.push(el('w:p'));
1492
1919
  if (parent === this.body && !elements(parent).some((c) => c.name === 'w:p' || c.name === 'w:tbl' || c.name === 'w:sdt')) {
1493
1920
  const sect = firstChild(parent, 'w:sectPr');
@@ -1741,6 +2168,7 @@ export class DocxEditor {
1741
2168
  this.check('link');
1742
2169
  if ('url' in target && !/^(https?|mailto|tel|ftp):/i.test(target.url))
1743
2170
  throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
2171
+ this.dropStaleFallbacks([hyperlink]);
1744
2172
  const old = hyperlink.attrs['r:id'];
1745
2173
  if ('url' in target) {
1746
2174
  hyperlink.attrs['r:id'] = await this.doc.pkg.addRelationship(this.part, REL.hyperlink, target.url, true);
@@ -1768,19 +2196,22 @@ export class DocxEditor {
1768
2196
  }
1769
2197
  await this.doc.refreshRels(this.part);
1770
2198
  }
1771
- /** Set the alt text (wp:docPr/@descr) of a picture or drawing. */
2199
+ /** Set the alt text (wp:docPr/@descr) of a picture or drawing. Not tracked, as in Word (see `setObjectAlt`). */
1772
2200
  setImageAlt(drawing, text) {
1773
- this.check('edit');
1774
2201
  const props = drawing.name === 'wp:docPr' ? drawing : findAll(drawing, 'wp:docPr')[0];
1775
2202
  if (!props)
1776
2203
  throw new EditError('This object has no description to edit');
2204
+ const node = this.runChildHolding(props, this.index());
2205
+ this.checkUntracked({ start: { node, offset: 0 }, end: { node, offset: 1 } });
1777
2206
  props.attrs['descr'] = text;
2207
+ dropFallback(node);
1778
2208
  this.changed();
1779
2209
  }
1780
2210
  /** Unwrap a w:hyperlink, keeping its text. */
1781
2211
  async removeHyperlink(link) {
1782
2212
  this.check('link');
1783
2213
  const idx = this.index();
2214
+ this.dropStaleFallbacks([link], idx);
1784
2215
  const parent = idx.parentOf(link);
1785
2216
  const runs = link.children;
1786
2217
  for (const run of findAll(link, 'w:r')) {
@@ -1825,7 +2256,9 @@ export class DocxEditor {
1825
2256
  return;
1826
2257
  const id = attr(start, 'w:id');
1827
2258
  const idx = this.index();
1828
- for (const node of [start, ...findAll(this.root, 'w:bookmarkEnd').filter((b) => attr(b, 'w:id') === id)]) {
2259
+ const nodes = [start, ...findAll(this.root, 'w:bookmarkEnd').filter((b) => attr(b, 'w:id') === id)];
2260
+ this.dropStaleFallbacks(nodes, idx);
2261
+ for (const node of nodes) {
1829
2262
  const parent = idx.parentOf(node);
1830
2263
  parent.children.splice(indexOfChild(parent, node), 1);
1831
2264
  }
@@ -1989,6 +2422,7 @@ export class DocxEditor {
1989
2422
  const region = this.lockedRegions().find((r) => r.id === id);
1990
2423
  if (!region)
1991
2424
  throw new EditError(`No locked region with id ${id}`);
2425
+ this.dropStaleFallbacks([region.el]);
1992
2426
  if (region.tag === LOCK_TAG) {
1993
2427
  const idx = this.index();
1994
2428
  const parent = idx.parentOf(region.el);