docxkeun 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +139 -16
  3. package/dist/api/editor.d.ts +172 -5
  4. package/dist/api/editor.js +814 -24
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +5 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +390 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/charts/color.d.ts +45 -0
  18. package/dist/charts/color.js +322 -0
  19. package/dist/charts/format.d.ts +12 -0
  20. package/dist/charts/format.js +459 -0
  21. package/dist/charts/index.d.ts +11 -0
  22. package/dist/charts/index.js +8 -0
  23. package/dist/charts/model.d.ts +225 -0
  24. package/dist/charts/model.js +758 -0
  25. package/dist/charts/outline.d.ts +17 -0
  26. package/dist/charts/outline.js +214 -0
  27. package/dist/charts/render.d.ts +20 -0
  28. package/dist/charts/render.js +1772 -0
  29. package/dist/drawing/arrows.d.ts +37 -0
  30. package/dist/drawing/arrows.js +99 -0
  31. package/dist/drawing/formula.d.ts +40 -0
  32. package/dist/drawing/formula.js +159 -0
  33. package/dist/drawing/geometry.d.ts +61 -0
  34. package/dist/drawing/geometry.js +286 -0
  35. package/dist/drawing/index.d.ts +12 -0
  36. package/dist/drawing/index.js +8 -0
  37. package/dist/drawing/presets.d.ts +72 -0
  38. package/dist/drawing/presets.js +2874 -0
  39. package/dist/fonts/shaping/apply.d.ts +94 -0
  40. package/dist/fonts/shaping/apply.js +349 -0
  41. package/dist/fonts/shaping/arabic.d.ts +28 -0
  42. package/dist/fonts/shaping/arabic.js +235 -0
  43. package/dist/fonts/shaping/buffer.d.ts +53 -0
  44. package/dist/fonts/shaping/buffer.js +95 -0
  45. package/dist/fonts/shaping/gdef.d.ts +30 -0
  46. package/dist/fonts/shaping/gdef.js +66 -0
  47. package/dist/fonts/shaping/gpos.d.ts +86 -0
  48. package/dist/fonts/shaping/gpos.js +428 -0
  49. package/dist/fonts/shaping/gsub.d.ts +65 -0
  50. package/dist/fonts/shaping/gsub.js +313 -0
  51. package/dist/fonts/shaping/index.d.ts +32 -0
  52. package/dist/fonts/shaping/index.js +402 -0
  53. package/dist/fonts/shaping/indic.d.ts +6 -0
  54. package/dist/fonts/shaping/indic.js +805 -0
  55. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  56. package/dist/fonts/shaping/layout-common.js +349 -0
  57. package/dist/fonts/shaping/plan.d.ts +87 -0
  58. package/dist/fonts/shaping/plan.js +152 -0
  59. package/dist/fonts/shaping/scripts.d.ts +26 -0
  60. package/dist/fonts/shaping/scripts.js +160 -0
  61. package/dist/fonts/shaping/shaper.d.ts +23 -0
  62. package/dist/fonts/shaping/shaper.js +5 -0
  63. package/dist/fonts/shaping/unicode.d.ts +34 -0
  64. package/dist/fonts/shaping/unicode.js +138 -0
  65. package/dist/images/bmp.d.ts +9 -0
  66. package/dist/images/bmp.js +234 -0
  67. package/dist/images/gif.d.ts +9 -0
  68. package/dist/images/gif.js +215 -0
  69. package/dist/images/index.d.ts +18 -0
  70. package/dist/images/index.js +63 -0
  71. package/dist/images/png-encode.d.ts +4 -0
  72. package/dist/images/png-encode.js +73 -0
  73. package/dist/images/size.d.ts +10 -0
  74. package/dist/images/size.js +83 -0
  75. package/dist/images/tiff.d.ts +14 -0
  76. package/dist/images/tiff.js +407 -0
  77. package/dist/index.d.ts +7 -2
  78. package/dist/index.js +5 -0
  79. package/dist/layout/bidi.d.ts +18 -0
  80. package/dist/layout/bidi.js +71 -0
  81. package/dist/layout/blocks.d.ts +20 -3
  82. package/dist/layout/blocks.js +88 -58
  83. package/dist/layout/cache.d.ts +31 -0
  84. package/dist/layout/cache.js +38 -0
  85. package/dist/layout/drawing.d.ts +30 -0
  86. package/dist/layout/drawing.js +120 -0
  87. package/dist/layout/engine.d.ts +3 -0
  88. package/dist/layout/engine.js +218 -11
  89. package/dist/layout/index.d.ts +1 -0
  90. package/dist/layout/index.js +1 -0
  91. package/dist/layout/lines.d.ts +63 -5
  92. package/dist/layout/lines.js +245 -20
  93. package/dist/layout/paint.d.ts +25 -3
  94. package/dist/layout/paint.js +26 -10
  95. package/dist/layout/shapes.d.ts +7 -0
  96. package/dist/layout/shapes.js +338 -0
  97. package/dist/layout/style.d.ts +4 -0
  98. package/dist/layout/style.js +2 -0
  99. package/dist/layout/types.d.ts +89 -2
  100. package/dist/math/boxes.d.ts +88 -0
  101. package/dist/math/boxes.js +166 -0
  102. package/dist/math/index.d.ts +29 -0
  103. package/dist/math/index.js +44 -0
  104. package/dist/math/layout.d.ts +13 -0
  105. package/dist/math/layout.js +771 -0
  106. package/dist/math/linear.d.ts +3 -0
  107. package/dist/math/linear.js +152 -0
  108. package/dist/math/omml.d.ts +15 -0
  109. package/dist/math/omml.js +57 -0
  110. package/dist/math/paths.d.ts +61 -0
  111. package/dist/math/paths.js +450 -0
  112. package/dist/math/symbols.d.ts +49 -0
  113. package/dist/math/symbols.js +269 -0
  114. package/dist/math/text.d.ts +53 -0
  115. package/dist/math/text.js +316 -0
  116. package/dist/metafile/canvas.d.ts +80 -0
  117. package/dist/metafile/canvas.js +515 -0
  118. package/dist/metafile/dib.d.ts +27 -0
  119. package/dist/metafile/dib.js +300 -0
  120. package/dist/metafile/emf.d.ts +31 -0
  121. package/dist/metafile/emf.js +591 -0
  122. package/dist/metafile/geometry.d.ts +49 -0
  123. package/dist/metafile/geometry.js +85 -0
  124. package/dist/metafile/index.d.ts +27 -0
  125. package/dist/metafile/index.js +34 -0
  126. package/dist/metafile/reader.d.ts +28 -0
  127. package/dist/metafile/reader.js +59 -0
  128. package/dist/metafile/state.d.ts +118 -0
  129. package/dist/metafile/state.js +172 -0
  130. package/dist/metafile/text.d.ts +17 -0
  131. package/dist/metafile/text.js +130 -0
  132. package/dist/metafile/wmf.d.ts +33 -0
  133. package/dist/metafile/wmf.js +395 -0
  134. package/dist/model/content.d.ts +92 -7
  135. package/dist/model/content.js +251 -17
  136. package/dist/model/document.d.ts +34 -1
  137. package/dist/model/document.js +80 -1
  138. package/dist/model/fields.d.ts +4 -0
  139. package/dist/model/fields.js +10 -0
  140. package/dist/model/numbering.d.ts +2 -0
  141. package/dist/model/numbering.js +22 -0
  142. package/dist/model/props.d.ts +2 -0
  143. package/dist/model/props.js +3 -0
  144. package/dist/opc/index.d.ts +1 -1
  145. package/dist/opc/package.d.ts +34 -0
  146. package/dist/opc/package.js +58 -4
  147. package/dist/pdf/export.js +97 -6
  148. package/dist/pdf/images.d.ts +7 -0
  149. package/dist/pdf/images.js +39 -2
  150. package/dist/render/activity.d.ts +138 -0
  151. package/dist/render/activity.js +794 -0
  152. package/dist/render/clipboard.d.ts +29 -0
  153. package/dist/render/clipboard.js +401 -0
  154. package/dist/render/comments.d.ts +166 -0
  155. package/dist/render/comments.js +779 -0
  156. package/dist/render/context-menu.d.ts +124 -0
  157. package/dist/render/context-menu.js +525 -0
  158. package/dist/render/editing.d.ts +146 -5
  159. package/dist/render/editing.js +678 -53
  160. package/dist/render/index.d.ts +12 -0
  161. package/dist/render/index.js +11 -0
  162. package/dist/render/navigation-panel.d.ts +76 -0
  163. package/dist/render/navigation-panel.js +431 -0
  164. package/dist/render/selection.js +5 -0
  165. package/dist/render/svg.d.ts +4 -6
  166. package/dist/render/svg.js +69 -7
  167. package/dist/render/toolbar.d.ts +83 -0
  168. package/dist/render/toolbar.js +505 -0
  169. package/dist/render/ui/comment-layout.d.ts +39 -0
  170. package/dist/render/ui/comment-layout.js +79 -0
  171. package/dist/render/ui/icons.d.ts +6 -0
  172. package/dist/render/ui/icons.js +38 -0
  173. package/dist/render/ui/menu.d.ts +38 -0
  174. package/dist/render/ui/menu.js +274 -0
  175. package/dist/render/ui/nav-model.d.ts +11 -0
  176. package/dist/render/ui/nav-model.js +34 -0
  177. package/dist/render/ui/overflow.d.ts +5 -0
  178. package/dist/render/ui/overflow.js +18 -0
  179. package/dist/render/ui/popover.d.ts +18 -0
  180. package/dist/render/ui/popover.js +109 -0
  181. package/dist/render/ui/theme.d.ts +2 -0
  182. package/dist/render/ui/theme.js +29 -0
  183. package/dist/render/undo.d.ts +76 -0
  184. package/dist/render/undo.js +144 -0
  185. package/dist/render/viewer.d.ts +100 -7
  186. package/dist/render/viewer.js +302 -92
  187. package/dist/security/policy.d.ts +3 -0
  188. package/dist/security/policy.js +6 -2
  189. package/dist/security/protection.d.ts +1 -0
  190. package/dist/security/protection.js +1 -1
  191. package/dist/text/bidi-data.d.ts +53 -0
  192. package/dist/text/bidi-data.js +318 -0
  193. package/dist/text/bidi.d.ts +37 -0
  194. package/dist/text/bidi.js +508 -0
  195. package/dist/xml/ns.d.ts +5 -0
  196. package/dist/xml/ns.js +7 -0
  197. package/package.json +9 -2
@@ -4,10 +4,13 @@
4
4
  * such as hyperlinks, fields, content controls and tracked insertions are flattened into markers;
5
5
  * every inline keeps a reference to the XML it came from so edits can go back to the source.
6
6
  */
7
+ import { mathToText } from '../math/linear.js';
7
8
  import { attr, elements, firstChild, localName, textContent } from '../xml/index.js';
8
- import { fieldLinkTarget, isDynamicField, parseFieldInstruction } from './fields.js';
9
+ import { fieldLinkTarget, setLinkSource, isDynamicField, parseFieldInstruction } from './fields.js';
9
10
  import { mergeCellProps, mergeParagraphProps, mergeRunProps, mergeTableProps, parseCellProps, parseParagraphProps, parseRowProps, parseRunProps, parseSectionProps, parseTableProps, } from './props.js';
10
11
  import { emuToPt, parseIntSafe, parseOnOff, parseTwipsMeasure } from './units.js';
12
+ /** Word-like colours for revision authors (one per author, in order of first appearance). */
13
+ export const REVISION_COLORS = ['B5082E', '2E74B5', '548235', '7030A0', 'C55A11', '00838F', '7F6000', '595959'];
11
14
  /** Lock info of a content control whose content cannot be edited. */
12
15
  function contentLock(sdt) {
13
16
  const sdtPr = firstChild(sdt, 'w:sdtPr');
@@ -16,7 +19,7 @@ function contentLock(sdt) {
16
19
  return undefined;
17
20
  return { id: attr(firstChild(sdtPr, 'w:id'), 'w:val') ?? '', title: attr(firstChild(sdtPr, 'w:alias'), 'w:val') };
18
21
  }
19
- const UNDERSTOOD_REQUIRES = new Set(['w14', 'w15', 'w16se', 'w16cid', 'w16cex', 'wp14', 'w16du', 'w16sdtdh']);
22
+ const UNDERSTOOD_REQUIRES = new Set(['w14', 'w15', 'w16se', 'w16cid', 'w16cex', 'wp14', 'w16du', 'w16sdtdh', 'wps', 'wpg', 'wpc', 'cx', 'cx1', 'cx2', 'aink', 'am3d', 'a14']);
20
23
  export class StoryReader {
21
24
  ctx;
22
25
  fields = [];
@@ -35,7 +38,7 @@ export class StoryReader {
35
38
  readBlocks(container, cell) {
36
39
  const out = [];
37
40
  this.collectBlocks(container, out, cell);
38
- return out;
41
+ return this.ctx.showDeletions ? out : joinDeletedMarks(out);
39
42
  }
40
43
  collectBlocks(container, out, cell) {
41
44
  for (const node of container.children) {
@@ -109,6 +112,8 @@ export class StoryReader {
109
112
  for (const lock of this.blockLocks)
110
113
  inlines.push({ kind: 'lockEnd', id: lock.id });
111
114
  const sectPr = firstChild(pPr, 'w:sectPr');
115
+ const markRPr = firstChild(pPr, 'w:rPr');
116
+ const markRevision = firstChild(markRPr, 'w:del') || firstChild(markRPr, 'w:moveFrom') ? 'del' : firstChild(markRPr, 'w:ins') || firstChild(markRPr, 'w:moveTo') ? 'ins' : undefined;
112
117
  return {
113
118
  kind: 'paragraph',
114
119
  el: p,
@@ -118,8 +123,22 @@ export class StoryReader {
118
123
  inlines,
119
124
  numbering: numInfo,
120
125
  sectionEnd: sectPr ? parseSectionProps(sectPr) : undefined,
126
+ ...(markRevision ? { markRevision } : {}),
121
127
  };
122
128
  }
129
+ /** Display formatting for text inside a tracked change (only when deletions are shown: "all markup"). */
130
+ revisionProps(props) {
131
+ const rev = this.revisions[this.revisions.length - 1];
132
+ if (!rev || !this.ctx.showDeletions)
133
+ return props;
134
+ let index = this.authors.indexOf(rev.author);
135
+ if (index < 0)
136
+ index = this.authors.push(rev.author) - 1;
137
+ const color = REVISION_COLORS[index % REVISION_COLORS.length];
138
+ return rev.kind === 'ins' ? { ...props, underline: 'single', underlineColor: color, color } : { ...props, strike: true, color };
139
+ }
140
+ revisions = [];
141
+ authors = [];
123
142
  suppressed() {
124
143
  for (const f of this.fields)
125
144
  if (f.phase === 'instr' || f.dynamic)
@@ -161,6 +180,10 @@ export class StoryReader {
161
180
  }
162
181
  case 'w:ins':
163
182
  case 'w:moveTo':
183
+ this.revisions.push({ kind: 'ins', author: attr(node, 'w:author') ?? '' });
184
+ this.readInlines(node, out);
185
+ this.revisions.pop();
186
+ break;
164
187
  case 'w:smartTag':
165
188
  case 'w:customXml':
166
189
  case 'w:dir':
@@ -169,8 +192,11 @@ export class StoryReader {
169
192
  break;
170
193
  case 'w:del':
171
194
  case 'w:moveFrom':
172
- if (this.ctx.showDeletions)
195
+ if (this.ctx.showDeletions) {
196
+ this.revisions.push({ kind: 'del', author: attr(node, 'w:author') ?? '' });
173
197
  this.readInlines(node, out);
198
+ this.revisions.pop();
199
+ }
174
200
  break;
175
201
  case 'w:sdt': {
176
202
  const lock = contentLock(node);
@@ -238,7 +264,7 @@ export class StoryReader {
238
264
  }
239
265
  readRun(run, out) {
240
266
  let props;
241
- const getProps = () => (props ??= this.runProps(run));
267
+ const getProps = () => (props ??= this.revisionProps(this.runProps(run)));
242
268
  for (const node of run.children) {
243
269
  if (node.type !== 'element')
244
270
  continue;
@@ -267,7 +293,7 @@ export class StoryReader {
267
293
  break;
268
294
  case 'w:delText':
269
295
  if (this.ctx.showDeletions)
270
- out.push({ kind: 'text', text: textContent(node), node, run, props: { ...getProps(), strike: true } });
296
+ out.push({ kind: 'text', text: textContent(node), node, run, props: getProps() });
271
297
  break;
272
298
  case 'w:tab':
273
299
  case 'w:ptab':
@@ -411,7 +437,7 @@ export class StoryReader {
411
437
  const location = attr(node, 'w:docLocation');
412
438
  if (url && location)
413
439
  url += `#${location}`;
414
- return { url, anchor, tooltip };
440
+ return setLinkSource({ url, anchor, tooltip }, node);
415
441
  }
416
442
  chooseAlternate(node) {
417
443
  for (const choice of elements(node, 'mc:Choice')) {
@@ -430,13 +456,12 @@ export class StoryReader {
430
456
  const height = emuToPt(Number(attr(extent, 'cy') ?? 0));
431
457
  const docPr = firstChild(d, 'wp:docPr');
432
458
  const graphicData = firstChild(firstChild(d, 'a:graphic'), 'a:graphicData');
433
- const blip = findDescendant(graphicData, 'a:blip');
434
- const rId = attr(blip, 'r:embed') ?? attr(blip, 'r:link');
435
- const rel = rId ? this.ctx.rels.get(rId) : undefined;
459
+ const content = this.readGraphic(graphicData, width, height);
460
+ const picture = content?.type === 'picture' ? content : undefined;
436
461
  const image = {
437
462
  kind: 'image',
438
- target: rel?.target,
439
- external: rel?.external ?? false,
463
+ target: picture?.target,
464
+ external: picture?.external ?? false,
440
465
  width,
441
466
  height,
442
467
  alt: attr(docPr, 'descr') || attr(docPr, 'title') || undefined,
@@ -444,15 +469,133 @@ export class StoryReader {
444
469
  run,
445
470
  props,
446
471
  };
472
+ if (content && content.type !== 'picture')
473
+ image.content = content;
474
+ const xfrm = graphicData ? findDescendant(graphicData, 'a:xfrm') : undefined;
475
+ const transform = readTransform(xfrm);
476
+ if (transform.rotation)
477
+ image.rotation = transform.rotation;
478
+ if (transform.flipH)
479
+ image.flipH = true;
480
+ if (transform.flipV)
481
+ image.flipV = true;
447
482
  if (isAnchor)
448
483
  image.float = readFloat(d);
449
484
  return image;
450
485
  }
486
+ /** The content of an a:graphicData: picture, shape, group, canvas, chart or SmartArt. */
487
+ readGraphic(graphicData, width, height) {
488
+ if (!graphicData)
489
+ return undefined;
490
+ for (const c of elements(graphicData)) {
491
+ switch (c.name) {
492
+ case 'pic:pic':
493
+ return this.readPicture(c);
494
+ case 'wps:wsp':
495
+ return { type: 'shape', shape: this.readShape(c) };
496
+ case 'wpg:wgp':
497
+ case 'wpc:wpc':
498
+ return { type: 'group', children: this.readGroupChildren(c, { x: 0, y: 0, w: width, h: height }) };
499
+ case 'c:chart': {
500
+ const rel = this.ctx.rels.get(attr(c, 'r:id') ?? '');
501
+ return { type: 'chart', part: rel?.target };
502
+ }
503
+ case 'dgm:relIds': {
504
+ const rel = this.ctx.rels.get(attr(c, 'r:dm') ?? '');
505
+ return { type: 'diagram', dataPart: rel?.target };
506
+ }
507
+ default:
508
+ break;
509
+ }
510
+ }
511
+ // Anything else with a picture in it (e.g. an unknown wrapper) still shows the picture.
512
+ const blip = findDescendant(graphicData, 'a:blip');
513
+ return blip ? this.readPicture(graphicData) : undefined;
514
+ }
515
+ readPicture(node) {
516
+ const blip = findDescendant(node, 'a:blip');
517
+ const rId = attr(blip, 'r:embed') ?? attr(blip, 'r:link');
518
+ const rel = rId ? this.ctx.rels.get(rId) : undefined;
519
+ return { type: 'picture', target: rel?.target, external: rel?.external ?? false };
520
+ }
521
+ readShape(wsp) {
522
+ const spPr = firstChild(wsp, 'wps:spPr') ?? firstChild(wsp, 'dsp:spPr') ?? firstChild(wsp, 'a:spPr') ?? firstChild(wsp, 'p:spPr');
523
+ const geometry = firstChild(spPr, 'a:prstGeom') ?? firstChild(spPr, 'a:custGeom');
524
+ const shape = { geometry, spPr, style: firstChild(wsp, 'wps:style') ?? firstChild(wsp, 'dsp:style') };
525
+ const content = firstChild(firstChild(wsp, 'wps:txbx'), 'w:txbxContent');
526
+ const bodyPr = firstChild(wsp, 'wps:bodyPr');
527
+ if (content) {
528
+ const inset = (name, fallback) => {
529
+ const v = parseIntSafe(attr(bodyPr, name));
530
+ return v === undefined ? fallback : emuToPt(v);
531
+ };
532
+ const anchor = attr(bodyPr, 'anchor');
533
+ const vert = attr(bodyPr, 'vert');
534
+ shape.text = {
535
+ container: content,
536
+ autoFit: !!firstChild(bodyPr, 'a:spAutoFit'),
537
+ blocks: this.readBlocks(content),
538
+ insets: { left: inset('lIns', 7.2), top: inset('tIns', 3.6), right: inset('rIns', 7.2), bottom: inset('bIns', 3.6) },
539
+ anchor: anchor === 'ctr' ? 'ctr' : anchor === 'b' ? 'b' : 't',
540
+ vertical: vert !== undefined && vert !== 'horz',
541
+ };
542
+ }
543
+ const txBody = firstChild(wsp, 'dsp:txBody') ?? firstChild(wsp, 'wps:txBody');
544
+ if (txBody)
545
+ shape.txBody = txBody;
546
+ return shape;
547
+ }
548
+ /** Children of a group or canvas, mapped from the group's child coordinates into `frame`. */
549
+ readGroupChildren(group, frame) {
550
+ const grpSpPr = firstChild(group, 'wpg:grpSpPr') ?? firstChild(group, 'wpc:bg') ?? firstChild(group, 'a:grpSpPr');
551
+ const xfrm = firstChild(grpSpPr, 'a:xfrm');
552
+ const chOff = firstChild(xfrm, 'a:chOff');
553
+ const chExt = firstChild(xfrm, 'a:chExt');
554
+ const off = { x: Number(attr(chOff, 'x') ?? 0), y: Number(attr(chOff, 'y') ?? 0) };
555
+ const ext = { cx: Number(attr(chExt, 'cx') ?? 0), cy: Number(attr(chExt, 'cy') ?? 0) };
556
+ // Without child extents (a canvas), child coordinates are EMU from the frame's corner.
557
+ const sx = ext.cx > 0 ? frame.w / ext.cx : 1 / 12700;
558
+ const sy = ext.cy > 0 ? frame.h / ext.cy : 1 / 12700;
559
+ const out = [];
560
+ for (const c of elements(group)) {
561
+ let content;
562
+ let spPr;
563
+ switch (c.name) {
564
+ case 'wps:wsp':
565
+ content = { type: 'shape', shape: this.readShape(c) };
566
+ spPr = firstChild(c, 'wps:spPr');
567
+ break;
568
+ case 'pic:pic':
569
+ content = this.readPicture(c);
570
+ spPr = firstChild(c, 'pic:spPr');
571
+ break;
572
+ case 'wpg:grpSp':
573
+ case 'wpg:wgp':
574
+ spPr = firstChild(c, 'wpg:grpSpPr');
575
+ break;
576
+ case 'wpc:wpc':
577
+ break;
578
+ default:
579
+ continue;
580
+ }
581
+ const t = readTransform(firstChild(spPr, 'a:xfrm'));
582
+ const child = {
583
+ x: frame.x + (t.x - off.x) * sx,
584
+ y: frame.y + (t.y - off.y) * sy,
585
+ w: t.cx * sx,
586
+ h: t.cy * sy,
587
+ };
588
+ if (!content)
589
+ content = { type: 'group', children: this.readGroupChildren(c, { x: 0, y: 0, w: child.w, h: child.h }) };
590
+ out.push({ ...child, rotation: t.rotation, flipH: t.flipH, flipV: t.flipV, content });
591
+ }
592
+ return out;
593
+ }
451
594
  readVml(node, run, props) {
452
595
  const imagedata = findDescendant(node, 'v:imagedata');
453
596
  const rId = attr(imagedata, 'r:id');
454
597
  if (!rId)
455
- return undefined;
598
+ return this.readVmlTextBox(node, run, props);
456
599
  const shape = findDescendant(node, 'v:shape');
457
600
  const style = parseCssStyle(attr(shape, 'style') ?? '');
458
601
  const rel = this.ctx.rels.get(rId);
@@ -468,11 +611,54 @@ export class StoryReader {
468
611
  props,
469
612
  };
470
613
  }
471
- readMath(node, out) {
472
- // Equations are not typeset yet: show their text so content is not lost.
473
- for (const t of findAllDescendants(node, 'm:t')) {
474
- out.push({ kind: 'text', text: textContent(t), node: t, run: node, props: this.runProps(undefined) });
614
+ /** An old-style (VML) text box: its Word paragraphs in a plain frame, sized from the VML style. */
615
+ readVmlTextBox(node, run, props) {
616
+ const textbox = findDescendant(node, 'v:textbox');
617
+ const content = firstChild(textbox, 'w:txbxContent');
618
+ if (!content)
619
+ return undefined;
620
+ const shape = findDescendant(node, 'v:shape') ?? findDescendant(node, 'v:rect') ?? findDescendant(node, 'v:roundrect');
621
+ const style = parseCssStyle(attr(shape, 'style') ?? '');
622
+ const fill = attr(shape, 'fillcolor');
623
+ const stroke = attr(shape, 'strokecolor');
624
+ const inline = {
625
+ kind: 'image',
626
+ target: undefined,
627
+ external: false,
628
+ width: cssLengthToPt(style.width) ?? 144,
629
+ height: cssLengthToPt(style.height) ?? 72,
630
+ drawing: node,
631
+ run,
632
+ props,
633
+ content: {
634
+ type: 'shape',
635
+ shape: {
636
+ geometry: undefined,
637
+ spPr: undefined,
638
+ style: undefined,
639
+ vml: { fill: attr(shape, 'filled') === 'f' ? undefined : (fill?.replace('#', '') ?? 'FFFFFF'), stroke: attr(shape, 'stroked') === 'f' ? undefined : (stroke?.replace('#', '') ?? '000000') },
640
+ text: { container: content, blocks: this.readBlocks(content), insets: { left: 7.2, top: 3.6, right: 7.2, bottom: 3.6 }, anchor: 't', vertical: false },
641
+ },
642
+ },
643
+ };
644
+ if (style.position === 'absolute') {
645
+ inline.float = {
646
+ behindDoc: (style['z-index'] ?? '').startsWith('-'),
647
+ wrap: 'square',
648
+ wrapText: 'bothSides',
649
+ hRelative: style['mso-position-horizontal-relative'] ?? 'column',
650
+ hAlign: style['mso-position-horizontal'],
651
+ hOffset: cssLengthToPt(style['margin-left']) ?? 0,
652
+ vRelative: style['mso-position-vertical-relative'] ?? 'paragraph',
653
+ vAlign: style['mso-position-vertical'],
654
+ vOffset: cssLengthToPt(style['margin-top']) ?? 0,
655
+ dist: { top: 0, bottom: 0, left: 9, right: 9 },
656
+ };
475
657
  }
658
+ return inline;
659
+ }
660
+ readMath(node, out) {
661
+ out.push({ kind: 'math', node, display: node.name === 'm:oMathPara', text: mathToText(node), props: this.runProps(undefined) });
476
662
  }
477
663
  readTable(tbl) {
478
664
  const { styles } = this.ctx;
@@ -684,6 +870,8 @@ export function blocksToText(blocks) {
684
870
  s += '\n';
685
871
  else if (i.kind === 'field')
686
872
  s += i.cached;
873
+ else if (i.kind === 'math')
874
+ s += i.text;
687
875
  }
688
876
  lines.push(s);
689
877
  }
@@ -694,3 +882,49 @@ export function blocksToText(blocks) {
694
882
  }
695
883
  return lines.join('\n');
696
884
  }
885
+ /**
886
+ * The final view of tracked changes: a paragraph whose mark was deleted runs on into the next
887
+ * paragraph (which keeps its own properties), as Word shows it with markup hidden.
888
+ */
889
+ function joinDeletedMarks(blocks) {
890
+ const out = [];
891
+ let carry = [];
892
+ for (const b of blocks) {
893
+ if (b.kind === 'paragraph' && b.markRevision === 'del') {
894
+ carry = [...carry, ...b.inlines];
895
+ continue;
896
+ }
897
+ if (carry.length && b.kind === 'paragraph') {
898
+ b.inlines = [...carry, ...b.inlines];
899
+ carry = [];
900
+ }
901
+ else if (carry.length) {
902
+ // A table follows: the carried text stays as its own paragraph rather than vanishing.
903
+ const last = blocks[blocks.indexOf(b) - 1];
904
+ if (last && last.kind === 'paragraph')
905
+ out.push({ ...last, inlines: carry, markRevision: undefined });
906
+ carry = [];
907
+ }
908
+ out.push(b);
909
+ }
910
+ if (carry.length) {
911
+ const last = blocks[blocks.length - 1];
912
+ if (last && last.kind === 'paragraph')
913
+ out.push({ ...last, inlines: carry, markRevision: undefined });
914
+ }
915
+ return out;
916
+ }
917
+ /** Position, size (EMU) and rotation (degrees) of an a:xfrm. */
918
+ function readTransform(xfrm) {
919
+ const off = firstChild(xfrm, 'a:off');
920
+ const ext = firstChild(xfrm, 'a:ext');
921
+ return {
922
+ x: Number(attr(off, 'x') ?? 0),
923
+ y: Number(attr(off, 'y') ?? 0),
924
+ cx: Number(attr(ext, 'cx') ?? 0),
925
+ cy: Number(attr(ext, 'cy') ?? 0),
926
+ rotation: Number(attr(xfrm, 'rot') ?? 0) / 60000,
927
+ flipH: parseOnOff(attr(xfrm, 'flipH') ?? '0'),
928
+ flipV: parseOnOff(attr(xfrm, 'flipV') ?? '0'),
929
+ };
930
+ }
@@ -1,5 +1,5 @@
1
1
  /** A loaded .docx: its package, parsed parts and readers for every story. */
2
- import { OpcPackage } from '../opc/index.js';
2
+ import { OpcPackage, type PackageCheckpoint } from '../opc/index.js';
3
3
  import { type XmlDocument, type XmlElement } from '../xml/index.js';
4
4
  import { type Block, type Story } from './content.js';
5
5
  import { NumberingDefs } from './numbering.js';
@@ -49,6 +49,16 @@ export declare class DocxError extends Error {
49
49
  }
50
50
  export declare function isCompoundFile(bytes: Uint8Array): boolean;
51
51
  export declare function toBytes(input: Uint8Array | ArrayBuffer | Blob): Promise<Uint8Array>;
52
+ /** An opaque snapshot of a document (see `DocxDocument.checkpoint`). */
53
+ export interface DocumentCheckpoint {
54
+ readonly pkg: PackageCheckpoint;
55
+ readonly parts: WordParts;
56
+ readonly relMaps: Array<[string, Array<[string, {
57
+ target: string;
58
+ external: boolean;
59
+ }]>]>;
60
+ readonly mediaCache: Array<[string, Uint8Array]>;
61
+ }
52
62
  export declare class DocxDocument {
53
63
  readonly pkg: OpcPackage;
54
64
  readonly mainPart: string;
@@ -70,6 +80,14 @@ export declare class DocxDocument {
70
80
  /** A new, empty document with Word's default styles. */
71
81
  static create(): Promise<DocxDocument>;
72
82
  private load;
83
+ private readonly mediaCache;
84
+ /**
85
+ * Charts and SmartArt live in their own parts, and metafile pictures are drawn as vectors, so
86
+ * layout (which is synchronous) needs them read in advance.
87
+ */
88
+ private loadDrawingParts;
89
+ /** Bytes of a media part read at open (metafiles and TIFF images), for synchronous rendering. */
90
+ mediaSync(part: string | undefined): Uint8Array | undefined;
73
91
  private loadRels;
74
92
  /** Re-read styles, numbering and theme (after they were edited). */
75
93
  reparseDefinitions(): void;
@@ -87,6 +105,8 @@ export declare class DocxDocument {
87
105
  headerFooterPart(rId: string): string | undefined;
88
106
  /** Header or footer content. */
89
107
  headerFooter(part: string): Story;
108
+ /** Headers, footers and note parts, for editing them (`new DocxEditor(doc, guard, { part })`). */
109
+ storyParts(): StoryPart[];
90
110
  /** Blocks of a footnote or endnote by id. */
91
111
  note(type: 'footnote' | 'endnote', id: string): Block[];
92
112
  get defaultTabStop(): number;
@@ -96,6 +116,10 @@ export declare class DocxDocument {
96
116
  media(part: string): Promise<Uint8Array>;
97
117
  /** Mark a part as edited: it will be re-serialised on save and caches are refreshed. */
98
118
  touch(part: string): void;
119
+ /** Snapshot every part and the document's own indexes, for document-wide undo. */
120
+ checkpoint(): DocumentCheckpoint;
121
+ /** Put the document back as it was at `checkpoint()` and tell listeners the main part changed. */
122
+ restore(cp: DocumentCheckpoint): void;
99
123
  invalidate(): void;
100
124
  /** Subscribe to edits; returns an unsubscribe function. */
101
125
  onChange(listener: (part: string) => void): () => void;
@@ -108,3 +132,12 @@ export declare class DocxDocument {
108
132
  password?: string;
109
133
  }): Promise<Uint8Array>;
110
134
  }
135
+ /** A header, footer or notes part. */
136
+ export interface StoryPart {
137
+ kind: 'header' | 'footer' | 'footnotes' | 'endnotes';
138
+ part: string;
139
+ /** Which pages a header or footer is for. */
140
+ type?: 'default' | 'first' | 'even';
141
+ /** Index of the first section that uses it. */
142
+ section?: number;
143
+ }
@@ -1,6 +1,6 @@
1
1
  /** A loaded .docx: its package, parsed parts and readers for every story. */
2
2
  import { CONTENT_TYPE, OpcPackage, REL, isRelType, relTypeName } from '../opc/index.js';
3
- import { attr, elements, firstChild, parseXml, textContent } from '../xml/index.js';
3
+ import { attr, elements, findAll, firstChild, parseXml, textContent } from '../xml/index.js';
4
4
  import { StoryReader } from './content.js';
5
5
  import { NumberingDefs } from './numbering.js';
6
6
  import { StyleSheet } from './styles.js';
@@ -127,8 +127,41 @@ export class DocxDocument {
127
127
  if (name)
128
128
  await pkg.getXml(name);
129
129
  }
130
+ await this.loadDrawingParts();
130
131
  this.reparseDefinitions();
131
132
  }
133
+ mediaCache = new Map();
134
+ /**
135
+ * Charts and SmartArt live in their own parts, and metafile pictures are drawn as vectors, so
136
+ * layout (which is synchronous) needs them read in advance.
137
+ */
138
+ async loadDrawingParts() {
139
+ const { pkg } = this;
140
+ const stories = [this.mainPart, ...[...this.relMaps.keys()].filter((p) => p !== this.mainPart)];
141
+ for (const story of stories) {
142
+ for (const rel of await pkg.relationships(story)) {
143
+ if (rel.external)
144
+ continue;
145
+ const name = pkg.resolve(story, rel);
146
+ if (!pkg.has(name))
147
+ continue;
148
+ const type = rel.type.slice(rel.type.lastIndexOf('/') + 1);
149
+ if (type === 'chart' || type.startsWith('diagram')) {
150
+ await pkg.getXml(name);
151
+ // A chart's own relationships (its embedded workbook, styles); a diagram drawing's images.
152
+ if (!this.relMaps.has(name))
153
+ await this.loadRels(name);
154
+ }
155
+ else if (type === 'image' && /\.(emf|wmf|tiff?)$/i.test(name)) {
156
+ this.mediaCache.set(name, await pkg.getBytes(name));
157
+ }
158
+ }
159
+ }
160
+ }
161
+ /** Bytes of a media part read at open (metafiles and TIFF images), for synchronous rendering. */
162
+ mediaSync(part) {
163
+ return part ? this.mediaCache.get(part) : undefined;
164
+ }
132
165
  async loadRels(part) {
133
166
  const map = new Map();
134
167
  for (const r of await this.pkg.relationships(part))
@@ -188,6 +221,26 @@ export class DocxDocument {
188
221
  }
189
222
  return story;
190
223
  }
224
+ /** Headers, footers and note parts, for editing them (`new DocxEditor(doc, guard, { part })`). */
225
+ storyParts() {
226
+ const out = [];
227
+ const seen = new Set();
228
+ findAll(this.documentXml.root, 'w:sectPr').forEach((sectPr, section) => {
229
+ for (const ref of elements(sectPr)) {
230
+ const kind = ref.name === 'w:headerReference' ? 'header' : ref.name === 'w:footerReference' ? 'footer' : undefined;
231
+ const part = kind ? this.headerFooterPart(attr(ref, 'r:id') ?? '') : undefined;
232
+ if (!kind || !part || seen.has(part))
233
+ continue;
234
+ seen.add(part);
235
+ out.push({ kind, part, type: (attr(ref, 'w:type') ?? 'default'), section });
236
+ }
237
+ });
238
+ if (this.parts.footnotes)
239
+ out.push({ kind: 'footnotes', part: this.parts.footnotes });
240
+ if (this.parts.endnotes)
241
+ out.push({ kind: 'endnotes', part: this.parts.endnotes });
242
+ return out;
243
+ }
191
244
  /** Blocks of a footnote or endnote by id. */
192
245
  note(type, id) {
193
246
  const part = type === 'footnote' ? this.parts.footnotes : this.parts.endnotes;
@@ -246,6 +299,32 @@ export class DocxDocument {
246
299
  for (const l of this.listeners)
247
300
  l(part);
248
301
  }
302
+ /** Snapshot every part and the document's own indexes, for document-wide undo. */
303
+ checkpoint() {
304
+ return {
305
+ pkg: this.pkg.checkpoint(),
306
+ parts: { ...this.parts },
307
+ relMaps: [...this.relMaps].map(([part, map]) => [part, [...map].map(([id, r]) => [id, { ...r }])]),
308
+ mediaCache: [...this.mediaCache],
309
+ };
310
+ }
311
+ /** Put the document back as it was at `checkpoint()` and tell listeners the main part changed. */
312
+ restore(cp) {
313
+ this.pkg.restore(cp.pkg);
314
+ for (const k of Object.keys(this.parts))
315
+ delete this.parts[k];
316
+ Object.assign(this.parts, cp.parts);
317
+ this.relMaps.clear();
318
+ for (const [part, entries] of cp.relMaps)
319
+ this.relMaps.set(part, new Map(entries.map(([id, r]) => [id, { ...r }])));
320
+ this.mediaCache.clear();
321
+ for (const [name, bytes] of cp.mediaCache)
322
+ this.mediaCache.set(name, bytes);
323
+ this.documentXml = this.pkg.cachedXml(this.mainPart);
324
+ this.reparseDefinitions();
325
+ for (const l of this.listeners)
326
+ l(this.mainPart);
327
+ }
249
328
  invalidate() {
250
329
  this.bodyCache = undefined;
251
330
  this.storyCache.clear();
@@ -13,5 +13,9 @@ export interface LinkTarget {
13
13
  anchor?: string;
14
14
  tooltip?: string;
15
15
  }
16
+ /** Remember the w:hyperlink element a link target was read from (links made by fields have none). */
17
+ export declare function setLinkSource(target: LinkTarget, element: object): LinkTarget;
18
+ /** The w:hyperlink element a link target came from, so a menu can edit exactly that link. */
19
+ export declare function linkSource(target: LinkTarget): object | undefined;
16
20
  /** Link target expressed by a field, if the field is a link. */
17
21
  export declare function fieldLinkTarget(f: FieldInstruction): LinkTarget | undefined;
@@ -59,6 +59,16 @@ export function parseFieldInstruction(raw) {
59
59
  export function isDynamicField(type) {
60
60
  return type === 'PAGE' || type === 'NUMPAGES' || type === 'SECTIONPAGES';
61
61
  }
62
+ const linkSources = new WeakMap();
63
+ /** Remember the w:hyperlink element a link target was read from (links made by fields have none). */
64
+ export function setLinkSource(target, element) {
65
+ linkSources.set(target, element);
66
+ return target;
67
+ }
68
+ /** The w:hyperlink element a link target came from, so a menu can edit exactly that link. */
69
+ export function linkSource(target) {
70
+ return linkSources.get(target);
71
+ }
62
72
  /** Link target expressed by a field, if the field is a link. */
63
73
  export function fieldLinkTarget(f) {
64
74
  if (f.type === 'HYPERLINK') {
@@ -50,4 +50,6 @@ export declare class NumberingCounter {
50
50
  } | undefined;
51
51
  }
52
52
  export declare function formatNumber(n: number, format: string): string;
53
+ /** A list label with symbol-font bullets (Symbol, Wingdings) replaced by their Unicode look-alikes. */
54
+ export declare function normaliseBullet(text: string): string;
53
55
  export {};
@@ -243,3 +243,25 @@ export function formatNumber(n, format) {
243
243
  return String(n);
244
244
  }
245
245
  }
246
+ /** Private-use symbol-font bullets mapped to Unicode equivalents. */
247
+ const SYMBOL_BULLETS = {
248
+ 0xf0b7: '•',
249
+ 0xf0a7: '▪',
250
+ 0xf0a8: '◆',
251
+ 0xf0d8: '➢',
252
+ 0xf076: '❖',
253
+ 0xf0fc: '✓',
254
+ 0xf06e: '■',
255
+ 0xf071: '❑',
256
+ 0xf0e0: '➢',
257
+ 0xf06f: '□',
258
+ };
259
+ /** A list label with symbol-font bullets (Symbol, Wingdings) replaced by their Unicode look-alikes. */
260
+ export function normaliseBullet(text) {
261
+ let out = '';
262
+ for (const ch of text) {
263
+ const cp = ch.codePointAt(0);
264
+ out += SYMBOL_BULLETS[cp] ?? (cp >= 0xf000 && cp <= 0xf0ff ? '•' : ch);
265
+ }
266
+ return out;
267
+ }
@@ -61,6 +61,8 @@ export interface RunProps {
61
61
  kern?: number;
62
62
  lang?: string;
63
63
  rtl?: boolean;
64
+ /** w14:ligatures: which OpenType ligatures Word applies ('standard', 'all'…; absent or 'none': none). */
65
+ ligatures?: string;
64
66
  border?: Border;
65
67
  emboss?: boolean;
66
68
  imprint?: boolean;
@@ -121,6 +121,9 @@ export function parseRunProps(rPr) {
121
121
  p.kern = halfPtToPt(kern);
122
122
  p.lang = val(rPr, 'w:lang');
123
123
  p.rtl = onOff(rPr, 'w:rtl');
124
+ const lig = val(rPr, 'w14:ligatures');
125
+ if (lig)
126
+ p.ligatures = lig;
124
127
  p.border = parseBorder(firstChild(rPr, 'w:bdr'));
125
128
  p.emboss = onOff(rPr, 'w:emboss');
126
129
  p.imprint = onOff(rPr, 'w:imprint');
@@ -1,3 +1,3 @@
1
1
  export * from './constants.js';
2
2
  export * from './paths.js';
3
- export { OpcPackage, OpcError, type Relationship } from './package.js';
3
+ export { OpcPackage, OpcError, type PackageCheckpoint, type Relationship } from './package.js';