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.
@@ -0,0 +1,574 @@
1
+ import { CONTENT_TYPE, REL } from '../opc/index.js';
2
+ import { attr, childPath, cloneElement, el, elements, findAll, firstChild, insertOrdered, NS, removeChildren, text, walk } from '../xml/index.js';
3
+ import { sectionProperties } from './headers.js';
4
+ import { EditError, TreeIndex } from './positions.js';
5
+ // ---------------------------------------------------------------------------------------------
6
+ // Listing
7
+ function kindOf(inline, vml) {
8
+ switch (inline.content?.type) {
9
+ case 'chart':
10
+ return 'chart';
11
+ case 'diagram':
12
+ return 'diagram';
13
+ case 'group':
14
+ return 'group';
15
+ case 'shape': {
16
+ // The reader only makes a VML shape of an old text box.
17
+ if (vml)
18
+ return 'textBox';
19
+ const flag = attr(childPath(inline.drawing, 'a:graphic', 'a:graphicData', 'wps:wsp', 'wps:cNvSpPr'), 'txBox');
20
+ return flag === '1' || flag === 'true' ? 'textBox' : 'shape';
21
+ }
22
+ default:
23
+ return 'picture';
24
+ }
25
+ }
26
+ /** The objects of some paragraphs, numbered from 1 (a group counts once, not per shape in it). */
27
+ export function listObjects(paragraphs) {
28
+ const out = [];
29
+ for (const paragraph of paragraphs) {
30
+ let idx;
31
+ for (const inline of paragraph.inlines) {
32
+ if (inline.kind !== 'image')
33
+ continue;
34
+ // The reader reads mc:Choice content through a stand-in run, so find the real one in the tree.
35
+ idx ??= new TreeIndex(paragraph.el);
36
+ const vml = inline.drawing.name === 'w:pict' || inline.drawing.name === 'w:object';
37
+ const drawing = vml ? inline.drawing : (idx.parent.get(inline.drawing) ?? inline.drawing);
38
+ const obj = {
39
+ n: out.length + 1,
40
+ kind: kindOf(inline, vml),
41
+ paragraph,
42
+ run: idx.ancestor(drawing, 'w:r') ?? inline.run,
43
+ drawing,
44
+ vml,
45
+ width: inline.width,
46
+ height: inline.height,
47
+ floating: inline.float !== undefined,
48
+ };
49
+ if (inline.alt)
50
+ obj.alt = inline.alt;
51
+ if (inline.content?.type === 'chart' && inline.content.part)
52
+ obj.chartPart = inline.content.part;
53
+ out.push(obj);
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+ // ---------------------------------------------------------------------------------------------
59
+ // Drawing XML
60
+ const emu = (pt) => String(Math.round(pt * 12700));
61
+ /** A w:drawing with an inline frame of `widthPt` × `heightPt` points around `graphicData`. */
62
+ export function inlineFrame(id, name, widthPt, heightPt, graphicData, alt) {
63
+ const docPr = { id: String(id), name };
64
+ if (alt)
65
+ docPr.descr = alt;
66
+ return el('w:drawing', {}, [
67
+ el('wp:inline', { distT: 0, distB: 0, distL: 0, distR: 0 }, [
68
+ el('wp:extent', { cx: emu(widthPt), cy: emu(heightPt) }),
69
+ el('wp:effectExtent', { l: 0, t: 0, r: 0, b: 0 }),
70
+ el('wp:docPr', docPr),
71
+ el('wp:cNvGraphicFramePr'),
72
+ el('a:graphic', { 'xmlns:a': NS.a }, [graphicData]),
73
+ ]),
74
+ ]);
75
+ }
76
+ /** Where a floating object sits: relativeFrom of wp:positionH and wp:positionV. */
77
+ const RELATIVE_FROM = { margin: ['margin', 'margin'], page: ['page', 'page'], paragraph: ['column', 'paragraph'] };
78
+ const WRAPS = ['square', 'topAndBottom', 'inFront', 'behind'];
79
+ /**
80
+ * Check a placement's position, reference and wrap style (EditError when wrong). x and y may be left
81
+ * out only for an object that already floats (`floating`), which keeps its own.
82
+ */
83
+ export function checkPlacement(place, floating = false) {
84
+ if ('inline' in place)
85
+ return;
86
+ for (const side of [place.x, place.y]) {
87
+ if (side === undefined ? !floating : !Number.isFinite(side))
88
+ throw new EditError('A floating object needs x and y in points');
89
+ }
90
+ if (place.from !== undefined && !Object.hasOwn(RELATIVE_FROM, place.from))
91
+ throw new EditError(`Place an object from the margin, page or paragraph, not "${place.from}"`);
92
+ if (place.wrap !== undefined && !WRAPS.includes(place.wrap))
93
+ throw new EditError(`Wrap text square, topAndBottom, inFront or behind, not "${place.wrap}"`);
94
+ }
95
+ /** The z-order for a new floating object: above every other one in `roots` (Word starts at 251659264). */
96
+ export function nextRelativeHeight(roots) {
97
+ let top = 0;
98
+ for (const root of roots)
99
+ for (const anchor of findAll(root, 'wp:anchor'))
100
+ top = Math.max(top, Number(attr(anchor, 'relativeHeight')) || 0);
101
+ return Math.max(top + 1, 251659264);
102
+ }
103
+ /** wp:anchor's children in schema order (wp14 relative sizes last). */
104
+ const ANCHOR_ORDER = [
105
+ 'wp:simplePos', 'wp:positionH', 'wp:positionV', 'wp:extent', 'wp:effectExtent', 'wp:wrapNone', 'wp:wrapSquare', 'wp:wrapTight', 'wp:wrapThrough', 'wp:wrapTopAndBottom',
106
+ 'wp:docPr', 'wp:cNvGraphicFramePr', 'a:graphic', 'wp14:sizeRelH', 'wp14:sizeRelV',
107
+ ];
108
+ const WRAP_ELEMENTS = new Set(['wp:wrapNone', 'wp:wrapSquare', 'wp:wrapTight', 'wp:wrapThrough', 'wp:wrapTopAndBottom']);
109
+ const wrapElement = (wrap) => wrap === 'square' ? el('wp:wrapSquare', { wrapText: 'bothSides' }) : wrap === 'topAndBottom' ? el('wp:wrapTopAndBottom') : el('wp:wrapNone');
110
+ const positionElement = (axis, relativeFrom, offset) => el(`wp:position${axis}`, { relativeFrom }, [el('wp:posOffset', {}, [text(emu(offset))])]);
111
+ const optional = (e) => (e ? [e] : []);
112
+ /** A wp:anchor around `parts` at `place` (from the paragraph and square wrap by default), at z-order `relativeHeight`. */
113
+ function anchorOf(parts, place, relativeHeight, attrs = {}) {
114
+ checkPlacement(place);
115
+ const [h, v] = RELATIVE_FROM[place.from ?? 'paragraph'];
116
+ const wrap = place.wrap ?? 'square';
117
+ const frame = { ...attrs, distT: 0, distB: 0, distL: 114300, distR: 114300, simplePos: 0, relativeHeight, behindDoc: wrap === 'behind' ? 1 : 0, locked: 0, layoutInCell: 1, allowOverlap: 1 };
118
+ return el('wp:anchor', frame, [
119
+ el('wp:simplePos', { x: 0, y: 0 }),
120
+ positionElement('H', h, place.x),
121
+ positionElement('V', v, place.y),
122
+ parts.extent,
123
+ ...optional(parts.effectExtent),
124
+ wrapElement(wrap),
125
+ parts.docPr,
126
+ ...optional(parts.cNvGraphicFramePr),
127
+ parts.graphic,
128
+ ]);
129
+ }
130
+ /**
131
+ * A w:drawing with a floating frame (wp:anchor) of `widthPt` × `heightPt` points around
132
+ * `graphicData`, at `place` (from the paragraph by default, square wrap by default) and at z-order
133
+ * `relativeHeight`.
134
+ */
135
+ export function anchorFrame(id, name, widthPt, heightPt, place, graphicData, alt, relativeHeight) {
136
+ const docPr = { id: String(id), name };
137
+ if (alt)
138
+ docPr.descr = alt;
139
+ const parts = {
140
+ extent: el('wp:extent', { cx: emu(widthPt), cy: emu(heightPt) }),
141
+ effectExtent: el('wp:effectExtent', { l: 0, t: 0, r: 0, b: 0 }),
142
+ docPr: el('wp:docPr', docPr),
143
+ cNvGraphicFramePr: el('wp:cNvGraphicFramePr'),
144
+ graphic: el('a:graphic', { 'xmlns:a': NS.a }, [graphicData]),
145
+ };
146
+ return el('w:drawing', {}, [anchorOf(parts, place, relativeHeight)]);
147
+ }
148
+ /** The graphic of a chart whose part the relationship `relId` points at. */
149
+ export function chartGraphic(relId) {
150
+ return el('a:graphicData', { uri: 'http://schemas.openxmlformats.org/drawingml/2006/chart' }, [el('c:chart', { 'xmlns:c': NS.c, 'xmlns:r': NS.r, 'r:id': relId })]);
151
+ }
152
+ // ---------------------------------------------------------------------------------------------
153
+ // Changing objects
154
+ /** The frame (wp:inline or wp:anchor) of an object's w:drawing. */
155
+ export function frameOf(drawing) {
156
+ const frame = elements(drawing).find((e) => e.name === 'wp:inline' || e.name === 'wp:anchor');
157
+ if (!frame)
158
+ throw new EditError('This object has no frame to change');
159
+ return frame;
160
+ }
161
+ function partsOf(frame) {
162
+ const [extent, docPr, graphic] = ['wp:extent', 'wp:docPr', 'a:graphic'].map((n) => firstChild(frame, n));
163
+ if (!extent || !docPr || !graphic)
164
+ throw new EditError('This object is missing part of its frame');
165
+ return { extent, effectExtent: firstChild(frame, 'wp:effectExtent'), docPr, cNvGraphicFramePr: firstChild(frame, 'wp:cNvGraphicFramePr'), graphic };
166
+ }
167
+ /** The namespace declarations on an element, kept when its frame is rebuilt. */
168
+ function declarations(e) {
169
+ return Object.fromEntries(Object.entries(e.attrs).filter(([k]) => k === 'xmlns' || k.startsWith('xmlns:')));
170
+ }
171
+ /**
172
+ * Word's old VML copy of an object (the mc:Fallback beside its mc:Choice) is stale once the
173
+ * object changes, so it goes. `node` is the run's child holding the object.
174
+ */
175
+ export function dropFallback(node) {
176
+ if (node.name === 'mc:AlternateContent')
177
+ removeChildren(node, 'mc:Fallback');
178
+ }
179
+ /** An object's new size in points: as given, or with one side given, the other keeps the frame's proportions. */
180
+ export function resized(frame, size) {
181
+ const { width, height } = size;
182
+ if (width === undefined && height === undefined)
183
+ throw new EditError('Give a new width, height or both');
184
+ for (const side of [width, height]) {
185
+ if (side !== undefined && !(side > 0 && Number.isFinite(side)))
186
+ throw new EditError('An object needs a positive width and height');
187
+ }
188
+ const extent = firstChild(frame, 'wp:extent');
189
+ const cx = Number(attr(extent, 'cx')) || 0;
190
+ const cy = Number(attr(extent, 'cy')) || 0;
191
+ if (width !== undefined)
192
+ return { width, height: height ?? (cx > 0 ? (cy * width) / cx : cy / 12700) };
193
+ return { width: cy > 0 ? (cx * height) / cy : cx / 12700, height: height };
194
+ }
195
+ /** Size a frame to `widthPt` × `heightPt`, with the picture, shape or group in it (a group's children scale with it). */
196
+ export function resizeFrame(frame, widthPt, heightPt) {
197
+ const size = { cx: emu(widthPt), cy: emu(heightPt) };
198
+ const extent = firstChild(frame, 'wp:extent');
199
+ if (!extent)
200
+ throw new EditError('This object has no size to change');
201
+ Object.assign(extent.attrs, size);
202
+ // A size relative to the page or margin would win over the new one.
203
+ removeChildren(frame, 'wp14:sizeRelH');
204
+ removeChildren(frame, 'wp14:sizeRelV');
205
+ const graphicData = childPath(frame, 'a:graphic', 'a:graphicData');
206
+ for (const content of graphicData ? elements(graphicData) : []) {
207
+ const props = firstChild(content, 'pic:spPr') ?? firstChild(content, 'wps:spPr') ?? firstChild(content, 'wpg:grpSpPr');
208
+ const ext = childPath(props, 'a:xfrm', 'a:ext');
209
+ if (ext)
210
+ Object.assign(ext.attrs, size);
211
+ }
212
+ }
213
+ /**
214
+ * Move a floating frame to `place`. Without `from` or `wrap` it keeps its own; a side without an
215
+ * offset (x or y) keeps its own offset or alignment, counted from `from` when that is given. A
216
+ * position Word stored as a percentage (wp14, inside mc:AlternateContent) is replaced when a new
217
+ * offset is given.
218
+ */
219
+ function moveAnchor(anchor, place) {
220
+ const holds = (c, name) => c.name === name || (c.name === 'mc:AlternateContent' && findAll(c, name).length > 0);
221
+ // The frame's own position elements: its child, or the ones in an mc:AlternateContent child.
222
+ const positions = (name) => elements(anchor).flatMap((c) => (c.name === name ? [c] : c.name === 'mc:AlternateContent' ? findAll(c, name) : []));
223
+ const sides = [
224
+ ['H', place.x, 0, 'column'],
225
+ ['V', place.y, 1, 'paragraph'],
226
+ ];
227
+ for (const [axis, offset, i, fallback] of sides) {
228
+ const name = `wp:position${axis}`;
229
+ const from = place.from ? RELATIVE_FROM[place.from][i] : undefined;
230
+ if (offset === undefined) {
231
+ if (from)
232
+ for (const position of positions(name))
233
+ position.attrs.relativeFrom = from;
234
+ continue;
235
+ }
236
+ const relativeFrom = from ?? attr(positions(name)[0], 'relativeFrom') ?? fallback;
237
+ // The new position goes where the old one was: the other side may be in an mc:AlternateContent,
238
+ // which ANCHOR_ORDER can't place.
239
+ const at = anchor.children.findIndex((c) => c.type === 'element' && holds(c, name));
240
+ anchor.children = anchor.children.filter((c) => !(c.type === 'element' && holds(c, name)));
241
+ const position = positionElement(axis, relativeFrom, offset);
242
+ if (at < 0)
243
+ insertOrdered(anchor, position, ANCHOR_ORDER);
244
+ else
245
+ anchor.children.splice(at, 0, position);
246
+ // simplePos="1" would place it at wp:simplePos instead.
247
+ anchor.attrs.simplePos = '0';
248
+ }
249
+ if (place.wrap) {
250
+ anchor.children = anchor.children.filter((c) => !(c.type === 'element' && WRAP_ELEMENTS.has(c.name)));
251
+ insertOrdered(anchor, wrapElement(place.wrap), ANCHOR_ORDER);
252
+ anchor.attrs.behindDoc = place.wrap === 'behind' ? '1' : '0';
253
+ }
254
+ }
255
+ /**
256
+ * Place an object's w:drawing inline, or floating at `place`: an inline frame becomes a wp:anchor
257
+ * (at z-order `relativeHeight()`, from the paragraph and square wrap by default) around the same
258
+ * docPr, extent and graphic, and back; a floating one moves (see `moveAnchor`).
259
+ */
260
+ export function placeFrame(drawing, place, relativeHeight) {
261
+ const frame = frameOf(drawing);
262
+ checkPlacement(place, frame.name === 'wp:anchor');
263
+ let next;
264
+ if ('inline' in place) {
265
+ if (frame.name === 'wp:inline')
266
+ return;
267
+ const parts = partsOf(frame);
268
+ next = el('wp:inline', { ...declarations(frame), distT: 0, distB: 0, distL: 0, distR: 0 }, [
269
+ parts.extent,
270
+ ...optional(parts.effectExtent),
271
+ parts.docPr,
272
+ ...optional(parts.cNvGraphicFramePr),
273
+ parts.graphic,
274
+ ]);
275
+ }
276
+ else if (frame.name === 'wp:inline') {
277
+ next = anchorOf(partsOf(frame), place, relativeHeight(), declarations(frame));
278
+ }
279
+ else {
280
+ moveAnchor(frame, place);
281
+ return;
282
+ }
283
+ drawing.children[drawing.children.indexOf(frame)] = next;
284
+ }
285
+ /**
286
+ * A copy of an object: of `node`, the run's child holding it (a w:drawing, or the
287
+ * mc:AlternateContent around one), without Word's old VML copy; and the w:drawing in the copy that
288
+ * stands where `drawing` stands in the original.
289
+ */
290
+ export function cloneObject(idx, node, drawing) {
291
+ const path = [];
292
+ for (let cur = drawing; cur !== node; cur = idx.parentOf(cur))
293
+ path.unshift(idx.parentOf(cur).children.indexOf(cur));
294
+ const copy = cloneElement(node);
295
+ let found = copy;
296
+ for (const i of path)
297
+ found = found.children[i];
298
+ dropFallback(copy);
299
+ return { copy, drawing: found };
300
+ }
301
+ const RUN_REVISIONS = new Set(['w:ins', 'w:del', 'w:moveFrom', 'w:moveTo']);
302
+ /** Take an object's run child out of its run; a run (and a tracked change around it) left empty goes too. */
303
+ export function takeOut(idx, node) {
304
+ let parent = idx.parentOf(node);
305
+ parent.children.splice(parent.children.indexOf(node), 1);
306
+ const empty = (e) => !e.children.some((c) => c.type === 'element' && c.name !== 'w:rPr');
307
+ for (let cur = parent; (cur.name === 'w:r' || RUN_REVISIONS.has(cur.name)) && empty(cur); cur = parent) {
308
+ parent = idx.parentOf(cur);
309
+ parent.children.splice(parent.children.indexOf(cur), 1);
310
+ }
311
+ }
312
+ // ---------------------------------------------------------------------------------------------
313
+ // Shapes and text boxes
314
+ /** Word's names for new shapes (the wp:docPr name, before the drawing id). */
315
+ export const SHAPE_NAMES = {
316
+ textBox: 'Text Box',
317
+ rect: 'Rectangle',
318
+ roundRect: 'Rectangle: Rounded Corners',
319
+ ellipse: 'Oval',
320
+ triangle: 'Isosceles Triangle',
321
+ diamond: 'Diamond',
322
+ rightArrow: 'Arrow: Right',
323
+ leftArrow: 'Arrow: Left',
324
+ upArrow: 'Arrow: Up',
325
+ downArrow: 'Arrow: Down',
326
+ chevron: 'Arrow: Chevron',
327
+ pentagon: 'Regular Pentagon',
328
+ star5: 'Star: 5 Points',
329
+ wedgeRectCallout: 'Speech Bubble: Rectangle',
330
+ wedgeRoundRectCallout: 'Speech Bubble: Rectangle with Corners Rounded',
331
+ cloudCallout: 'Thought Bubble: Cloud',
332
+ line: 'Straight Connector',
333
+ };
334
+ /** Whether an object's w:drawing holds a picture (pic:pic), not a chart, diagram, canvas or a graphic docxkeun doesn't know. */
335
+ export function isPicture(drawing) {
336
+ const frame = elements(drawing).find((e) => e.name === 'wp:inline' || e.name === 'wp:anchor');
337
+ return childPath(frame, 'a:graphic', 'a:graphicData', 'pic:pic') !== undefined;
338
+ }
339
+ /** Whether a node sits inside a text box (DrawingML or VML: both keep their text in w:txbxContent). */
340
+ export function inTextBox(idx, node) {
341
+ return idx.ancestor(node, 'w:txbxContent') !== undefined;
342
+ }
343
+ /** A colour option: RRGGBB (a leading # is fine) or 'none'. */
344
+ function checkColour(value, what) {
345
+ if (value !== undefined && value !== 'none' && !/^#?[0-9A-Fa-f]{6}$/.test(value))
346
+ throw new EditError(`A ${what} colour is RRGGBB (like 4472C4) or "none", not "${value}"`);
347
+ }
348
+ /**
349
+ * Check a new shape's options (EditError when wrong) and fill in its size and placement: a text box
350
+ * is 180 × 72 pt, a line 144 × 0 pt, other shapes 108 × 72 pt; by default it floats at the top left
351
+ * of its paragraph.
352
+ */
353
+ export function checkShape(shape) {
354
+ if (!Object.hasOwn(SHAPE_NAMES, shape.shape))
355
+ throw new EditError(`Unknown shape "${shape.shape}"`);
356
+ const line = shape.shape === 'line';
357
+ if (line && shape.text)
358
+ throw new EditError('A line cannot hold text');
359
+ const [w, h] = shape.shape === 'textBox' ? [180, 72] : line ? [144, 0] : [108, 72];
360
+ const width = shape.width ?? w;
361
+ const height = shape.height ?? h;
362
+ // A line may be flat in one direction, not both; other shapes need both sides.
363
+ const sized = (n) => Number.isFinite(n) && (line ? n >= 0 : n > 0);
364
+ if (!sized(width) || !sized(height) || width + height === 0)
365
+ throw new EditError(line ? 'A line needs a length' : 'A shape needs a positive width and height');
366
+ checkColour(shape.fill, 'fill');
367
+ checkColour(shape.outline, 'outline');
368
+ const place = shape.place ?? { x: 0, y: 0 };
369
+ checkPlacement(place);
370
+ return { width, height, place };
371
+ }
372
+ const solid = (colour) => el('a:solidFill', {}, [el('a:srgbClr', { val: colour.replace(/^#/, '').toUpperCase() })]);
373
+ /**
374
+ * The graphic of a new shape (wps:wsp) of `widthPt` × `heightPt` points, holding `shape.text` (each
375
+ * line a paragraph, each run made by `newRun`). A text box is white with a thin black outline and
376
+ * top-aligned text; other shapes take the theme's accent 1 with a darker outline (wps:style) and
377
+ * white, centred text; `fill` and `outline` override either.
378
+ */
379
+ export function shapeGraphic(shape, widthPt, heightPt, newRun) {
380
+ const box = shape.shape === 'textBox';
381
+ const line = shape.shape === 'line';
382
+ const spPr = el('wps:spPr', {}, [
383
+ el('a:xfrm', {}, [el('a:off', { x: 0, y: 0 }), el('a:ext', { cx: emu(widthPt), cy: emu(heightPt) })]),
384
+ el('a:prstGeom', { prst: box ? 'rect' : shape.shape }, [el('a:avLst')]),
385
+ ]);
386
+ const fill = shape.fill ?? (box ? 'FFFFFF' : undefined);
387
+ if (fill !== undefined)
388
+ spPr.children.push(fill === 'none' ? el('a:noFill') : solid(fill));
389
+ const outline = shape.outline ?? (box ? '000000' : undefined);
390
+ // A shape's own outline keeps the style's width.
391
+ if (outline !== undefined)
392
+ spPr.children.push(el('a:ln', { w: box ? 9525 : undefined }, [outline === 'none' ? el('a:noFill') : solid(outline)]));
393
+ const children = [line ? el('wps:cNvCnPr') : el('wps:cNvSpPr', { txBox: box ? 1 : undefined }), spPr];
394
+ if (!box) {
395
+ const scheme = (...transforms) => el('a:schemeClr', { val: 'accent1' }, transforms);
396
+ children.push(el('wps:style', {}, [
397
+ el('a:lnRef', { idx: 2 }, [scheme(el('a:shade', { val: 50000 }))]),
398
+ el('a:fillRef', { idx: 1 }, [scheme()]),
399
+ el('a:effectRef', { idx: 0 }, [scheme()]),
400
+ el('a:fontRef', { idx: 'minor' }, [el('a:schemeClr', { val: 'lt1' })]),
401
+ ]));
402
+ }
403
+ if (box || shape.text) {
404
+ // An empty text box still has a paragraph to type in.
405
+ const lines = (shape.text ?? '').split(/\r?\n/);
406
+ const paragraphs = lines.map((t) => box ? el('w:p', {}, t ? [newRun(t)] : []) : el('w:p', {}, [el('w:pPr', {}, [el('w:jc', { 'w:val': 'center' })]), ...(t ? [newRun(t, { color: 'FFFFFF' })] : [])]));
407
+ children.push(el('wps:txbx', {}, [el('w:txbxContent', {}, paragraphs)]));
408
+ }
409
+ children.push(el('wps:bodyPr', { rot: 0, vert: 'horz', wrap: 'square', lIns: 91440, tIns: 45720, rIns: 91440, bIns: 45720, anchor: box ? 't' : 'ctr', anchorCtr: 0 }, [el('a:noAutofit')]));
410
+ return el('a:graphicData', { uri: 'http://schemas.microsoft.com/office/word/2010/wordprocessingShape' }, [el('wps:wsp', {}, children)]);
411
+ }
412
+ /** The w:sectPr of the section holding `node`: the next paragraph section break, or the body's own. */
413
+ export function sectionAt(body, idx, node) {
414
+ const sections = sectionProperties(body);
415
+ const at = idx.order.get(node);
416
+ if (at === undefined)
417
+ return sections[sections.length - 1];
418
+ for (const sectPr of sections) {
419
+ const paragraph = idx.ancestor(sectPr, 'w:p');
420
+ if (!paragraph)
421
+ return sectPr;
422
+ let last = paragraph;
423
+ for (let c = elements(last).at(-1); c; c = elements(last).at(-1))
424
+ last = c;
425
+ if (at <= idx.order.get(last))
426
+ return sectPr;
427
+ }
428
+ return sections[sections.length - 1];
429
+ }
430
+ const CHART_WIDTH = 432;
431
+ const CHART_HEIGHT = 252;
432
+ /** A new chart's size in points: as given (one side keeps Word's 432 × 252 proportions), else Word's default shrunk to `maxWidth`. */
433
+ export function chartSize(size, maxWidth) {
434
+ for (const side of [size.width, size.height]) {
435
+ if (side !== undefined && !(side > 0 && Number.isFinite(side)))
436
+ throw new EditError('A chart needs a positive width and height');
437
+ }
438
+ const { width, height } = size;
439
+ if (width !== undefined)
440
+ return { width, height: height ?? (width * CHART_HEIGHT) / CHART_WIDTH };
441
+ if (height !== undefined)
442
+ return { width: (height * CHART_WIDTH) / CHART_HEIGHT, height };
443
+ const scale = Math.min(1, maxWidth / CHART_WIDTH);
444
+ return { width: CHART_WIDTH * scale, height: CHART_HEIGHT * scale };
445
+ }
446
+ // ---------------------------------------------------------------------------------------------
447
+ // Chart parts
448
+ /** `{base}{n}{ext}` with the lowest n from 1 that no part has. */
449
+ export function freePartName(pkg, base, ext) {
450
+ let n = 1;
451
+ while (pkg.has(`${base}${n}${ext}`))
452
+ n++;
453
+ return `${base}${n}${ext}`;
454
+ }
455
+ /** Store a new embedded workbook and relate it to a chart part; returns the relationship id. */
456
+ export async function addWorkbook(pkg, chartPart, bytes) {
457
+ const name = freePartName(pkg, 'word/embeddings/Microsoft_Excel_Worksheet', '.xlsx');
458
+ pkg.setDefaultContentType('xlsx', CONTENT_TYPE.xlsx);
459
+ pkg.setBytes(name, bytes);
460
+ return pkg.addRelationship(chartPart, REL.package, name);
461
+ }
462
+ /** The chart part and its c:chartSpace behind a chart object. */
463
+ export function chartOf(doc, obj) {
464
+ if (obj.kind !== 'chart')
465
+ throw new EditError(`Object ${obj.n} is ${obj.kind === 'textBox' ? 'a text box' : `a ${obj.kind}`}, not a chart`);
466
+ const root = obj.chartPart ? doc.xmlSync(obj.chartPart)?.root : undefined;
467
+ if (!obj.chartPart || root?.name !== 'c:chartSpace')
468
+ throw new EditError(`The data of chart ${obj.n} is missing from the file`);
469
+ return { part: obj.chartPart, chartSpace: root };
470
+ }
471
+ const PLOT_TYPES = { 'c:lineChart': 'line', 'c:areaChart': 'area', 'c:pieChart': 'pie', 'c:doughnutChart': 'doughnut', 'c:scatterChart': 'scatter' };
472
+ /** The new-chart type of a chart's first plot (undefined for kinds new charts can't have), and its stacking. */
473
+ export function chartKind(chartSpace) {
474
+ const plotArea = childPath(chartSpace, 'c:chart', 'c:plotArea');
475
+ const plot = plotArea ? elements(plotArea).find((e) => e.name.endsWith('Chart')) : undefined;
476
+ if (!plot)
477
+ return { type: undefined, stacked: undefined };
478
+ const type = plot.name === 'c:barChart' ? (attr(firstChild(plot, 'c:barDir'), 'val') === 'bar' ? 'bar' : 'column') : PLOT_TYPES[plot.name];
479
+ // Only column, bar and area charts stack as far as new data is concerned (a stacked line is still a line).
480
+ if (type !== 'column' && type !== 'bar' && type !== 'area')
481
+ return { type, stacked: undefined };
482
+ const grouping = attr(firstChild(plot, 'c:grouping'), 'val');
483
+ return { type, stacked: grouping === 'stacked' ? 'stacked' : grouping === 'percentStacked' ? 'percent' : undefined };
484
+ }
485
+ /**
486
+ * Where a chart's data lives (its c:externalData relationship): an outside file ('linked'), a part
487
+ * in the package ('embedded'; `workbook` is set when that part is an .xlsx package that can be
488
+ * rewritten, not an old OLE object), or nowhere.
489
+ */
490
+ export function chartData(doc, chartPart, chartSpace) {
491
+ const relId = attr(firstChild(chartSpace, 'c:externalData'), 'r:id');
492
+ const rel = relId === undefined ? undefined : doc.rels(chartPart).get(relId);
493
+ if (!rel)
494
+ return { source: 'none', relId, workbook: undefined };
495
+ if (rel.external)
496
+ return { source: 'linked', relId, workbook: undefined };
497
+ if (!doc.pkg.has(rel.target))
498
+ return { source: 'none', relId, workbook: undefined };
499
+ return { source: 'embedded', relId, workbook: doc.pkg.contentType(rel.target) === CONTENT_TYPE.xlsx ? rel.target : undefined };
500
+ }
501
+ const CHARTSPACE_ORDER = [
502
+ 'c:date1904', 'c:lang', 'c:roundedCorners', 'mc:AlternateContent', 'c:style', 'c:clrMapOvr', 'c:pivotSource', 'c:protection', 'c:chart', 'c:spPr', 'c:txPr',
503
+ 'c:externalData', 'c:printSettings', 'c:userShapes', 'c:extLst',
504
+ ];
505
+ /**
506
+ * Give a chart a new embedded .xlsx workbook in place of the data source it had (an old OLE object,
507
+ * a missing part, or none), pointing its c:externalData at it.
508
+ */
509
+ export async function replaceWorkbook(doc, chartPart, chartSpace, oldRelId, bytes) {
510
+ const { pkg } = doc;
511
+ const relId = await addWorkbook(pkg, chartPart, bytes);
512
+ const old = oldRelId === undefined ? undefined : await pkg.relationshipById(chartPart, oldRelId);
513
+ if (old) {
514
+ await pkg.removeRelationship(chartPart, old.id);
515
+ const target = pkg.resolve(chartPart, old);
516
+ if (!old.external && pkg.has(target))
517
+ pkg.removePart(target);
518
+ }
519
+ let externalData = firstChild(chartSpace, 'c:externalData');
520
+ if (!externalData) {
521
+ externalData = el('c:externalData', {}, [el('c:autoUpdate', { val: 0 })]);
522
+ insertOrdered(chartSpace, externalData, CHARTSPACE_ORDER);
523
+ }
524
+ externalData.attrs['r:id'] = relId;
525
+ if (chartSpace.attrs['xmlns:r'] === undefined)
526
+ chartSpace.attrs['xmlns:r'] = NS.r;
527
+ await doc.refreshRels(chartPart);
528
+ }
529
+ /**
530
+ * Copy a part and the parts its relationships point to inside the package (a chart's workbook,
531
+ * styles and colours), so the copy shares nothing it could change; pictures are shared. References
532
+ * to relationships (r:id, r:embed, …) in the copied XML are renumbered to the copy's. Returns the
533
+ * copy's name.
534
+ */
535
+ export async function copyPart(pkg, name, copies = new Map()) {
536
+ const done = copies.get(name);
537
+ if (done)
538
+ return done;
539
+ // chart1.xml → chartN.xml, Microsoft_Excel_Worksheet.xlsx → Microsoft_Excel_WorksheetN.xlsx.
540
+ const [, base = name, ext = ''] = /^(.*?)\d*(\.[^./]*)?$/.exec(name) ?? [];
541
+ const copy = freePartName(pkg, base, ext);
542
+ copies.set(name, copy);
543
+ const type = pkg.contentType(name);
544
+ const isXml = type !== undefined && /[+/]xml$/.test(type);
545
+ let root;
546
+ if (isXml) {
547
+ const xml = await pkg.getXml(name);
548
+ root = cloneElement(xml.root);
549
+ pkg.setXml(copy, { declaration: xml.declaration, prolog: [...xml.prolog], root, epilog: [...xml.epilog] }, type);
550
+ }
551
+ else {
552
+ pkg.setBytes(copy, (await pkg.getBytes(name)).slice(), type);
553
+ }
554
+ const ids = new Map();
555
+ for (const rel of [...(await pkg.relationships(name))]) {
556
+ let target = rel.target;
557
+ if (!rel.external) {
558
+ target = pkg.resolve(name, rel);
559
+ if (pkg.has(target) && !pkg.contentType(target)?.startsWith('image/'))
560
+ target = await copyPart(pkg, target, copies);
561
+ }
562
+ ids.set(rel.id, await pkg.addRelationship(copy, rel.type, target, rel.external));
563
+ }
564
+ if (root && ids.size > 0) {
565
+ walk(root, (e) => {
566
+ for (const [key, value] of Object.entries(e.attrs)) {
567
+ const id = key.startsWith('r:') ? ids.get(value) : undefined;
568
+ if (id !== undefined)
569
+ e.attrs[key] = id;
570
+ }
571
+ });
572
+ }
573
+ return copy;
574
+ }
@@ -310,6 +310,17 @@ function joinWithNext(p, para) {
310
310
  p.parent.set(c, next);
311
311
  parent.children.splice(i, 1);
312
312
  }
313
+ /** Remove a table row; a table left without rows goes too (a cell that held it keeps a paragraph). */
314
+ function removeRow(p, row) {
315
+ const table = p.parent.get(row);
316
+ remove(p, row);
317
+ if (!table || elements(table, 'w:tr').length)
318
+ return;
319
+ const holder = p.parent.get(table);
320
+ remove(p, table);
321
+ if (holder?.name === 'w:tc' && !elements(holder, 'w:p').length)
322
+ holder.children.push(el('w:p'));
323
+ }
313
324
  function restoreProperties(p, change) {
314
325
  const owner = p.parent.get(change);
315
326
  if (!owner)
@@ -362,14 +373,14 @@ function apply(root, filter, accept) {
362
373
  const row = p.parent.get(p.parent.get(node));
363
374
  remove(p, node);
364
375
  if (!accept && row)
365
- remove(p, row);
376
+ removeRow(p, row);
366
377
  break;
367
378
  }
368
379
  case 'row-delete': {
369
380
  const row = p.parent.get(p.parent.get(node));
370
381
  remove(p, node);
371
382
  if (accept && row)
372
- remove(p, row);
383
+ removeRow(p, row);
373
384
  break;
374
385
  }
375
386
  }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Building blocks for DocxEditor's table and copy operations: a new table's XML, cleaning a copied
3
+ * block so it can live next to its original, and marking new content as a tracked insertion.
4
+ */
5
+ import { type XmlElement } from '../xml/index.js';
6
+ import { type RevisionAuthor } from './revisions.js';
7
+ /** Options for a new table. */
8
+ export interface TableOptions {
9
+ /** The first row is a header: bold, and repeated at the top of each page the table runs onto. */
10
+ header?: boolean;
11
+ /** Relative column widths (e.g. [1, 3, 1]); default: equal. The table spans the text width. */
12
+ widths?: number[];
13
+ /** Grid borders (default true). Ignored when `style` is given. */
14
+ borders?: boolean;
15
+ /** The table's position between the margins (default left). */
16
+ align?: 'left' | 'center' | 'right';
17
+ /** A table style id; default: Word's "Table Grid" when the document has it. */
18
+ style?: string;
19
+ }
20
+ /**
21
+ * A new table (w:tbl). `widths` are the columns' widths in twips; `paragraph` makes a cell's
22
+ * paragraph for one line of text (lines come from "\n" in the cell text).
23
+ */
24
+ export declare function buildTable(rows: string[][], widths: number[], o: {
25
+ header: boolean;
26
+ style: string | undefined;
27
+ borders: boolean;
28
+ align: TableOptions['align'];
29
+ paragraph: (text: string, header: boolean) => XmlElement;
30
+ }): XmlElement;
31
+ /** Column widths in twips: `weights` (default equal) scaled to fill `total`. */
32
+ export declare function columnWidths(columns: number, total: number, weights?: number[]): number[];
33
+ /** What a copy left out because it can only exist once in a document. */
34
+ export interface CopyDropped {
35
+ /** Comment anchors (the comments stay on the original). */
36
+ comments: number;
37
+ /** Footnote and endnote references. */
38
+ notes: number;
39
+ /** Bookmarks (their names must be unique; links keep pointing at the original). */
40
+ bookmarks: number;
41
+ }
42
+ /** Fresh ids for the copy's elements that must be unique in the document. */
43
+ export interface CopyIds {
44
+ revision: () => string;
45
+ drawing: () => string;
46
+ sdt: () => string;
47
+ }
48
+ /**
49
+ * Make a cloned block fit to sit next to its original: drop what may exist only once (bookmarks,
50
+ * comment anchors, note references, editable-range markers, a paragraph's section break), give
51
+ * drawings, content controls and tracked changes new ids, and drop Word's paragraph ids.
52
+ */
53
+ export declare function cleanCopy(node: XmlElement, ids: CopyIds, dropped: CopyDropped): void;
54
+ /** Mark a table row inserted or deleted (w:trPr/w:ins or w:del). */
55
+ export declare function markRow(row: XmlElement, kind: 'ins' | 'del', id: string, who: RevisionAuthor): void;
56
+ /**
57
+ * Mark new content (a paragraph, a table, a row) as a tracked insertion by `who`: its runs, its
58
+ * paragraph marks and its table rows. `markParagraph` marks one paragraph mark.
59
+ */
60
+ export declare function markInserted(node: XmlElement, nextId: () => string, who: RevisionAuthor, markParagraph: (p: XmlElement) => void): void;