-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtoFlowBlocks.ts
More file actions
3273 lines (3068 loc) · 106 KB
/
Copy pathtoFlowBlocks.ts
File metadata and controls
3273 lines (3068 loc) · 106 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
/**
* ProseMirror to FlowBlock Converter
*
* Converts a ProseMirror document into FlowBlock[] for the layout engine.
* Tracks pmStart/pmEnd positions for click-to-position mapping.
*/
import type { Node as PMNode, Mark } from "prosemirror-model";
import { convertBulletToUnicode } from "../../docx/bulletMarkers";
import { resolveDocumentGridLinePitch } from "../../docx/documentGrid";
import { padDecimal } from "../../docx/numberingParser";
import type {
FlowBlock,
ParagraphBlock,
TableBlock,
TableRow,
TableCell,
CellBorders,
BorderStyle,
ImageBlock,
TextBoxBlock,
PageBreakBlock,
ColumnBreakBlock,
SectionBreakBlock,
Run,
TextRun,
TabRun,
ImageRun,
FieldRun,
RunFormatting,
ParagraphAttrs,
SdtGroup,
TabStop,
FloatingTablePosition,
} from "../../layout-engine/types";
import { setTextBoxGroupId } from "../../layout-engine/textBoxGroup";
import { setParagraphFrame } from "../../layout-engine/paragraphFrame";
import { DEFAULT_TEXTBOX_MARGINS, DEFAULT_TEXTBOX_WIDTH } from "../../layout-engine/types";
import { getColumns } from "../sectionColumns";
import {
expectBlockSdtAttrs,
expectCharacterSpacingMarkAttrs,
expectCommentMarkAttrs,
expectEmphasisMarkAttrs,
expectFieldAttrs,
expectFontFamilyMarkAttrs,
expectLanguageMarkAttrs,
expectFontSizeMarkAttrs,
expectFootnoteRefMarkAttrs,
expectHardBreakAttrs,
expectHighlightMarkAttrs,
expectHyperlinkMarkAttrs,
expectImageAttrs,
expectMathAttrs,
expectParagraphAttrs,
expectRunFormattingOverrideMarkAttrs,
expectRunShadingMarkAttrs,
expectTableAttrs,
expectTableCellAttrs,
expectTableRowAttrs,
expectTextBoxAttrs,
expectTextColorMarkAttrs,
expectTextEffectMarkAttrs,
expectTrackedChangeMarkAttrs,
expectUnderlineMarkAttrs,
} from "../../prosemirror/attrs";
import { autospacingMatchesBase } from "../../prosemirror/autospacingBase";
import { runShadingAttrsToShading } from "../../prosemirror/conversion/runShadingMark";
import { directionIsRtl } from "../../prosemirror/paragraphDirection";
import type { RunFormattingOverrideAttrs } from "../../prosemirror/schema/marks";
import type {
ImageAttrs,
ParagraphAttrs as PMParagraphAttrs,
} from "../../prosemirror/schema/nodes";
import { assertValidProseMirrorDocument } from "../../prosemirror/validation";
import type {
ColorValue,
Theme,
SectionProperties,
NumberFormat,
TextFormatting,
} from "../../types/document";
import { NUMBER_FORMAT_VALUES } from "../../types/documentEnumValues";
import { resolveColor, resolveHighlightToCss } from "../../utils/colorResolver";
import { resolveThemeFont } from "../../utils/fontResolver";
import { resolveShadingFill } from "../../utils/formatToStyle";
import {
AUTO_PARAGRAPH_SPACING_PX,
pointsToPixels,
halfPointsToPixels,
halfPointsToPoints,
} from "../../utils/units";
import { groupParagraphFrames } from "./paragraphFrames";
/**
* Options for the conversion.
*/
export type ToFlowBlocksOptions = {
/** Default font family. */
defaultFont?: string;
/** Default font size in points. */
defaultSize?: number;
/** Theme for resolving theme colors. */
theme?: Theme | null;
/** Page content height in pixels (pageHeight - marginTop - marginBottom). Images taller than this are scaled down to fit. */
pageContentHeight?: number;
/** Shared list counters for nested containers. */
listCounters?: Map<number, number[]>;
/** Latest concrete counters by abstract numbering definition. */
listAbstractCounters?: Map<number, number[]>;
/** Shared startOverride state for nested containers. */
listSeenNumIds?: Set<string>;
/**
* Parallel counter state for the "original" (pre-revision) document, used to
* number tracked-deletion list items. Word numbers inserted and deleted list
* runs as if they never coexist: insertions get final-document numbering,
* deletions keep their original numbering. Without a separate stream a deleted
* item continues the counter of the inserted item before it (a, b → c, d, e
* instead of a, b and a, b, c). Normal items advance both streams.
*/
originalListCounters?: Map<number, number[]>;
/** Latest concrete original-stream counters by abstract numbering definition. */
originalListAbstractCounters?: Map<number, number[]>;
/** Original-stream startOverride state. */
originalListSeenNumIds?: Set<string>;
/**
* Document-wide `w:defaultTabStop` (§17.6.13) in twips. Stamped onto
* every paragraph block so paragraph-local layout helpers (list marker
* tab-stop math) can read it without taking a `Document` reference.
* Defaults to the OOXML 720-twip value when absent.
*/
defaultTabStopTwips?: number;
/** Document-wide custom Word line-breaking settings. */
lineBreakRules?: {
noLineBreaksBefore?: { language?: string; characters: string };
noLineBreaksAfter?: { language?: string; characters: string };
useLegacyEthiopicAmharicRules?: boolean;
};
/** Document-generation policy for justified line fitting. */
justificationCompatibility?: NonNullable<ParagraphAttrs["justificationCompatibility"]>;
/** Document-wide automatic hyphenation policy. */
automaticHyphenation?: NonNullable<ParagraphAttrs["automaticHyphenation"]>;
/** Line pitch for the final body section, whose properties live outside the PM body. */
finalSectionDocumentGridLinePitchTwips?: number;
};
const DEFAULT_FONT = "Calibri";
const DEFAULT_TABLE_CELL_MARGIN_TWIPS = {
top: 0,
right: 108,
bottom: 0,
left: 108,
} as const;
type TablePaddingSide = keyof typeof DEFAULT_TABLE_CELL_MARGIN_TWIPS;
const DEFAULT_BLACK_TEXT_COLOR_VALUES = new Set(["000000", "000"]);
function normalizeResolvedTextColor(color: string): string {
return color.trim().toLowerCase().replace(/^#/u, "");
}
function isDefaultBlackResolvedTextColor(color: string): boolean {
return DEFAULT_BLACK_TEXT_COLOR_VALUES.has(normalizeResolvedTextColor(color));
}
function areResolvedTextColorsEqual(left: string, right: string): boolean {
return normalizeResolvedTextColor(left) === normalizeResolvedTextColor(right);
}
/**
* Constrain image dimensions to fit within the page content area.
* Scales proportionally if height exceeds pageContentHeight.
*/
function constrainImageToPage(
width: number,
height: number,
pageContentHeight: number | undefined,
): { width: number; height: number } {
if (!pageContentHeight || height <= pageContentHeight) {
return { width, height };
}
const scale = pageContentHeight / height;
return { width: Math.round(width * scale), height: pageContentHeight };
}
const DEFAULT_SIZE = 11; // points (Word 2007+ default)
/**
* Convert twips to pixels (1 twip = 1/1440 inch, 1 inch = 96 CSS px).
* No rounding — precision prevents cumulative layout drift across paragraphs.
*/
function twipsToPixels(twips: number): number {
return (twips / 1440) * 96;
}
/**
* Generate a unique block ID.
*/
let blockIdCounter = 0;
function nextBlockId(): string {
return `block-${++blockIdCounter}`;
}
function formatNumberedMarker(counters: number[], level: number): string {
const parts: number[] = [];
for (let i = 0; i <= level; i += 1) {
const value = counters[i] ?? 0;
if (value <= 0) {
break;
}
parts.push(value);
}
if (parts.length === 0) {
return "1.";
}
return `${parts.join(".")}.`;
}
const ROMAN_PAIRS: [number, string][] = [
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100, "C"],
[90, "XC"],
[50, "L"],
[40, "XL"],
[10, "X"],
[9, "IX"],
[5, "V"],
[4, "IV"],
[1, "I"],
];
function toRoman(value: number, upper: boolean): string {
if (value <= 0) {
return "";
}
let remaining = value;
let output = "";
for (const [number, symbol] of ROMAN_PAIRS) {
while (remaining >= number) {
output += symbol;
remaining -= number;
}
}
return upper ? output : output.toLowerCase();
}
function toLetter(value: number, upper: boolean): string {
if (value <= 0) {
return "";
}
const zeroBased = value - 1;
const baseCodePoint = upper ? 65 : 97;
const letter = String.fromCodePoint(baseCodePoint + (zeroBased % 26));
return letter.repeat(Math.floor(zeroBased / 26) + 1);
}
export function formatCounter(value: number, format: NumberFormat | undefined): string {
if (!Number.isFinite(value)) {
return "";
}
// NumberFormat is the OOXML w:numFmt enum (70+ values). This switch
// handles every format whose counter-rendering differs from a simple
// decimal; CJK/Hindi/Arabic counters fall through to the decimal
// default. Matches Word's display when those font glyphs are absent.
switch (format) {
case "upperRoman":
return toRoman(value, true);
case "lowerRoman":
return toRoman(value, false);
case "upperLetter":
return toLetter(value, true);
case "lowerLetter":
return toLetter(value, false);
case "decimalZero":
return padDecimal(value, 2);
case "decimalZero3":
return padDecimal(value, 3);
case "decimalZero4":
return padDecimal(value, 4);
case "decimalZero5":
return padDecimal(value, 5);
case "none":
return "";
default:
return String(value);
}
}
export function resolveListTemplate(
template: string,
counters: number[],
levelFormats: NumberFormat[] | undefined,
forceDecimal = false,
): string {
return template.replace(/%(?<digit>\d)(?<punct>[.):\]])?/gu, (...args) => {
const { digit, punct = "" } = args.at(-1) as {
digit: string;
punct?: string;
};
const index = Number.parseInt(digit, 10) - 1;
if (index < 0) {
return "";
}
const counter = counters[index];
if (counter === undefined || Number.isNaN(counter)) {
return "";
}
const formatted = formatCounter(counter, forceDecimal ? "decimal" : levelFormats?.[index]);
return formatted ? `${formatted}${punct}` : "";
});
}
function getLastListCounters(listCounters: Map<number, number[]>): number[] | undefined {
let lastCounters: number[] | undefined;
for (const counters of listCounters.values()) {
lastCounters = counters;
}
return lastCounters;
}
function applyMarkerAllCaps(marker: string | null, allCaps: boolean | undefined): string | null {
if (marker === null || !allCaps) {
return marker;
}
return marker.toLocaleUpperCase();
}
function computeListMarker(
pmAttrs: PMParagraphAttrs,
listCounters: Map<number, number[]>,
abstractCounters: Map<number, number[]>,
seenNumIds: Set<string>,
): string | null {
const numId = pmAttrs.numPr?.numId;
if (numId === undefined || numId === 0) {
if (pmAttrs.listMarker?.includes("%") && !pmAttrs.listIsBullet) {
const counters = getLastListCounters(listCounters);
if (counters) {
return resolveListTemplate(
pmAttrs.listMarker,
counters,
pmAttrs.listLevelNumFmts,
pmAttrs.listIsLegal,
);
}
}
return null;
}
if (pmAttrs.listIsBullet) {
return convertBulletToUnicode(pmAttrs.listMarker || "");
}
const level = pmAttrs.numPr?.ilvl ?? 0;
const counters =
listCounters.get(numId) ?? (Array.from({ length: 9 }, () => Number.NaN) as number[]);
const abstractNumId = pmAttrs.listAbstractNumId;
if (level > 0) {
const latestAbstractCounters =
abstractNumId === undefined ? undefined : abstractCounters.get(abstractNumId);
if (counters.slice(0, level).every(Number.isNaN)) {
for (let i = 0; i < level; i += 1) {
const latestCounter = latestAbstractCounters?.[i];
counters[i] =
latestCounter !== undefined && !Number.isNaN(latestCounter)
? latestCounter
: (pmAttrs.listLevelStarts?.[i] ?? 1);
}
}
}
const seenKey = `${numId}:${level}`;
if (!seenNumIds.has(seenKey)) {
seenNumIds.add(seenKey);
if (pmAttrs.listStartOverride != null) {
counters[level] = pmAttrs.listStartOverride - 1;
} else if (Number.isNaN(counters[level])) {
counters[level] = (pmAttrs.listLevelStarts?.[level] ?? 1) - 1;
}
}
counters[level] = (counters[level] ?? 0) + 1;
for (let i = level + 1; i < counters.length; i += 1) {
counters[i] = Number.NaN;
}
// Word's default LISTNUM field advances the counter at one ilvl deeper
// than the host paragraph. Carrying the consumed advances forward here
// means a later sibling at that depth (e.g. an OutNum3 "(b)" following an
// OutNum2 "(a)") picks up the next letter instead of restarting at "(a)".
const childAdvances = pmAttrs.listImplicitChildLevelAdvances ?? 0;
if (childAdvances > 0 && level + 1 < counters.length) {
const childCounter = counters[level + 1];
counters[level + 1] =
(childCounter === undefined || Number.isNaN(childCounter) ? 0 : childCounter) + childAdvances;
}
listCounters.set(numId, counters);
if (abstractNumId !== undefined) {
abstractCounters.set(abstractNumId, [...counters]);
}
const levelFormats =
pmAttrs.listLevelNumFmts ?? (pmAttrs.listNumFmt ? [pmAttrs.listNumFmt] : undefined);
if (pmAttrs.listMarker && pmAttrs.listMarker.includes("%")) {
return resolveListTemplate(pmAttrs.listMarker, counters, levelFormats, pmAttrs.listIsLegal);
}
if (pmAttrs.listMarker) {
return pmAttrs.listMarker;
}
// OOXML allows a list level to set lvlText="" with numFmt="none" to attach
// numbering metadata (counters, indents) without painting a marker — Word
// glossary/definition styles use this. An empty listMarker means the level
// explicitly opts out; synthesising a decimal counter here would forge a
// marker the source never authored.
const levelFormat = levelFormats?.[level] ?? pmAttrs.listNumFmt;
if (levelFormat === "none" || pmAttrs.listMarker === "") {
return null;
}
return formatNumberedMarker(counters, level);
}
/**
* Reset the block ID counter (useful for testing).
*/
export function resetBlockIdCounter(): void {
blockIdCounter = 0;
}
/**
* Extract run formatting from ProseMirror marks.
*/
function extractRunFormatting(marks: readonly Mark[], theme?: Theme | null): RunFormatting {
const formatting: RunFormatting = {};
let hasNoteRef = false;
for (const mark of marks) {
switch (mark.type.name) {
case "bold":
formatting.bold = true;
break;
case "italic":
formatting.italic = true;
break;
case "underline": {
const attrs = expectUnderlineMarkAttrs(mark);
if (attrs.style || attrs.color) {
const underlineObj: { style?: string; color?: string } = {};
if (attrs.style) {
underlineObj.style = attrs.style;
}
if (attrs.color) {
underlineObj.color = resolveColor(attrs.color, theme);
}
formatting.underline = underlineObj;
} else {
formatting.underline = true;
}
break;
}
case "strike":
formatting.strike = true;
break;
case "textColor": {
const attrs = expectTextColorMarkAttrs(mark);
if (attrs.themeColor || attrs.rgb) {
const colorArg: ColorValue = {};
if (attrs.rgb) {
colorArg.rgb = attrs.rgb;
}
if (attrs.themeColor) {
colorArg.themeColor = attrs.themeColor;
}
if (attrs.themeTint) {
colorArg.themeTint = attrs.themeTint;
}
if (attrs.themeShade) {
colorArg.themeShade = attrs.themeShade;
}
if (!isAutomaticTextColorValue(colorArg)) {
formatting.color = resolveColor(colorArg, theme);
formatting.textColorSource = "direct";
}
}
break;
}
case "highlight":
formatting.highlight = resolveHighlightToCss(expectHighlightMarkAttrs(mark).color);
break;
case "runShading": {
const shadingCss = resolveShadingFill(
runShadingAttrsToShading(expectRunShadingMarkAttrs(mark)),
theme,
);
if (shadingCss) {
formatting.shading = shadingCss;
}
break;
}
case "fontSize": {
const attrs = expectFontSizeMarkAttrs(mark);
// Convert half-points to points
formatting.fontSize = attrs.size / 2;
break;
}
case "fontFamily": {
const attrs = expectFontFamilyMarkAttrs(mark);
const font = resolveWesternThemeFont(attrs, theme);
if (font) {
formatting.fontFamily = font;
}
const eastAsiaFont = resolveEastAsiaThemeFont(attrs, theme);
if (eastAsiaFont) {
formatting.eastAsiaFontFamily = eastAsiaFont;
}
break;
}
case "language": {
const attrs = expectLanguageMarkAttrs(mark);
formatting.language = {
...(attrs.val ? { val: attrs.val } : {}),
...(attrs.eastAsia ? { eastAsia: attrs.eastAsia } : {}),
...(attrs.bidi ? { bidi: attrs.bidi } : {}),
};
break;
}
case "characterSpacing": {
const attrs = expectCharacterSpacingMarkAttrs(mark);
if (attrs.spacing !== undefined) {
formatting.letterSpacing = twipsToPixels(attrs.spacing);
}
if (attrs.position !== undefined && attrs.position !== 0) {
formatting.positionPx = halfPointsToPixels(attrs.position);
}
if (attrs.scale !== undefined && attrs.scale !== 100) {
formatting.horizontalScale = attrs.scale;
}
if (attrs.kerning !== undefined && attrs.kerning > 0) {
formatting.kerningMinPt = halfPointsToPoints(attrs.kerning);
}
break;
}
case "allCaps":
formatting.allCaps = true;
break;
case "smallCaps":
formatting.smallCaps = true;
break;
case "emboss":
formatting.emboss = true;
break;
case "imprint":
formatting.imprint = true;
break;
case "hidden":
// eigenpal #424 (w:vanish gap 9): mark surfaces RunFormatting.hidden
// so the painter can apply the dimmed dotted-underline treatment.
formatting.hidden = true;
break;
case "textShadow":
formatting.textShadow = true;
break;
case "textOutline":
formatting.textOutline = true;
break;
case "rtl":
formatting.rtl = true;
break;
case "textEffect":
// The textEffect mark schema rejects "none"; only animated variants
// ever reach this branch.
formatting.textEffect = expectTextEffectMarkAttrs(mark).effect;
break;
case "runFormattingOverride":
applyRunFormattingOverrides(formatting, expectRunFormattingOverrideMarkAttrs(mark));
break;
case "emphasisMark": {
formatting.emphasisMark = expectEmphasisMarkAttrs(mark).type ?? "dot";
break;
}
case "superscript":
formatting.superscript = true;
break;
case "subscript":
formatting.subscript = true;
break;
case "hyperlink": {
const attrs = expectHyperlinkMarkAttrs(mark);
const link: RunFormatting["hyperlink"] & object = {
href: attrs.href,
};
if (attrs.tooltip !== undefined) {
link.tooltip = attrs.tooltip;
}
formatting.hyperlink = link;
break;
}
case "footnoteRef": {
hasNoteRef = true;
const attrs = expectFootnoteRefMarkAttrs(mark);
if (attrs.vertAlign === "superscript") {
formatting.superscript = true;
}
const id = typeof attrs.id === "string" ? Number.parseInt(attrs.id, 10) : attrs.id;
if (attrs.noteType === "endnote") {
formatting.endnoteRefId = id;
} else {
formatting.footnoteRefId = id;
}
break;
}
case "comment": {
const commentId = expectCommentMarkAttrs(mark).commentId;
if (commentId) {
if (!formatting.commentIds) {
formatting.commentIds = [];
}
formatting.commentIds.push(commentId);
}
break;
}
case "insertion": {
const attrs = expectTrackedChangeMarkAttrs(mark);
formatting.isInsertion = true;
formatting.changeAuthor = attrs.author;
if (attrs.date !== undefined) {
formatting.changeDate = attrs.date;
}
formatting.changeRevisionId = attrs.revisionId;
if (attrs.provenance === "suggested") {
formatting.isSuggestion = true;
if (attrs.suggestionId) {
formatting.suggestionId = attrs.suggestionId;
}
}
break;
}
case "deletion": {
const attrs = expectTrackedChangeMarkAttrs(mark);
formatting.isDeletion = true;
formatting.changeAuthor = attrs.author;
if (attrs.date !== undefined) {
formatting.changeDate = attrs.date;
}
formatting.changeRevisionId = attrs.revisionId;
if (attrs.provenance === "suggested") {
formatting.isSuggestion = true;
if (attrs.suggestionId) {
formatting.suggestionId = attrs.suggestionId;
}
}
break;
}
default:
break;
}
}
if (hasNoteRef && formatting.subscript) {
delete formatting.superscript;
}
return formatting;
}
type ThemeFontAttributes = {
ascii?: string | null;
hAnsi?: string | null;
eastAsia?: string | null;
asciiTheme?: string | null;
hAnsiTheme?: string | null;
eastAsiaTheme?: string | null;
};
const resolveWesternThemeFont = (
fontFamily: ThemeFontAttributes,
theme?: Theme | null,
): string | undefined => {
const themeRef = fontFamily.asciiTheme ?? fontFamily.hAnsiTheme;
const themedFont = themeRef ? resolveThemeFont(themeRef, theme?.fontScheme) : null;
return themedFont ?? fontFamily.ascii ?? fontFamily.hAnsi ?? undefined;
};
const resolveEastAsiaThemeFont = (
fontFamily: ThemeFontAttributes,
theme?: Theme | null,
): string | undefined => {
const themedFont = fontFamily.eastAsiaTheme
? resolveThemeFont(fontFamily.eastAsiaTheme, theme?.fontScheme)
: null;
return themedFont ?? fontFamily.eastAsia ?? undefined;
};
function isAutomaticTextColorValue(color: ColorValue): boolean {
const rgb = color.rgb?.trim().toLowerCase();
return color.auto === true || rgb === "auto" || (!rgb && !color.themeColor);
}
function markDefaultBlackTextColorSource(
formatting: RunFormatting,
paraDefaults: RunFormatting,
): RunFormatting {
if (
formatting.textColorSource === "direct" ||
formatting.color === undefined ||
paraDefaults.color === undefined ||
!isDefaultBlackResolvedTextColor(formatting.color) ||
!areResolvedTextColorsEqual(formatting.color, paraDefaults.color)
) {
return formatting;
}
return {
...formatting,
textColorSource: "paragraphDefault",
};
}
function mergeRunFormatting(paraDefaults: RunFormatting, formatting: RunFormatting): RunFormatting {
const merged = {
...paraDefaults,
...markDefaultBlackTextColorSource(formatting, paraDefaults),
};
if (merged.letterSpacing === 0) {
delete merged.letterSpacing;
}
return merged;
}
function applyRunFormattingOverrides(
formatting: RunFormatting,
attrs: RunFormattingOverrideAttrs,
): void {
if (attrs.bold === false) {
formatting.bold = false;
}
if (attrs.italic === false) {
formatting.italic = false;
}
if (attrs.underline === "none") {
formatting.underline = false;
}
if (attrs.strike === false) {
formatting.strike = false;
}
if (attrs.allCaps === false) {
formatting.allCaps = false;
}
if (attrs.smallCaps === false) {
formatting.smallCaps = false;
}
if (attrs.emboss === false) {
formatting.emboss = false;
}
if (attrs.imprint === false) {
formatting.imprint = false;
}
if (attrs.shadow === false) {
formatting.textShadow = false;
}
if (attrs.outline === false) {
formatting.textOutline = false;
}
if (attrs.rtl === false) {
formatting.rtl = false;
}
}
function paragraphRunDefaults(pmAttrs: PMParagraphAttrs, theme?: Theme | null): RunFormatting {
const defaultTextFormatting = pmAttrs.defaultTextFormatting as TextFormatting | undefined;
if (!defaultTextFormatting) {
return {};
}
const result: RunFormatting = {};
const fontFamily = defaultTextFormatting.fontFamily
? resolveWesternThemeFont(defaultTextFormatting.fontFamily, theme)
: undefined;
if (fontFamily) {
result.fontFamily = fontFamily;
}
// East-Asian font inherited from the paragraph style / docDefaults, so CJK
// runs without a direct `w:eastAsia` still get per-character EA selection. A
// run's own fontFamily mark overrides this via mergeRunFormatting.
const eastAsiaFontFamily = defaultTextFormatting.fontFamily
? resolveEastAsiaThemeFont(defaultTextFormatting.fontFamily, theme)
: undefined;
if (eastAsiaFontFamily) {
result.eastAsiaFontFamily = eastAsiaFontFamily;
}
if (defaultTextFormatting.language) {
result.language = { ...defaultTextFormatting.language };
}
if (defaultTextFormatting.fontSize !== undefined) {
result.fontSize = defaultTextFormatting.fontSize / 2;
}
if (defaultTextFormatting.bold !== undefined) {
result.bold = defaultTextFormatting.bold;
}
if (defaultTextFormatting.italic !== undefined) {
result.italic = defaultTextFormatting.italic;
}
if (defaultTextFormatting.underline && defaultTextFormatting.underline.style !== "none") {
result.underline = { style: defaultTextFormatting.underline.style };
if (defaultTextFormatting.underline.color) {
result.underline.color = resolveColor(defaultTextFormatting.underline.color, theme);
}
}
if (defaultTextFormatting.strike !== undefined) {
result.strike = defaultTextFormatting.strike;
}
if (defaultTextFormatting.color && !isAutomaticTextColorValue(defaultTextFormatting.color)) {
result.color = resolveColor(defaultTextFormatting.color, theme);
result.textColorSource = "paragraphDefault";
}
if (defaultTextFormatting.highlight) {
const highlight = resolveHighlightToCss(defaultTextFormatting.highlight);
if (highlight) {
result.highlight = highlight;
}
}
if (defaultTextFormatting.vertAlign === "superscript") {
result.superscript = true;
}
if (defaultTextFormatting.vertAlign === "subscript") {
result.subscript = true;
}
if (defaultTextFormatting.allCaps !== undefined) {
result.allCaps = defaultTextFormatting.allCaps;
}
if (defaultTextFormatting.smallCaps !== undefined) {
result.smallCaps = defaultTextFormatting.smallCaps;
}
if (defaultTextFormatting.spacing !== undefined && defaultTextFormatting.spacing !== 0) {
result.letterSpacing = twipsToPixels(defaultTextFormatting.spacing);
}
if (defaultTextFormatting.position !== undefined && defaultTextFormatting.position !== 0) {
result.positionPx = halfPointsToPixels(defaultTextFormatting.position);
}
if (defaultTextFormatting.scale !== undefined && defaultTextFormatting.scale !== 100) {
result.horizontalScale = defaultTextFormatting.scale;
}
if (defaultTextFormatting.kerning !== undefined && defaultTextFormatting.kerning > 0) {
result.kerningMinPt = halfPointsToPoints(defaultTextFormatting.kerning);
}
if (defaultTextFormatting.emboss !== undefined) {
result.emboss = defaultTextFormatting.emboss;
}
if (defaultTextFormatting.imprint !== undefined) {
result.imprint = defaultTextFormatting.imprint;
}
if (defaultTextFormatting.shadow !== undefined) {
result.textShadow = defaultTextFormatting.shadow;
}
if (defaultTextFormatting.outline !== undefined) {
result.textOutline = defaultTextFormatting.outline;
}
if (defaultTextFormatting.emphasisMark && defaultTextFormatting.emphasisMark !== "none") {
result.emphasisMark = defaultTextFormatting.emphasisMark;
}
return result;
}
/**
* Build an ImageRun from ProseMirror node attrs, applying conditional property assignment
* to satisfy exactOptionalPropertyTypes.
*/
function buildImageRun(
attrs: ImageAttrs,
constrained: { width: number; height: number },
pmStart: number,
pmEnd: number,
// Tracked-change attrs lifted off the image node's PM marks. eigenpal #641.
trackedChange?: Pick<
RunFormatting,
"isInsertion" | "isDeletion" | "changeAuthor" | "changeDate" | "changeRevisionId"
>,
): ImageRun {
const run: ImageRun = {
kind: "image",
src: attrs.src,
width: constrained.width,
height: constrained.height,
pmStart,
pmEnd,
};
if (attrs.alt !== undefined) {
run.alt = attrs.alt;
}
if (attrs.transform !== undefined) {
run.transform = attrs.transform;
}
// eigenpal #424 (opacity render pipeline): copy opacity verbatim. PM
// schema defaults `opacity` to `null`, which survives the typed cast on
// ImageAttrs (`number | undefined`). Gate with `!= null` so the model
// never carries the schema sentinel.
if (attrs.opacity != null) {
run.opacity = attrs.opacity;
}
if (attrs.wrapType !== undefined) {
run.wrapType = attrs.wrapType;
}
if (attrs.displayMode !== undefined) {
run.displayMode = attrs.displayMode;
}
if (attrs.cssFloat !== undefined) {
run.cssFloat = attrs.cssFloat;
}
if (attrs.distTop !== undefined) {
run.distTop = attrs.distTop;
}
if (attrs.distBottom !== undefined) {
run.distBottom = attrs.distBottom;
}
if (attrs.distLeft !== undefined) {
run.distLeft = attrs.distLeft;
}
if (attrs.distRight !== undefined) {
run.distRight = attrs.distRight;
}
if (attrs._docxObjectPreview === true) {
run.exactLineHeight = true;
}
// eigenpal #424: pass crop fractions through to the painter so it can
// emit CSS clip-path. PM defaults are `null`; treat null as "not set".
if (attrs.cropTop != null) {
run.cropTop = attrs.cropTop;
}
if (attrs.cropRight != null) {
run.cropRight = attrs.cropRight;
}
if (attrs.cropBottom != null) {
run.cropBottom = attrs.cropBottom;
}
if (attrs.cropLeft != null) {
run.cropLeft = attrs.cropLeft;
}
// eigenpal #1096: image borders are authored on the PM image attrs and
// painted by layout-painter. PM defaults are null; treat null as absent.
if (attrs.borderWidth != null) {
run.borderWidth = attrs.borderWidth;
}
if (attrs.borderColor) {
run.borderColor = attrs.borderColor;
}
if (attrs.borderStyle) {
run.borderStyle = attrs.borderStyle;
}
if (attrs.position !== undefined) {
run.position = attrs.position;
}
if (attrs.layoutInCell !== undefined) {
run.layoutInCell = attrs.layoutInCell;
}
if (trackedChange?.isInsertion) {
run.isInsertion = true;
}
if (trackedChange?.isDeletion) {
run.isDeletion = true;
}
if (trackedChange?.changeAuthor !== undefined) {
run.changeAuthor = trackedChange.changeAuthor;
}
if (trackedChange?.changeDate !== undefined) {
run.changeDate = trackedChange.changeDate;
}
if (trackedChange?.changeRevisionId !== undefined) {
run.changeRevisionId = trackedChange.changeRevisionId;
}
return run;
}