-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrunParser.ts
More file actions
1231 lines (1103 loc) · 33.1 KB
/
Copy pathrunParser.ts
File metadata and controls
1231 lines (1103 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Run Parser - Parse text runs (w:r) with complete formatting
*
* A run is a contiguous region of text with the same character formatting.
* Runs can contain:
* - Text (w:t)
* - Tabs (w:tab)
* - Line breaks (w:br)
* - Symbols (w:sym)
* - Footnote/endnote references
* - Field characters
* - Drawings/images (w:drawing)
* - And more...
*
* OOXML Reference:
* - Run: w:r
* - Run properties: w:rPr
* - Text content: w:t
*/
import type {
Run,
RunContent,
TextContent,
TabContent,
BreakContent,
SymbolContent,
NoteReferenceContent,
FieldCharContent,
InstrTextContent,
SoftHyphenContent,
NoBreakHyphenContent,
DrawingContent,
RunPropertyChange,
TextFormatting,
ColorValue,
ShadingProperties,
Theme,
Image,
RelationshipMap,
MediaFile,
ShapeContent,
} from "../types/document";
import { normalizeRevisionId } from "@stll/docx-core/model";
import { parseGroupDrawing } from "./groupDrawingParser";
import { parseImage } from "./imageParser";
import {
EmphasisMarkSchema,
FontThemeSchema,
HighlightColorSchema,
ShadingPatternSchema,
TextEffectSchema,
ThemeColorSlotSchema,
UnderlineStyleSchema,
narrowEnum,
} from "./parserEnums";
import { parseShapeFromDrawing, shouldPreserveRawShapeDrawing } from "./shapeParser";
import type { StyleMap } from "./styleParser";
import { parseVmlImageContent } from "./vmlImageParser";
import { resolveThemeFontRef } from "./themeParser";
import {
cloneWithXmlnsDeclarations,
findAllDeep,
findChild,
findChildren,
getAttribute,
getChildElements,
getTextContent,
mergeXmlnsDeclarations,
parseBooleanElement,
parseNumericAttribute,
elementToXml,
} from "./xmlParser";
import type { XmlElement } from "./xmlParser";
/**
* Sanity cap on `w:lang` `@w:val`/`@w:eastAsia`/`@w:bidi` tag length. BCP-47
* tags top out well under this; a hostile/corrupt tag here would drive the
* hyphenation dictionary lookup and segmenter cache keying with an
* attacker-sized string per run.
*/
const MAX_LANGUAGE_TAG_LENGTH = 35;
const truncateLanguageTag = (value: string | undefined): string | undefined =>
value === undefined ? undefined : value.slice(0, MAX_LANGUAGE_TAG_LENGTH);
/**
* Parse color value from attributes
*/
function parseColorValue(
rgb: string | null,
themeColor: string | null,
themeTint: string | null,
themeShade: string | null,
): ColorValue {
const color: ColorValue = {};
if (rgb && rgb !== "auto") {
color.rgb = rgb;
} else if (rgb === "auto") {
color.auto = true;
}
const validatedThemeColor = narrowEnum(themeColor, ThemeColorSlotSchema);
if (validatedThemeColor) {
color.themeColor = validatedThemeColor;
}
if (themeTint) {
color.themeTint = themeTint;
}
if (themeShade) {
color.themeShade = themeShade;
}
return color;
}
/**
* Parse shading properties (w:shd)
*/
function parseShadingProperties(shd: XmlElement | null): ShadingProperties | undefined {
if (!shd) {
return undefined;
}
const props: ShadingProperties = {};
const color = getAttribute(shd, "w", "color");
if (color && color !== "auto") {
props.color = { rgb: color };
}
const fill = getAttribute(shd, "w", "fill");
if (fill && fill !== "auto") {
props.fill = { rgb: fill };
}
const themeFill = getAttribute(shd, "w", "themeFill");
const validatedThemeFill = narrowEnum(themeFill, ThemeColorSlotSchema);
if (validatedThemeFill) {
if (!props.fill) {
props.fill = {};
}
props.fill.themeColor = validatedThemeFill;
}
const themeFillTint = getAttribute(shd, "w", "themeFillTint");
if (themeFillTint && props.fill) {
props.fill.themeTint = themeFillTint;
}
const themeFillShade = getAttribute(shd, "w", "themeFillShade");
if (themeFillShade && props.fill) {
props.fill.themeShade = themeFillShade;
}
const pattern = narrowEnum(getAttribute(shd, "w", "val"), ShadingPatternSchema);
if (pattern) {
props.pattern = pattern;
}
return Object.keys(props).length > 0 ? props : undefined;
}
type RunPropertyChildren = {
b?: XmlElement;
bCs?: XmlElement;
caps?: XmlElement;
color?: XmlElement;
cs?: XmlElement;
dstrike?: XmlElement;
effect?: XmlElement;
em?: XmlElement;
emboss?: XmlElement;
highlight?: XmlElement;
i?: XmlElement;
iCs?: XmlElement;
imprint?: XmlElement;
kern?: XmlElement;
lang?: XmlElement;
outline?: XmlElement;
position?: XmlElement;
rFonts?: XmlElement;
rtl?: XmlElement;
rStyle?: XmlElement;
shadow?: XmlElement;
shd?: XmlElement;
smallCaps?: XmlElement;
spacing?: XmlElement;
strike?: XmlElement;
sz?: XmlElement;
szCs?: XmlElement;
u?: XmlElement;
vanish?: XmlElement;
vertAlign?: XmlElement;
w?: XmlElement;
};
function collectFirstRunPropertyChildren(rPr: XmlElement): RunPropertyChildren {
const children: RunPropertyChildren = {};
for (const child of rPr.elements ?? []) {
if (child.type !== "element") {
continue;
}
const localName = getLocalName(child.name);
switch (localName) {
case "b":
children.b ??= child;
break;
case "bCs":
children.bCs ??= child;
break;
case "caps":
children.caps ??= child;
break;
case "color":
children.color ??= child;
break;
case "cs":
children.cs ??= child;
break;
case "dstrike":
children.dstrike ??= child;
break;
case "effect":
children.effect ??= child;
break;
case "em":
children.em ??= child;
break;
case "emboss":
children.emboss ??= child;
break;
case "highlight":
children.highlight ??= child;
break;
case "i":
children.i ??= child;
break;
case "iCs":
children.iCs ??= child;
break;
case "imprint":
children.imprint ??= child;
break;
case "kern":
children.kern ??= child;
break;
case "lang":
children.lang ??= child;
break;
case "outline":
children.outline ??= child;
break;
case "position":
children.position ??= child;
break;
case "rFonts":
children.rFonts ??= child;
break;
case "rtl":
children.rtl ??= child;
break;
case "rStyle":
children.rStyle ??= child;
break;
case "shadow":
children.shadow ??= child;
break;
case "shd":
children.shd ??= child;
break;
case "smallCaps":
children.smallCaps ??= child;
break;
case "spacing":
children.spacing ??= child;
break;
case "strike":
children.strike ??= child;
break;
case "sz":
children.sz ??= child;
break;
case "szCs":
children.szCs ??= child;
break;
case "u":
children.u ??= child;
break;
case "vanish":
children.vanish ??= child;
break;
case "vertAlign":
children.vertAlign ??= child;
break;
case "w":
children.w ??= child;
break;
}
}
return children;
}
/**
* Parse run formatting properties (w:rPr)
*
* Handles ALL rPr properties:
* - w:b (bold), w:i (italic), w:u (underline with style)
* - w:strike (strikethrough), w:dstrike (double strike)
* - w:vertAlign (superscript/subscript)
* - w:smallCaps, w:caps (capitalization)
* - w:highlight (text highlight color)
* - w:shd (character shading)
* - w:color (text color with theme resolution)
* - w:sz (font size in half-points)
* - w:rFonts (font family with theme resolution)
* - w:spacing (character spacing)
* - w:effect (text effects)
* - And more...
*/
export function parseRunProperties(
rPr: XmlElement | null,
theme: Theme | null,
_styles?: StyleMap,
): TextFormatting | undefined {
if (!rPr) {
return undefined;
}
const formatting: TextFormatting = {};
const propertyChildren = collectFirstRunPropertyChildren(rPr);
// Bold (w:b)
const b = propertyChildren.b;
if (b) {
formatting.bold = parseBooleanElement(b);
}
const bCs = propertyChildren.bCs;
if (bCs) {
formatting.boldCs = parseBooleanElement(bCs);
}
// Italic (w:i)
const i = propertyChildren.i;
if (i) {
formatting.italic = parseBooleanElement(i);
}
const iCs = propertyChildren.iCs;
if (iCs) {
formatting.italicCs = parseBooleanElement(iCs);
}
// Underline (w:u)
const u = propertyChildren.u;
if (u) {
const style = narrowEnum(getAttribute(u, "w", "val"), UnderlineStyleSchema);
if (style) {
formatting.underline = { style };
const colorVal = getAttribute(u, "w", "color");
const themeColor = getAttribute(u, "w", "themeColor");
if (colorVal || themeColor) {
formatting.underline.color = parseColorValue(
colorVal,
themeColor,
getAttribute(u, "w", "themeTint"),
getAttribute(u, "w", "themeShade"),
);
}
}
}
// Strikethrough (w:strike)
const strike = propertyChildren.strike;
if (strike) {
formatting.strike = parseBooleanElement(strike);
}
// Double strikethrough (w:dstrike)
const dstrike = propertyChildren.dstrike;
if (dstrike) {
formatting.doubleStrike = parseBooleanElement(dstrike);
}
// Vertical alignment - superscript/subscript (w:vertAlign)
const vertAlign = propertyChildren.vertAlign;
if (vertAlign) {
const val = getAttribute(vertAlign, "w", "val");
if (val === "superscript" || val === "subscript" || val === "baseline") {
formatting.vertAlign = val;
}
}
// Small caps (w:smallCaps)
const smallCaps = propertyChildren.smallCaps;
if (smallCaps) {
formatting.smallCaps = parseBooleanElement(smallCaps);
}
// All caps (w:caps)
const caps = propertyChildren.caps;
if (caps) {
formatting.allCaps = parseBooleanElement(caps);
}
// Hidden text (w:vanish)
const vanish = propertyChildren.vanish;
if (vanish) {
formatting.hidden = parseBooleanElement(vanish);
}
// Text color (w:color)
const color = propertyChildren.color;
if (color) {
formatting.color = parseColorValue(
getAttribute(color, "w", "val"),
getAttribute(color, "w", "themeColor"),
getAttribute(color, "w", "themeTint"),
getAttribute(color, "w", "themeShade"),
);
}
// Highlight color (w:highlight)
const highlight = propertyChildren.highlight;
if (highlight) {
const val = narrowEnum(getAttribute(highlight, "w", "val"), HighlightColorSchema);
if (val) {
formatting.highlight = val;
}
}
// Character shading (w:shd)
const shd = propertyChildren.shd;
if (shd) {
const shadingResult = parseShadingProperties(shd);
if (shadingResult) {
formatting.shading = shadingResult;
}
}
// Font size in half-points (w:sz)
const sz = propertyChildren.sz;
if (sz) {
const val = parseNumericAttribute(sz, "w", "val");
if (val !== undefined) {
formatting.fontSize = val;
}
}
// Font size complex script (w:szCs)
const szCs = propertyChildren.szCs;
if (szCs) {
const val = parseNumericAttribute(szCs, "w", "val");
if (val !== undefined) {
formatting.fontSizeCs = val;
}
}
// Font family (w:rFonts)
const rFonts = propertyChildren.rFonts;
if (rFonts) {
const fontFamily: NonNullable<TextFormatting["fontFamily"]> = {};
const ascii = getAttribute(rFonts, "w", "ascii");
if (ascii) {
fontFamily.ascii = ascii;
}
const hAnsi = getAttribute(rFonts, "w", "hAnsi");
if (hAnsi) {
fontFamily.hAnsi = hAnsi;
}
const eastAsia = getAttribute(rFonts, "w", "eastAsia");
if (eastAsia) {
fontFamily.eastAsia = eastAsia;
}
const csFont = getAttribute(rFonts, "w", "cs");
if (csFont) {
fontFamily.cs = csFont;
}
// Theme font references
const asciiThemeRaw = getAttribute(rFonts, "w", "asciiTheme");
const asciiTheme = narrowEnum(asciiThemeRaw, FontThemeSchema);
if (asciiTheme) {
fontFamily.asciiTheme = asciiTheme;
// Also resolve the actual font name for convenience
if (theme && !fontFamily.ascii) {
const resolved = resolveThemeFontRef(theme, asciiTheme);
if (resolved) {
fontFamily.ascii = resolved;
}
}
}
const hAnsiTheme = getAttribute(rFonts, "w", "hAnsiTheme");
if (hAnsiTheme) {
fontFamily.hAnsiTheme = hAnsiTheme;
if (theme && !fontFamily.hAnsi) {
const resolved = resolveThemeFontRef(theme, hAnsiTheme);
if (resolved) {
fontFamily.hAnsi = resolved;
}
}
}
const eastAsiaTheme = getAttribute(rFonts, "w", "eastAsiaTheme");
if (eastAsiaTheme) {
fontFamily.eastAsiaTheme = eastAsiaTheme;
if (theme && !fontFamily.eastAsia) {
const resolved = resolveThemeFontRef(theme, eastAsiaTheme);
if (resolved) {
fontFamily.eastAsia = resolved;
}
}
}
const csTheme = getAttribute(rFonts, "w", "cstheme");
if (csTheme) {
fontFamily.csTheme = csTheme;
if (theme && !fontFamily.cs) {
const resolved = resolveThemeFontRef(theme, csTheme);
if (resolved) {
fontFamily.cs = resolved;
}
}
}
formatting.fontFamily = fontFamily;
}
const lang = propertyChildren.lang;
if (lang) {
const val = truncateLanguageTag(getAttribute(lang, "w", "val") || undefined);
const eastAsia = truncateLanguageTag(getAttribute(lang, "w", "eastAsia") || undefined);
const bidi = truncateLanguageTag(getAttribute(lang, "w", "bidi") || undefined);
if (val || eastAsia || bidi) {
formatting.language = {
...(val ? { val } : {}),
...(eastAsia ? { eastAsia } : {}),
...(bidi ? { bidi } : {}),
};
}
}
// Character spacing in twips (w:spacing)
const spacing = propertyChildren.spacing;
if (spacing) {
const val = parseNumericAttribute(spacing, "w", "val");
if (val !== undefined) {
formatting.spacing = val;
}
}
// Position - raised/lowered in half-points (w:position)
const position = propertyChildren.position;
if (position) {
const val = parseNumericAttribute(position, "w", "val");
if (val !== undefined) {
formatting.position = val;
}
}
// Horizontal text scale percentage (w:w)
const w = propertyChildren.w;
if (w) {
const val = parseNumericAttribute(w, "w", "val");
if (val !== undefined) {
formatting.scale = val;
}
}
// Kerning threshold in half-points (w:kern)
const kern = propertyChildren.kern;
if (kern) {
const val = parseNumericAttribute(kern, "w", "val");
if (val !== undefined) {
formatting.kerning = val;
}
}
// Text effect animation (w:effect)
const effect = propertyChildren.effect;
if (effect) {
const val = narrowEnum(getAttribute(effect, "w", "val"), TextEffectSchema);
if (val) {
formatting.effect = val;
}
}
// Emphasis mark (w:em)
const em = propertyChildren.em;
if (em) {
const val = narrowEnum(getAttribute(em, "w", "val"), EmphasisMarkSchema);
if (val) {
formatting.emphasisMark = val;
}
}
// Emboss effect (w:emboss)
const emboss = propertyChildren.emboss;
if (emboss) {
formatting.emboss = parseBooleanElement(emboss);
}
// Imprint/engrave effect (w:imprint)
const imprint = propertyChildren.imprint;
if (imprint) {
formatting.imprint = parseBooleanElement(imprint);
}
// Outline effect (w:outline)
const outline = propertyChildren.outline;
if (outline) {
formatting.outline = parseBooleanElement(outline);
}
// Shadow effect (w:shadow)
const shadow = propertyChildren.shadow;
if (shadow) {
formatting.shadow = parseBooleanElement(shadow);
}
// Right-to-left text (w:rtl)
const rtl = propertyChildren.rtl;
if (rtl) {
formatting.rtl = parseBooleanElement(rtl);
}
// Complex script formatting (w:cs)
const cs = propertyChildren.cs;
if (cs) {
formatting.cs = parseBooleanElement(cs);
}
// Character style reference (w:rStyle)
const rStyle = propertyChildren.rStyle;
if (rStyle) {
const val = getAttribute(rStyle, "w", "val");
if (val) {
formatting.styleId = val;
}
}
return Object.keys(formatting).length > 0 ? formatting : undefined;
}
function parsePropertyChangeInfo(changeElement: XmlElement): RunPropertyChange["info"] {
const rawId = getAttribute(changeElement, "w", "id");
const parsedId = rawId ? Number.parseInt(rawId, 10) : 0;
const author = (getAttribute(changeElement, "w", "author") ?? "").trim();
const date = (getAttribute(changeElement, "w", "date") ?? "").trim();
const rsid = (getAttribute(changeElement, "w", "rsid") ?? "").trim();
const info: RunPropertyChange["info"] = {
// `w:id` is attacker-controlled and unbounded in the schema; fold at the
// parse boundary (eigenpal #1093).
id: normalizeRevisionId(parsedId),
author: author.length > 0 ? author : "Unknown",
};
if (date.length > 0) {
info.date = date;
}
if (rsid.length > 0) {
info.rsid = rsid;
}
return info;
}
function parseRunPropertyChanges(
rPr: XmlElement | null,
theme: Theme | null,
styles: StyleMap | null,
currentFormatting: TextFormatting | undefined,
): RunPropertyChange[] | undefined {
if (!rPr) {
return undefined;
}
const changes = findChildren(rPr, "w", "rPrChange")
.map((changeElement): RunPropertyChange => {
const previousRPr = findChild(changeElement, "w", "rPr");
const change: RunPropertyChange = {
type: "runPropertyChange",
info: parsePropertyChangeInfo(changeElement),
};
const previousFormatting = parseRunProperties(previousRPr, theme, styles ?? undefined);
if (previousFormatting) {
change.previousFormatting = previousFormatting;
}
if (currentFormatting) {
change.currentFormatting = currentFormatting;
}
return change;
})
.filter((change) => change.previousFormatting || change.currentFormatting);
return changes.length > 0 ? changes : undefined;
}
/**
* Parse text content (w:t)
*/
function parseTextContent(element: XmlElement): TextContent {
const text = getTextContent(element);
const preserveSpace = getAttribute(element, "xml", "space") === "preserve";
const content: TextContent = { type: "text", text };
if (preserveSpace) {
content.preserveSpace = true;
}
return content;
}
/**
* Parse tab element (w:tab)
*/
function parseTabContent(): TabContent {
return { type: "tab" };
}
/**
* Parse break element (w:br)
*/
function parseBreakContent(element: XmlElement): BreakContent {
const breakType = getAttribute(element, "w", "type");
const clear = getAttribute(element, "w", "clear");
const content: BreakContent = { type: "break" };
if (breakType === "page" || breakType === "column" || breakType === "textWrapping") {
content.breakType = breakType;
}
if (clear === "none" || clear === "left" || clear === "right" || clear === "all") {
content.clear = clear;
}
return content;
}
/**
* Parse symbol element (w:sym)
*/
function parseSymbolContent(element: XmlElement): SymbolContent {
const font = getAttribute(element, "w", "font") ?? "";
const char = getAttribute(element, "w", "char") ?? "";
return {
type: "symbol",
font,
char,
};
}
/**
* Parse footnote reference (w:footnoteReference)
*/
function parseFootnoteReference(element: XmlElement): NoteReferenceContent {
const id = parseNumericAttribute(element, "w", "id") ?? 0;
return {
type: "footnoteRef",
id,
};
}
/**
* Parse endnote reference (w:endnoteReference)
*/
function parseEndnoteReference(element: XmlElement): NoteReferenceContent {
const id = parseNumericAttribute(element, "w", "id") ?? 0;
return {
type: "endnoteRef",
id,
};
}
/**
* Parse field character (w:fldChar)
*/
function parseFieldChar(element: XmlElement): FieldCharContent {
const fldCharType = getAttribute(element, "w", "fldCharType");
const fldLock =
getAttribute(element, "w", "fldLock") === "true" ||
getAttribute(element, "w", "fldLock") === "1";
const dirty =
getAttribute(element, "w", "dirty") === "true" || getAttribute(element, "w", "dirty") === "1";
let charType: FieldCharContent["charType"] = "begin";
if (fldCharType === "separate") {
charType = "separate";
} else if (fldCharType === "end") {
charType = "end";
}
const content: FieldCharContent = { type: "fieldChar", charType };
if (fldLock) {
content.fldLock = true;
}
if (dirty) {
content.dirty = true;
}
// Self-numbering fields (LISTNUM, AUTONUM, …) often skip the `separate`
// run and stash their last-rendered display value on a `<w:numberingChange
// w:original="…"/>` child of the end fldChar instead. Capture it so the
// paragraph parser can fall back to it when the field carries no result.
const numberingChange = findChild(element, "w", "numberingChange");
if (numberingChange) {
const original = getAttribute(numberingChange, "w", "original");
if (original !== null) {
content.originalValue = original;
}
}
return content;
}
/**
* Parse instruction text (w:instrText)
*/
function parseInstrText(element: XmlElement): InstrTextContent {
const text = getTextContent(element);
return {
type: "instrText",
text,
};
}
/**
* Parse drawing content (w:drawing).
*
* Dispatches by graphicData payload:
* - `pic:pic` → image (handled by imageParser).
* - `wps:wsp` with `<wps:txbx>` → text-box; returns null so
* `blockContentParser.enrichParagraphTextBoxes` can rebuild the shape
* with its inner paragraph content (it needs the style/numbering/theme
* context that is only available at the block parser level).
* - `wps:wsp` without text body → generic shape; parsed via
* `shapeParser.parseShapeFromDrawing` into a `ShapeContent`.
*/
function parseDrawingContent(
element: XmlElement,
rels: RelationshipMap | null,
media: Map<string, MediaFile> | null,
): DrawingContent | ShapeContent | null {
const groupImage = parseGroupDrawing(element, rels ?? undefined, media ?? undefined);
if (groupImage) {
return { type: "drawing", image: groupImage, rawXml: elementToXml(element) };
}
if (shouldPreserveRawShapeDrawing(element)) {
return {
type: "drawing",
image: {
type: "image",
rId: "",
size: { width: 0, height: 0 },
wrap: { type: "inline" },
},
rawXml: elementToXml(element),
};
}
// Generic shapes (rect/ellipse/line/arrow/...) come in here as wps:wsp
// with no text body. Text-box shapes are left for the block-content
// post-pass; image drawings fall through to parseImage.
const shape = parseShapeFromDrawing(element);
if (shape) {
return { type: "shape", shape };
}
const image = parseImage(element, rels ?? undefined, media ?? undefined);
if (!image) {
return null;
}
const drawing: DrawingContent = {
type: "drawing",
image,
};
if (!image.src) {
drawing.rawXml = elementToXml(element);
}
return drawing;
}
/**
* Get the local name of an element (without namespace prefix)
*/
function getLocalName(name: string | undefined): string {
if (!name) {
return "";
}
const colonIndex = name.indexOf(":");
return colonIndex !== -1 ? name.slice(colonIndex + 1) : name;
}
/**
* Parse all content within a run element
*/
function parseRunContents(
runElement: XmlElement,
rels: RelationshipMap | null,
media: Map<string, MediaFile> | null,
rootXmlns: Record<string, string> = {},
): RunContent[] {
const contents: RunContent[] = [];
const children = getChildElements(runElement);
for (const child of children) {
const localName = getLocalName(child.name);
switch (localName) {
case "t":
// Text content
contents.push(parseTextContent(child));
break;
case "tab":
// Tab character
contents.push(parseTabContent());
break;
case "br":
// Line/page/column break
contents.push(parseBreakContent(child));
break;
case "sym":
// Symbol character
contents.push(parseSymbolContent(child));
break;
case "footnoteReference":
// Footnote reference
contents.push(parseFootnoteReference(child));
break;
case "endnoteReference":
// Endnote reference
contents.push(parseEndnoteReference(child));
break;
case "fldChar":
// Field character (begin/separate/end)
contents.push(parseFieldChar(child));
break;
case "instrText":
// Field instruction text
contents.push(parseInstrText(child));
break;
case "softHyphen": {
const softHyphen: SoftHyphenContent = { type: "softHyphen" };
contents.push(softHyphen);
break;
}
case "noBreakHyphen": {
const noBreakHyphen: NoBreakHyphenContent = { type: "noBreakHyphen" };
contents.push(noBreakHyphen);
break;
}
case "drawing": {
// Drawing/image
const drawing = parseDrawingContent(child, rels, media);
if (drawing) {
contents.push(drawing);
}
break;
}
case "pict": {
// Legacy VML inline picture (e.g. an old-format header logo). Resolve
// it to the same drawing/image node a DrawingML image produces so it
// renders through the existing image path; the original VML round-trips
// verbatim via the drawing's rawXml.
const vmlDrawing = parseVmlImageContent(child, rels, media, rootXmlns);
if (vmlDrawing) {
contents.push(vmlDrawing);
}
break;
}
case "object": {
// Embedded objects can carry a relationship-backed VML preview. Route
// that preview through the image path while retaining the source XML.
const objectPreview = parseVmlImageContent(child, rels, media, rootXmlns);
if (objectPreview) {
contents.push(objectPreview);
}
break;
}