docxkeun 0.2.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.
- package/CHANGELOG.md +52 -0
- package/README.md +82 -3
- package/dist/api/editor.d.ts +191 -6
- package/dist/api/editor.js +780 -37
- package/dist/api/index.d.ts +4 -1
- package/dist/api/index.js +1 -0
- package/dist/api/objects.d.ts +202 -0
- package/dist/api/objects.js +574 -0
- package/dist/api/revisions.js +13 -2
- package/dist/api/tables.d.ts +60 -0
- package/dist/api/tables.js +138 -0
- package/dist/charts/index.d.ts +4 -1
- package/dist/charts/index.js +3 -1
- package/dist/charts/model.d.ts +4 -0
- package/dist/charts/model.js +3 -2
- package/dist/charts/workbook.d.ts +29 -0
- package/dist/charts/workbook.js +203 -0
- package/dist/charts/write.d.ts +91 -0
- package/dist/charts/write.js +559 -0
- package/dist/opc/constants.d.ts +4 -0
- package/dist/opc/constants.js +4 -0
- package/dist/render/activity.d.ts +58 -2
- package/dist/render/activity.js +500 -47
- package/dist/render/index.d.ts +1 -1
- package/dist/render/index.js +1 -1
- package/dist/render/viewer.js +2 -0
- package/package.json +1 -1
package/dist/api/editor.js
CHANGED
|
@@ -4,13 +4,18 @@
|
|
|
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';
|
|
10
12
|
import { createList, listItems } from './lists.js';
|
|
13
|
+
import { buildTable, cleanCopy, columnWidths, markInserted, markRow } from './tables.js';
|
|
14
|
+
import { cloneElement } from '../xml/index.js';
|
|
11
15
|
import { acceptRevisions, cleanRunProps, deleteRun, insertedRuns, listRevisions, markParagraph, nextRevisionId, paragraphMarkRevision, recordParagraphFormat, recordRunFormat, rejectRevisions, revisionStamp, runRevision, } from './revisions.js';
|
|
12
16
|
import { SETTINGS_ORDER } from '../security/protection.js';
|
|
13
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';
|
|
14
19
|
import { between, EditError, indexOfChild, isolate, PPR_ORDER, replaceMark, RPR_ORDER, textNode, TreeIndex, } from './positions.js';
|
|
15
20
|
const LOCK_VALUES = { content: 'contentLocked', contentAndControl: 'sdtContentLocked', control: 'sdtLocked' };
|
|
16
21
|
const LOCK_MODES = { contentLocked: 'content', sdtContentLocked: 'contentAndControl', sdtLocked: 'control' };
|
|
@@ -48,18 +53,33 @@ export function documentTracksChanges(doc) {
|
|
|
48
53
|
const enforced = attr(protection, 'w:enforcement');
|
|
49
54
|
return attr(protection, 'w:edit') === 'trackedChanges' && (enforced === '1' || enforced === 'true' || enforced === 'on');
|
|
50
55
|
}
|
|
51
|
-
/**
|
|
52
|
-
|
|
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 = {}) {
|
|
53
61
|
for (const b of blocks) {
|
|
54
|
-
if (b.kind === 'paragraph')
|
|
62
|
+
if (b.kind === 'paragraph') {
|
|
55
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
|
+
}
|
|
56
69
|
else
|
|
57
70
|
for (const row of b.rows)
|
|
58
71
|
for (const cell of row.cells)
|
|
59
|
-
paragraphsOf(cell.blocks, out);
|
|
72
|
+
paragraphsOf(cell.blocks, out, options);
|
|
60
73
|
}
|
|
61
74
|
return out;
|
|
62
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
|
+
}
|
|
63
83
|
export function paragraphText(para, options = {}) {
|
|
64
84
|
let text = '';
|
|
65
85
|
const segments = [];
|
|
@@ -173,6 +193,21 @@ function endOfRun(run, fallback) {
|
|
|
173
193
|
return { node: fallback, offset: 0 };
|
|
174
194
|
return last.name === 'w:t' ? { node: last, offset: textContent(last).length } : { node: last, offset: 1 };
|
|
175
195
|
}
|
|
196
|
+
/** Whether a list level is in a set_list format (decimal "1." and decimalParen "1)" differ by their text). */
|
|
197
|
+
function levelMatches(level, format) {
|
|
198
|
+
if (format === 'decimal')
|
|
199
|
+
return level.format === 'decimal' && !/\)\s*$/.test(level.text);
|
|
200
|
+
if (format === 'decimalParen')
|
|
201
|
+
return level.format === 'decimal' && /\)\s*$/.test(level.text);
|
|
202
|
+
return level.format === format;
|
|
203
|
+
}
|
|
204
|
+
function describeLevel(level) {
|
|
205
|
+
if (level.format === 'bullet')
|
|
206
|
+
return 'bulleted';
|
|
207
|
+
if (level.format === 'decimal')
|
|
208
|
+
return /\)\s*$/.test(level.text) ? 'numbered 1)' : 'numbered 1.';
|
|
209
|
+
return `numbered with ${level.format}`;
|
|
210
|
+
}
|
|
176
211
|
function newRun(text, template, format) {
|
|
177
212
|
const rPr = template ? firstChild(template, 'w:rPr') : undefined;
|
|
178
213
|
const run = el('w:r', {}, [...(rPr ? [structuredClone(rPr)] : []), ...runContent(text)]);
|
|
@@ -183,6 +218,19 @@ function newRun(text, template, format) {
|
|
|
183
218
|
return run;
|
|
184
219
|
}
|
|
185
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';
|
|
186
234
|
export class DocxEditor {
|
|
187
235
|
doc;
|
|
188
236
|
guard;
|
|
@@ -282,7 +330,7 @@ export class DocxEditor {
|
|
|
282
330
|
outer.children.splice(outer.children.indexOf(container), 1);
|
|
283
331
|
}
|
|
284
332
|
/** Mark the runs of a range as deleted (and the paragraph marks inside it), keeping the text. */
|
|
285
|
-
trackedCut(range, track) {
|
|
333
|
+
trackedCut(range, track, keep) {
|
|
286
334
|
const index = this.index();
|
|
287
335
|
const { startMark, endMark } = isolate(index, range);
|
|
288
336
|
let idx = this.index();
|
|
@@ -293,6 +341,10 @@ export class DocxEditor {
|
|
|
293
341
|
replaceMark(idx, endMark, []);
|
|
294
342
|
throw new EditError('The range crosses table cells');
|
|
295
343
|
}
|
|
344
|
+
if (keep) {
|
|
345
|
+
this.takeObjects(idx, startMark, endMark, keep);
|
|
346
|
+
idx = this.index();
|
|
347
|
+
}
|
|
296
348
|
const startPara = idx.ancestor(startMark, 'w:p');
|
|
297
349
|
const endPara = idx.ancestor(endMark, 'w:p');
|
|
298
350
|
const paragraphs = startPara === endPara ? [] : [startPara, ...between(idx, startMark, endMark, 'w:p').filter((p) => p !== endPara)];
|
|
@@ -323,8 +375,41 @@ export class DocxEditor {
|
|
|
323
375
|
check(action, range, detail) {
|
|
324
376
|
const tracked = this.trackChanges && (action === 'edit' || action === 'format' || action === 'fillForm');
|
|
325
377
|
this.guard?.assert(action, range, tracked ? { ...detail, tracked: true } : detail);
|
|
326
|
-
if (range
|
|
327
|
-
|
|
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
|
+
}
|
|
328
413
|
}
|
|
329
414
|
/** The locked content control around a node, if any. */
|
|
330
415
|
lockAround(idx, node) {
|
|
@@ -335,10 +420,9 @@ export class DocxEditor {
|
|
|
335
420
|
return undefined;
|
|
336
421
|
}
|
|
337
422
|
/** Throw LockedRegionError when a range touches a locked region (or would delete one). */
|
|
338
|
-
assertUnlocked(range) {
|
|
423
|
+
assertUnlocked(range, idx = this.index()) {
|
|
339
424
|
if (this.bypassLocks)
|
|
340
425
|
return;
|
|
341
|
-
const idx = this.index();
|
|
342
426
|
for (const pos of [range.start, range.end]) {
|
|
343
427
|
if (!idx.contains(pos.node))
|
|
344
428
|
continue;
|
|
@@ -376,10 +460,13 @@ export class DocxEditor {
|
|
|
376
460
|
rangeFromSelection(sel) {
|
|
377
461
|
return { start: { node: sel.start.inline.node, offset: sel.start.offset }, end: { node: sel.end.inline.node, offset: sel.end.offset } };
|
|
378
462
|
}
|
|
379
|
-
/**
|
|
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
|
+
*/
|
|
380
467
|
paragraphs() {
|
|
381
468
|
if (!this.isStory)
|
|
382
|
-
return paragraphsOf(this.doc.body().blocks);
|
|
469
|
+
return paragraphsOf(this.doc.body().blocks, [], { textBoxes: true });
|
|
383
470
|
const root = this.root;
|
|
384
471
|
if (root.name === 'w:footnotes' || root.name === 'w:endnotes') {
|
|
385
472
|
// Separator notes (w:type) are not content.
|
|
@@ -448,6 +535,7 @@ export class DocxEditor {
|
|
|
448
535
|
// Typing at the very edge of a locked region goes just outside it, as in Word.
|
|
449
536
|
this.guard?.assert('edit', { start: at, end: at }, track ? { tracked: true } : undefined);
|
|
450
537
|
const idx = this.index();
|
|
538
|
+
this.dropStaleFallbacks([at.node], idx);
|
|
451
539
|
const run = newRun(text, idx.parentOf(at.node), format);
|
|
452
540
|
const parent = idx.parentOf(edge.sdt);
|
|
453
541
|
parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, this.placed(run, track));
|
|
@@ -543,19 +631,10 @@ export class DocxEditor {
|
|
|
543
631
|
this.doc.pkg.setBytes(part, bytes, IMAGE_CONTENT_TYPES[ext]);
|
|
544
632
|
const rId = await this.doc.pkg.addRelationship(this.part, REL.image, part);
|
|
545
633
|
await this.doc.refreshRels(this.part);
|
|
546
|
-
|
|
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++;
|
|
634
|
+
const id = this.newDrawingId();
|
|
552
635
|
const name = options.name ?? `Picture ${id}`;
|
|
553
636
|
const cx = String(Math.round(width * 12700));
|
|
554
637
|
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
638
|
const docPr = { id: String(id), name };
|
|
560
639
|
if (options.alt)
|
|
561
640
|
docPr.descr = options.alt;
|
|
@@ -579,6 +658,339 @@ export class DocxEditor {
|
|
|
579
658
|
this.insertRunContent(at, [drawing]);
|
|
580
659
|
return drawing;
|
|
581
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
|
+
}
|
|
582
994
|
/** Add a footnote whose reference mark goes at a position. Returns the note's id. */
|
|
583
995
|
async addFootnote(at, text) {
|
|
584
996
|
this.check('edit', { start: at, end: at });
|
|
@@ -864,6 +1276,7 @@ export class DocxEditor {
|
|
|
864
1276
|
// Enter at the start or end of a locked block adds a paragraph outside it.
|
|
865
1277
|
this.guard?.assert('edit', { start: at, end: at });
|
|
866
1278
|
const idx = this.index();
|
|
1279
|
+
this.dropStaleFallbacks([at.node], idx);
|
|
867
1280
|
const pPr = firstChild(blockEdge.paragraph, 'w:pPr');
|
|
868
1281
|
const newPPr = pPr ? structuredClone(pPr) : undefined;
|
|
869
1282
|
if (newPPr)
|
|
@@ -952,8 +1365,16 @@ export class DocxEditor {
|
|
|
952
1365
|
const track = this.tracking();
|
|
953
1366
|
if (track) {
|
|
954
1367
|
const { startMark, endMark, idx } = this.trackedCut(range, track);
|
|
1368
|
+
const holders = new Set([idx.parentOf(startMark), idx.parentOf(endMark)]);
|
|
955
1369
|
replaceMark(idx, startMark, []);
|
|
956
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
|
+
}
|
|
957
1378
|
this.changed();
|
|
958
1379
|
return;
|
|
959
1380
|
}
|
|
@@ -969,25 +1390,66 @@ export class DocxEditor {
|
|
|
969
1390
|
this.removeRange(range);
|
|
970
1391
|
this.changed();
|
|
971
1392
|
}
|
|
972
|
-
/**
|
|
973
|
-
|
|
1393
|
+
/**
|
|
1394
|
+
* Replace a range with text formatted like the range's first run, or with pieces of text that are
|
|
1395
|
+
* each formatted like their own `like` run (for example to rewrite a sentence and keep which words
|
|
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.
|
|
1400
|
+
*/
|
|
1401
|
+
replaceRange(range, text, format, options = {}) {
|
|
974
1402
|
this.check('edit', range);
|
|
975
1403
|
const index = this.index();
|
|
976
1404
|
const template = index.parentOf(range.start.node);
|
|
1405
|
+
// Built before the cut, from the runs as they are now.
|
|
1406
|
+
const runs = typeof text === 'string'
|
|
1407
|
+
? text || format
|
|
1408
|
+
? [newRun(text, template, format)]
|
|
1409
|
+
: []
|
|
1410
|
+
: text.filter((p) => p.text).map((p) => newRun(p.text, p.like ?? template, format || p.format ? { ...format, ...p.format } : undefined));
|
|
977
1411
|
const track = this.tracking();
|
|
1412
|
+
const keep = options.keepObjects ? { runs: [], count: 0, nextId: track?.nextId ?? nextRevisionId(this.root) } : undefined;
|
|
978
1413
|
if (track) {
|
|
979
1414
|
// The old text stays as a deletion; the new text follows it as an insertion.
|
|
980
|
-
const { startMark, endMark } = this.trackedCut(range, track);
|
|
1415
|
+
const { startMark, endMark } = this.trackedCut(range, track, keep);
|
|
981
1416
|
replaceMark(this.index(), startMark, []);
|
|
982
1417
|
this.liftOutOfInsertion(endMark, this.index());
|
|
983
|
-
replaceMark(this.index(), endMark,
|
|
1418
|
+
replaceMark(this.index(), endMark, [...(runs.length ? [insertedRuns(runs, track.nextId(), track.who)] : []), ...(keep?.runs ?? [])]);
|
|
984
1419
|
this.changed();
|
|
985
|
-
return;
|
|
1420
|
+
return keep?.count ?? 0;
|
|
986
1421
|
}
|
|
987
|
-
const { startMark, endMark, idx } = this.cut(range);
|
|
988
|
-
replaceMark(idx, startMark,
|
|
1422
|
+
const { startMark, endMark, idx } = this.cut(range, keep);
|
|
1423
|
+
replaceMark(idx, startMark, [...runs, ...(keep?.runs ?? [])]);
|
|
989
1424
|
replaceMark(idx, endMark, []);
|
|
990
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
|
+
}
|
|
991
1453
|
}
|
|
992
1454
|
/** Replace every match; returns how many were replaced. */
|
|
993
1455
|
replaceAll(query, replacement) {
|
|
@@ -1107,7 +1569,7 @@ export class DocxEditor {
|
|
|
1107
1569
|
this.changed();
|
|
1108
1570
|
}
|
|
1109
1571
|
/** Remove the content of a range, returning the sentinels at its (now adjacent) ends. */
|
|
1110
|
-
cut(range) {
|
|
1572
|
+
cut(range, keep) {
|
|
1111
1573
|
const index = this.index();
|
|
1112
1574
|
const { startMark, endMark } = isolate(index, range);
|
|
1113
1575
|
let idx = this.index();
|
|
@@ -1118,6 +1580,10 @@ export class DocxEditor {
|
|
|
1118
1580
|
replaceMark(idx, endMark, []);
|
|
1119
1581
|
throw new EditError('The range crosses table cells');
|
|
1120
1582
|
}
|
|
1583
|
+
if (keep) {
|
|
1584
|
+
this.takeObjects(idx, startMark, endMark, keep);
|
|
1585
|
+
idx = this.index();
|
|
1586
|
+
}
|
|
1121
1587
|
const startPara = idx.ancestor(startMark, 'w:p');
|
|
1122
1588
|
const endPara = idx.ancestor(endMark, 'w:p');
|
|
1123
1589
|
// Remove runs between the marks, then whole paragraphs and tables in between.
|
|
@@ -1195,14 +1661,276 @@ export class DocxEditor {
|
|
|
1195
1661
|
}
|
|
1196
1662
|
const idx = this.index();
|
|
1197
1663
|
const parent = idx.parentOf(paragraph);
|
|
1198
|
-
// A table cell must keep at least one paragraph.
|
|
1199
|
-
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) {
|
|
1200
1666
|
paragraph.children = paragraph.children.filter((c) => c.type === 'element' && c.name === 'w:pPr');
|
|
1201
1667
|
}
|
|
1202
1668
|
else
|
|
1203
1669
|
parent.children.splice(indexOfChild(parent, paragraph), 1);
|
|
1204
1670
|
this.changed();
|
|
1205
1671
|
}
|
|
1672
|
+
// ---- copies and tables -----------------------------------------------------------------------
|
|
1673
|
+
/** The block (paragraph, table or content control) of the body that holds `node`. */
|
|
1674
|
+
topBlock(node, idx = this.index()) {
|
|
1675
|
+
let n = node;
|
|
1676
|
+
for (let p = idx.parent.get(n); p && p !== this.body; p = idx.parent.get(p))
|
|
1677
|
+
n = p;
|
|
1678
|
+
if (idx.parent.get(n) !== this.body)
|
|
1679
|
+
throw new EditError('That paragraph is not in the body of the document');
|
|
1680
|
+
return n;
|
|
1681
|
+
}
|
|
1682
|
+
/** Put new blocks into the body before/after the block holding `ref`, or at the start or end. */
|
|
1683
|
+
placeBlocks(blocks, where) {
|
|
1684
|
+
const body = this.body;
|
|
1685
|
+
const sect = firstChild(body, 'w:sectPr');
|
|
1686
|
+
let at;
|
|
1687
|
+
if (where === 'start')
|
|
1688
|
+
at = 0;
|
|
1689
|
+
else if (where === 'end')
|
|
1690
|
+
at = sect ? body.children.indexOf(sect) : body.children.length;
|
|
1691
|
+
else {
|
|
1692
|
+
const ref = where.before ?? where.after;
|
|
1693
|
+
if (!ref)
|
|
1694
|
+
throw new EditError('Pass the paragraph to place it before or after');
|
|
1695
|
+
const top = this.topBlock(ref);
|
|
1696
|
+
at = body.children.indexOf(top) + (where.after ? 1 : 0);
|
|
1697
|
+
}
|
|
1698
|
+
body.children.splice(at, 0, ...blocks);
|
|
1699
|
+
// Word wants a paragraph after a table that ends the document.
|
|
1700
|
+
const last = blocks[blocks.length - 1];
|
|
1701
|
+
const next = body.children[at + blocks.length];
|
|
1702
|
+
if (last?.name === 'w:tbl' && (!next || (next.type === 'element' && next.name === 'w:sectPr')))
|
|
1703
|
+
body.children.splice(at + blocks.length, 0, el('w:p'));
|
|
1704
|
+
}
|
|
1705
|
+
/** Permission to add content next to `where`. */
|
|
1706
|
+
checkPlace(where) {
|
|
1707
|
+
const ref = typeof where === 'object' ? (where.before ?? where.after) : undefined;
|
|
1708
|
+
this.check('edit', ref ? { start: { node: ref, offset: 0 }, end: { node: ref, offset: 0 } } : undefined);
|
|
1709
|
+
}
|
|
1710
|
+
/**
|
|
1711
|
+
* Copy the body's blocks from the one holding `from` to the one holding `to` (a table is copied
|
|
1712
|
+
* whole) and put the copies at `where`, with their formatting, lists, tables and pictures. Lists
|
|
1713
|
+
* in the copy number from the start again unless `restartLists` is false, and `pageBreak` starts
|
|
1714
|
+
* the copy on a new page. What may exist only once (bookmarks, comment anchors, note references)
|
|
1715
|
+
* is left out of the copy and counted in `dropped`.
|
|
1716
|
+
*/
|
|
1717
|
+
async copyBlocks(from, to, where, options = {}) {
|
|
1718
|
+
this.checkPlace(where);
|
|
1719
|
+
const idx = this.index();
|
|
1720
|
+
const kids = this.body.children;
|
|
1721
|
+
const first = kids.indexOf(this.topBlock(from, idx));
|
|
1722
|
+
const last = kids.indexOf(this.topBlock(to, idx));
|
|
1723
|
+
if (last < first)
|
|
1724
|
+
throw new EditError('The last paragraph to copy comes before the first');
|
|
1725
|
+
const originals = kids.slice(first, last + 1).filter((c) => c.type === 'element' && c.name !== 'w:sectPr');
|
|
1726
|
+
const copies = originals.map(cloneElement);
|
|
1727
|
+
const ids = this.copyIds();
|
|
1728
|
+
const dropped = { comments: 0, notes: 0, bookmarks: 0 };
|
|
1729
|
+
for (const c of copies)
|
|
1730
|
+
cleanCopy(c, ids, dropped);
|
|
1731
|
+
// Lists in the copy: a new list of the same look for each list copied, so numbering restarts.
|
|
1732
|
+
if (options.restartLists ?? true) {
|
|
1733
|
+
const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
|
|
1734
|
+
const renumbered = new Map();
|
|
1735
|
+
for (const p of copies.flatMap((c) => (c.name === 'w:p' ? [c] : findAll(c, 'w:p')))) {
|
|
1736
|
+
const pPr = firstChild(p, 'w:pPr');
|
|
1737
|
+
const numPr = firstChild(pPr, 'w:numPr');
|
|
1738
|
+
const styleId = attr(firstChild(pPr, 'w:pStyle'), 'w:val');
|
|
1739
|
+
const numId = numPr ? attr(firstChild(numPr, 'w:numId'), 'w:val') : styleId ? this.doc.styles.get(styleId)?.pPr.numId : undefined;
|
|
1740
|
+
if (!numId || numId === '0')
|
|
1741
|
+
continue;
|
|
1742
|
+
let fresh = renumbered.get(numId);
|
|
1743
|
+
if (!fresh) {
|
|
1744
|
+
const abstractId = this.doc.numbering.abstractFor(numId, styleNumId)?.id;
|
|
1745
|
+
fresh = await createList(this.doc, { format: 'keep', levels: new Set(), base: { numId, abstractId } });
|
|
1746
|
+
renumbered.set(numId, fresh);
|
|
1747
|
+
}
|
|
1748
|
+
const ilvl = numPr ? attr(firstChild(numPr, 'w:ilvl'), 'w:val') ?? '0' : String(styleId ? (this.doc.styles.get(styleId)?.pPr.ilvl ?? 0) : 0);
|
|
1749
|
+
const target = ensureChild(p, 'w:pPr');
|
|
1750
|
+
if (p.children[0] !== target) {
|
|
1751
|
+
p.children.splice(p.children.indexOf(target), 1);
|
|
1752
|
+
p.children.unshift(target);
|
|
1753
|
+
}
|
|
1754
|
+
removeChildren(target, 'w:numPr');
|
|
1755
|
+
insertOrdered(target, el('w:numPr', {}, [el('w:ilvl', { 'w:val': ilvl }), el('w:numId', { 'w:val': fresh })]), PPR_ORDER);
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
const blocks = [...copies];
|
|
1759
|
+
if (options.pageBreak) {
|
|
1760
|
+
const head = blocks[0];
|
|
1761
|
+
if (head?.name === 'w:p') {
|
|
1762
|
+
const pPr = ensureChild(head, 'w:pPr');
|
|
1763
|
+
if (head.children[0] !== pPr) {
|
|
1764
|
+
head.children.splice(head.children.indexOf(pPr), 1);
|
|
1765
|
+
head.children.unshift(pPr);
|
|
1766
|
+
}
|
|
1767
|
+
removeChildren(pPr, 'w:pageBreakBefore');
|
|
1768
|
+
insertOrdered(pPr, el('w:pageBreakBefore'), PPR_ORDER);
|
|
1769
|
+
}
|
|
1770
|
+
else
|
|
1771
|
+
blocks.unshift(el('w:p', {}, [el('w:pPr', {}, [el('w:pageBreakBefore')])]));
|
|
1772
|
+
}
|
|
1773
|
+
await this.copyChartParts(copies);
|
|
1774
|
+
const track = this.tracking();
|
|
1775
|
+
if (track)
|
|
1776
|
+
for (const b of blocks)
|
|
1777
|
+
markInserted(b, track.nextId, track.who, (p) => markParagraph(p, 'ins', track.nextId(), track.who));
|
|
1778
|
+
this.placeBlocks(blocks, where);
|
|
1779
|
+
this.changed();
|
|
1780
|
+
return { blocks, dropped };
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* Insert a table of text (`rows` of cell texts; "\n" in a cell starts a new paragraph) before or
|
|
1784
|
+
* after the block holding a paragraph, or at the start or end. It spans the text width.
|
|
1785
|
+
*/
|
|
1786
|
+
insertTable(where, rows, options = {}) {
|
|
1787
|
+
this.checkPlace(where);
|
|
1788
|
+
const columns = Math.max(0, ...rows.map((r) => r.length));
|
|
1789
|
+
if (!rows.length || !columns)
|
|
1790
|
+
throw new EditError('A table needs at least one row and one column');
|
|
1791
|
+
if (rows.length > 500 || columns > 63)
|
|
1792
|
+
throw new EditError('A table can have at most 500 rows and 63 columns');
|
|
1793
|
+
if (options.widths && (options.widths.length !== columns || options.widths.some((w) => !(w > 0)))) {
|
|
1794
|
+
throw new EditError(`widths needs ${columns} positive numbers, one per column`);
|
|
1795
|
+
}
|
|
1796
|
+
const sections = sectionProperties(this.body);
|
|
1797
|
+
const total = textWidth(sections[sections.length - 1]);
|
|
1798
|
+
const grid = this.doc.styles.get('TableGrid') ? 'TableGrid' : undefined;
|
|
1799
|
+
const style = options.style ?? (options.borders === false ? undefined : grid);
|
|
1800
|
+
if (options.style && !this.doc.styles.get(options.style))
|
|
1801
|
+
throw new EditError(`There is no table style "${options.style}"`);
|
|
1802
|
+
const track = this.tracking();
|
|
1803
|
+
const table = buildTable(rows, columnWidths(columns, total, options.widths), {
|
|
1804
|
+
header: !!options.header,
|
|
1805
|
+
style,
|
|
1806
|
+
borders: options.borders !== false,
|
|
1807
|
+
align: options.align,
|
|
1808
|
+
paragraph: (text, header) => el('w:p', {}, [
|
|
1809
|
+
// Without a table style, cells get Table Grid's tight spacing.
|
|
1810
|
+
...(style ? [] : [el('w:pPr', {}, [el('w:spacing', { 'w:before': '0', 'w:after': '0' })])]),
|
|
1811
|
+
...(text ? [newRun(text, undefined, header ? { bold: true } : undefined)] : []),
|
|
1812
|
+
]),
|
|
1813
|
+
});
|
|
1814
|
+
if (track)
|
|
1815
|
+
markInserted(table, track.nextId, track.who, (p) => markParagraph(p, 'ins', track.nextId(), track.who));
|
|
1816
|
+
this.placeBlocks([table], where);
|
|
1817
|
+
this.changed();
|
|
1818
|
+
return table;
|
|
1819
|
+
}
|
|
1820
|
+
/** The table holding a paragraph (the innermost one). */
|
|
1821
|
+
tableOf(paragraph) {
|
|
1822
|
+
const idx = this.index();
|
|
1823
|
+
const table = idx.ancestor(paragraph, 'w:tbl');
|
|
1824
|
+
if (!table)
|
|
1825
|
+
throw new EditError('That paragraph is not in a table');
|
|
1826
|
+
return table;
|
|
1827
|
+
}
|
|
1828
|
+
/** Permission to change a table: its whole text. */
|
|
1829
|
+
checkTable(table) {
|
|
1830
|
+
const paras = findAll(table, 'w:p');
|
|
1831
|
+
const a = this.paragraphRange(paras[0]);
|
|
1832
|
+
const b = this.paragraphRange(paras[paras.length - 1]);
|
|
1833
|
+
this.check('edit', a && b ? { start: a.start, end: b.end } : { start: { node: table, offset: 0 }, end: { node: table, offset: 0 } });
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* Insert rows into a table before row `at` (0-based; the row count appends). Each new row copies
|
|
1837
|
+
* the formatting of the row next to it and gets the texts of one entry of `rows`.
|
|
1838
|
+
*/
|
|
1839
|
+
insertTableRows(table, at, rows) {
|
|
1840
|
+
this.checkTable(table);
|
|
1841
|
+
const existing = elements(table, 'w:tr');
|
|
1842
|
+
if (!Number.isInteger(at) || at < 0 || at > existing.length)
|
|
1843
|
+
throw new EditError(`Rows go from 0 to ${existing.length}`);
|
|
1844
|
+
if (!rows.length)
|
|
1845
|
+
throw new EditError('Pass at least one row');
|
|
1846
|
+
const template = existing[at - 1] ?? existing[at];
|
|
1847
|
+
if (!template)
|
|
1848
|
+
throw new EditError('The table has no rows to copy the formatting of');
|
|
1849
|
+
const cells = elements(template, 'w:tc');
|
|
1850
|
+
const widest = Math.max(...rows.map((r) => r.length));
|
|
1851
|
+
if (widest > cells.length)
|
|
1852
|
+
throw new EditError(`That row has ${cells.length} cells, so a new row can have at most ${cells.length} texts`);
|
|
1853
|
+
const track = this.tracking();
|
|
1854
|
+
const made = rows.map((texts) => {
|
|
1855
|
+
const row = cloneElement(template);
|
|
1856
|
+
delete row.attrs['w14:paraId'];
|
|
1857
|
+
delete row.attrs['w14:textId'];
|
|
1858
|
+
// Only the first rows of a table repeat as a header.
|
|
1859
|
+
const trPr = firstChild(row, 'w:trPr');
|
|
1860
|
+
if (trPr && at > 0) {
|
|
1861
|
+
removeChildren(trPr, 'w:tblHeader');
|
|
1862
|
+
removeChildren(trPr, 'w:ins');
|
|
1863
|
+
removeChildren(trPr, 'w:del');
|
|
1864
|
+
}
|
|
1865
|
+
elements(row, 'w:tc').forEach((tc, i) => {
|
|
1866
|
+
const tcPr = firstChild(tc, 'w:tcPr');
|
|
1867
|
+
if (tcPr)
|
|
1868
|
+
removeChildren(tcPr, 'w:vMerge');
|
|
1869
|
+
const p = firstChild(tc, 'w:p') ?? el('w:p');
|
|
1870
|
+
const pPr = firstChild(p, 'w:pPr');
|
|
1871
|
+
const runTemplate = findAll(p, 'w:r')[0];
|
|
1872
|
+
const text = texts[i] ?? '';
|
|
1873
|
+
const lines = text.split('\n');
|
|
1874
|
+
const paragraphs = lines.map((line) => el('w:p', {}, [...(pPr ? [cloneElement(pPr)] : []), ...(line ? [newRun(line, runTemplate)] : [])]));
|
|
1875
|
+
tc.children = [...(tcPr ? [tcPr] : []), ...paragraphs];
|
|
1876
|
+
});
|
|
1877
|
+
if (track)
|
|
1878
|
+
markInserted(row, track.nextId, track.who, (p) => markParagraph(p, 'ins', track.nextId(), track.who));
|
|
1879
|
+
return row;
|
|
1880
|
+
});
|
|
1881
|
+
const anchor = existing[at];
|
|
1882
|
+
table.children.splice(anchor ? table.children.indexOf(anchor) : table.children.length, 0, ...made);
|
|
1883
|
+
this.changed();
|
|
1884
|
+
return made;
|
|
1885
|
+
}
|
|
1886
|
+
/** Delete rows `from` to `to` (0-based, inclusive) of a table; deleting them all deletes the table. */
|
|
1887
|
+
deleteTableRows(table, from, to = from) {
|
|
1888
|
+
this.checkTable(table);
|
|
1889
|
+
const rows = elements(table, 'w:tr');
|
|
1890
|
+
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to >= rows.length || to < from)
|
|
1891
|
+
throw new EditError(`Rows go from 0 to ${rows.length - 1}`);
|
|
1892
|
+
if (from === 0 && to === rows.length - 1) {
|
|
1893
|
+
this.deleteTable(table);
|
|
1894
|
+
return;
|
|
1895
|
+
}
|
|
1896
|
+
const doomed = rows.slice(from, to + 1);
|
|
1897
|
+
const track = this.tracking();
|
|
1898
|
+
if (track)
|
|
1899
|
+
for (const row of doomed)
|
|
1900
|
+
this.markRowDeleted(row, track);
|
|
1901
|
+
else
|
|
1902
|
+
table.children = table.children.filter((c) => !(c.type === 'element' && doomed.includes(c)));
|
|
1903
|
+
this.changed();
|
|
1904
|
+
}
|
|
1905
|
+
/** Delete a whole table. */
|
|
1906
|
+
deleteTable(table) {
|
|
1907
|
+
this.checkTable(table);
|
|
1908
|
+
const track = this.tracking();
|
|
1909
|
+
if (track)
|
|
1910
|
+
for (const row of elements(table, 'w:tr'))
|
|
1911
|
+
this.markRowDeleted(row, track);
|
|
1912
|
+
else {
|
|
1913
|
+
const idx = this.index();
|
|
1914
|
+
const parent = idx.parentOf(table);
|
|
1915
|
+
parent.children.splice(indexOfChild(parent, table), 1);
|
|
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)
|
|
1918
|
+
parent.children.push(el('w:p'));
|
|
1919
|
+
if (parent === this.body && !elements(parent).some((c) => c.name === 'w:p' || c.name === 'w:tbl' || c.name === 'w:sdt')) {
|
|
1920
|
+
const sect = firstChild(parent, 'w:sectPr');
|
|
1921
|
+
parent.children.splice(sect ? parent.children.indexOf(sect) : parent.children.length, 0, el('w:p'));
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
this.changed();
|
|
1925
|
+
}
|
|
1926
|
+
markRowDeleted(row, track) {
|
|
1927
|
+
const idx = this.index();
|
|
1928
|
+
for (const run of findAll(row, 'w:r'))
|
|
1929
|
+
deleteRun(run, (n) => idx.parent.get(n), track.nextId, track.who);
|
|
1930
|
+
for (const p of findAll(row, 'w:p'))
|
|
1931
|
+
markParagraph(p, 'del', track.nextId(), track.who);
|
|
1932
|
+
markRow(row, 'del', track.nextId(), track.who);
|
|
1933
|
+
}
|
|
1206
1934
|
setParagraphStyle(paragraph, styleId) {
|
|
1207
1935
|
this.check('format', this.paragraphRange(paragraph));
|
|
1208
1936
|
const track = this.tracking();
|
|
@@ -1328,11 +2056,19 @@ export class DocxEditor {
|
|
|
1328
2056
|
return undefined;
|
|
1329
2057
|
}
|
|
1330
2058
|
if (sameListAs) {
|
|
1331
|
-
if (format !== undefined || start !== undefined)
|
|
1332
|
-
throw new EditError('sameListAs cannot be combined with format or start');
|
|
1333
2059
|
const target = all.get(sameListAs)?.numbering;
|
|
1334
2060
|
if (!target)
|
|
1335
|
-
throw new EditError('The paragraph to join is not in a list');
|
|
2061
|
+
throw new EditError('The paragraph to join is not in a list yet: make it one first (with a format), then join the others to it');
|
|
2062
|
+
if (start !== undefined)
|
|
2063
|
+
throw new EditError("sameListAs continues that list's numbering; to number from a given value, use start without sameListAs");
|
|
2064
|
+
if (format !== undefined) {
|
|
2065
|
+
// Naming the list's own format is harmless; another format would start a different list.
|
|
2066
|
+
const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
|
|
2067
|
+
const lvl = this.doc.numbering.level(target.numId, level ?? target.ilvl, styleNumId);
|
|
2068
|
+
if (!lvl || !levelMatches(lvl, format)) {
|
|
2069
|
+
throw new EditError(`That list is ${lvl ? describeLevel(lvl) : 'in another format'}; to continue it leave out format, or to start a new list use format without sameListAs`);
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
1336
2072
|
for (const p of paras)
|
|
1337
2073
|
this.writeNumPr(p, { numId: target.numId, ilvl: level ?? (p.numbering ? p.numbering.ilvl : target.ilvl) });
|
|
1338
2074
|
this.changed();
|
|
@@ -1432,6 +2168,7 @@ export class DocxEditor {
|
|
|
1432
2168
|
this.check('link');
|
|
1433
2169
|
if ('url' in target && !/^(https?|mailto|tel|ftp):/i.test(target.url))
|
|
1434
2170
|
throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
|
|
2171
|
+
this.dropStaleFallbacks([hyperlink]);
|
|
1435
2172
|
const old = hyperlink.attrs['r:id'];
|
|
1436
2173
|
if ('url' in target) {
|
|
1437
2174
|
hyperlink.attrs['r:id'] = await this.doc.pkg.addRelationship(this.part, REL.hyperlink, target.url, true);
|
|
@@ -1459,19 +2196,22 @@ export class DocxEditor {
|
|
|
1459
2196
|
}
|
|
1460
2197
|
await this.doc.refreshRels(this.part);
|
|
1461
2198
|
}
|
|
1462
|
-
/** 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`). */
|
|
1463
2200
|
setImageAlt(drawing, text) {
|
|
1464
|
-
this.check('edit');
|
|
1465
2201
|
const props = drawing.name === 'wp:docPr' ? drawing : findAll(drawing, 'wp:docPr')[0];
|
|
1466
2202
|
if (!props)
|
|
1467
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 } });
|
|
1468
2206
|
props.attrs['descr'] = text;
|
|
2207
|
+
dropFallback(node);
|
|
1469
2208
|
this.changed();
|
|
1470
2209
|
}
|
|
1471
2210
|
/** Unwrap a w:hyperlink, keeping its text. */
|
|
1472
2211
|
async removeHyperlink(link) {
|
|
1473
2212
|
this.check('link');
|
|
1474
2213
|
const idx = this.index();
|
|
2214
|
+
this.dropStaleFallbacks([link], idx);
|
|
1475
2215
|
const parent = idx.parentOf(link);
|
|
1476
2216
|
const runs = link.children;
|
|
1477
2217
|
for (const run of findAll(link, 'w:r')) {
|
|
@@ -1516,7 +2256,9 @@ export class DocxEditor {
|
|
|
1516
2256
|
return;
|
|
1517
2257
|
const id = attr(start, 'w:id');
|
|
1518
2258
|
const idx = this.index();
|
|
1519
|
-
|
|
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) {
|
|
1520
2262
|
const parent = idx.parentOf(node);
|
|
1521
2263
|
parent.children.splice(indexOfChild(parent, node), 1);
|
|
1522
2264
|
}
|
|
@@ -1680,6 +2422,7 @@ export class DocxEditor {
|
|
|
1680
2422
|
const region = this.lockedRegions().find((r) => r.id === id);
|
|
1681
2423
|
if (!region)
|
|
1682
2424
|
throw new EditError(`No locked region with id ${id}`);
|
|
2425
|
+
this.dropStaleFallbacks([region.el]);
|
|
1683
2426
|
if (region.tag === LOCK_TAG) {
|
|
1684
2427
|
const idx = this.index();
|
|
1685
2428
|
const parent = idx.parentOf(region.el);
|