-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrenderParagraph.ts
More file actions
2975 lines (2734 loc) · 112 KB
/
Copy pathrenderParagraph.ts
File metadata and controls
2975 lines (2734 loc) · 112 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
/**
* Paragraph Fragment Renderer
*
* Renders paragraph fragments with lines and text runs to DOM.
* Handles text formatting, alignment, and positioning.
*/
import { ommlToMathml } from "../docx/mathToMathml";
import { parseXmlDocument } from "../docx/xmlParser";
import { evaluateFieldInstruction } from "../fields/evaluateField";
import type { FieldContext } from "../fields/fieldContext";
import {
getListMarkerInlineWidth,
getListMarkerVisualOffset,
} from "../layout-engine/measure/listMarkerWidth";
import { DEFAULT_FONT_SIZE } from "../layout-engine/measure/measureHelpers";
import {
FONT_KERNING_MODE,
countCompressibleSpaces,
getFontKerningMode,
getRunFontKerningMode,
toPaintedText,
} from "../layout-engine/measure/textMeasurementPolicy";
import type {
ParagraphBlock,
ParagraphMeasure,
ParagraphFragment,
ParagraphBorders,
BorderStyle,
MeasuredLine,
Run,
TextRun,
TabRun,
ImageRun,
LineBreakRun,
FieldRun,
MathRun,
TabStop,
ParagraphAttrs,
} from "../layout-engine/types";
import { calculateTabWidth } from "../prosemirror/utils/tabCalculator";
import type { TabContext, TabStop as TabCalcStop } from "../prosemirror/utils/tabCalculator";
import { getAuthorColorIdx, AUTHOR_COLORS } from "../utils/authorColors";
import { detectBaseDirection } from "../utils/baseDirection";
import { resolveFontFamily } from "../utils/fontResolver";
import { DOCX_BOLD_FONT_WEIGHT } from "../utils/fontWeights";
import { applySanitizedImageSrc } from "../utils/sanitizeImageSrc";
import {
inlineImageBoundingBox,
parseRotationDegrees,
rotatedBoundingBox,
} from "../utils/rotationBoundingBox";
import { hasCjk, segmentByScript } from "../utils/scriptSegments";
import { borderStrokeToCss, resolveParagraphBorderHorizontalOutsets } from "./borderStroke";
import { getAutomaticTextColorForBackground } from "./documentColors";
import {
applyImageBorder,
applyImageVisualAttrs,
hasImageCrop,
hasImageVisualAttrs,
wrapImageWithCrop,
} from "./renderImage";
import { isFloatingImageRun, resolveImageLineAlign } from "./renderUtils";
import type { RenderContext } from "./renderUtils";
import { applySdtDataAttrs } from "./sdtBoundary";
/**
* CSS class names for paragraph rendering
*/
export const PARAGRAPH_CLASS_NAMES = {
fragment: "layout-paragraph",
line: "layout-line",
run: "layout-run",
text: "layout-run-text",
tab: "layout-run-tab",
image: "layout-run-image",
lineBreak: "layout-run-linebreak",
};
// Text wrapping around floating images is implemented via measurement-time
// per-line leftOffset/rightOffset. renderPage.ts re-measures paragraphs with
// FloatingImageZone[] when floating images are present on the page.
/**
* Options for rendering a paragraph
*/
export type RenderParagraphOptions = {
/** Document to create elements in */
document?: Document;
/** Fragment's Y position relative to content area (for per-line margin calculation) */
fragmentContentY?: number;
/** Borders from the previous adjacent paragraph (for border grouping) */
prevBorders?: ParagraphBorders;
/** Borders from the next adjacent paragraph (for border grouping) */
nextBorders?: ParagraphBorders;
/** Inline image runs already rendered for this paragraph block */
renderedInlineImageKeys?: Set<string>;
};
/**
* Check if run is a text run
*/
function isTextRun(run: Run): run is TextRun {
return run.kind === "text";
}
/**
* Check if run is a tab run
*/
function isTabRun(run: Run): run is TabRun {
return run.kind === "tab";
}
/**
* Check if run is an image run
*/
function isImageRun(run: Run): run is ImageRun {
return run.kind === "image";
}
/**
* Check if run is a line break run
*/
function isLineBreakRun(run: Run): run is LineBreakRun {
return run.kind === "lineBreak";
}
/**
* Check if run is a field run
*/
function isFieldRun(run: Run): run is FieldRun {
return run.kind === "field";
}
/**
* Check if run is a math equation run
*/
function isMathRun(run: Run): run is MathRun {
return run.kind === "math";
}
const AUTOMATIC_TEXT_COLOR_VALUES = new Set(["auto", "windowtext"]);
const DEFAULT_BLACK_TEXT_COLOR_VALUES = new Set(["000000", "000"]);
const DOCX_SUPERSCRIPT_SCALE = 0.75;
// Suggested (AI-proposed) tracked changes render with a dotted stroke and a
// dedicated hue, distinct from the per-author redline palette. Driven by the
// `--suggestion-color` / `--suggestion-bg` CSS custom properties (editor.css);
// the inline fallbacks keep the painted canvas legible without the stylesheet.
const SUGGESTION_COLOR_CSS = "var(--suggestion-color, #6d3bd6)";
const SUGGESTION_TINT_CSS = "var(--suggestion-bg, color-mix(in oklch, #6d3bd6 12%, transparent))";
// The tint is layered as a translucent background-image so authored
// highlight/shading (w:highlight / w:shd) and the comment highlight — both
// painted via background-color earlier in applyRunStyles — stay visible
// underneath the proposal wash instead of being replaced by it.
const SUGGESTION_TINT_LAYER_CSS = `linear-gradient(${SUGGESTION_TINT_CSS}, ${SUGGESTION_TINT_CSS})`;
function normalizeTextColorValue(color: string): string {
return color.trim().toLowerCase().replace(/^#/u, "");
}
function isAutomaticTextColor(color: string): boolean {
return AUTOMATIC_TEXT_COLOR_VALUES.has(normalizeTextColorValue(color));
}
function isDefaultBlackTextColor(color: string): boolean {
return DEFAULT_BLACK_TEXT_COLOR_VALUES.has(normalizeTextColorValue(color));
}
function shouldRenderTextColor(
color: string,
highlight: string | undefined,
textColorSource: TextRun["textColorSource"],
): boolean {
if (isAutomaticTextColor(color)) {
return false;
}
if (highlight) {
return textColorSource !== "paragraphDefault" || !isDefaultBlackTextColor(color);
}
return !isDefaultBlackTextColor(color);
}
function getRenderableTextColor(run: TextRun | TabRun): string | undefined {
const textColor = run.color;
if (!textColor) {
return undefined;
}
if (!shouldRenderTextColor(textColor, run.highlight, run.textColorSource)) {
return undefined;
}
return textColor.trim();
}
function getHyperlinkTextColor(run: TextRun, inheritedColor: string): string {
const textColor = run.color?.trim();
if (textColor && !isAutomaticTextColor(textColor) && run.textColorSource === "direct") {
return textColor;
}
return getRenderableTextColor(run) || inheritedColor || "#0563c1";
}
function fontSizePtToPx(fontSizePt: number): number {
return (fontSizePt * 96) / 72;
}
function getRaisedRunFontSize(run: TextRun | TabRun): string {
if (run.fontSize) {
return `${fontSizePtToPx(run.fontSize) * DOCX_SUPERSCRIPT_SCALE}px`;
}
return `${DOCX_SUPERSCRIPT_SCALE}em`;
}
/**
* Apply text run styles to an element
*/
function applyRunStyles(element: HTMLElement, run: TextRun | TabRun): void {
// Font properties
if (run.fontFamily) {
// Use the font resolver for category-appropriate fallback stacks,
// matching the same stacks used in measureContainer.ts
element.style.fontFamily = resolveFontFamily(run.fontFamily).cssFallback;
}
if (run.fontSize) {
// fontSize is in points - convert to pixels to match Canvas measurement
// (1pt = 96/72 px at standard web DPI)
// Using px ensures consistent rendering with Canvas-based measurements
element.style.fontSize = `${fontSizePtToPx(run.fontSize)}px`;
}
if (run.bold) {
element.style.fontWeight = DOCX_BOLD_FONT_WEIGHT;
}
if (run.italic) {
element.style.fontStyle = "italic";
}
// Color — black/auto are skipped so --doc-canvas-text can adapt to dark mode.
// Explicit colors are exposed as a custom property (--doc-run-color) and read
// back via var(); dark mode then inverts their lightness with relative-color
// CSS (hue/chroma preserved), matching Word's dark-mode rendering instead of
// leaving authored colors dim on the dark canvas.
let hasExplicitTextColor = false;
const textColor = getRenderableTextColor(run);
if (textColor) {
element.style.color = textColor;
// Also expose the authored color so dark mode can invert its lightness
// (hue/chroma preserved) via relative-color CSS. The dark rule overrides
// this inline color with !important; light mode keeps it verbatim.
element.style.setProperty("--doc-run-color", textColor);
hasExplicitTextColor = true;
}
// Letter spacing
if (run.letterSpacing) {
element.style.letterSpacing = `${run.letterSpacing}px`;
}
if (run.allCaps) {
element.style.textTransform = "uppercase";
}
if (run.smallCaps) {
element.style.fontVariant = "small-caps";
}
if (run.positionPx) {
element.style.verticalAlign = `${run.positionPx}px`;
}
if (run.horizontalScale && run.horizontalScale !== 100) {
element.style.display = "inline-block";
element.style.transform = `scaleX(${run.horizontalScale / 100})`;
element.style.transformOrigin = "left center";
}
element.style.fontKerning = getRunFontKerningMode(run, DEFAULT_FONT_SIZE);
if (run.emboss) {
element.style.textShadow = "1px 1px 1px rgba(255,255,255,0.5), -1px -1px 1px rgba(0,0,0,0.3)";
}
if (run.imprint) {
element.style.textShadow = "-1px -1px 1px rgba(255,255,255,0.5), 1px 1px 1px rgba(0,0,0,0.3)";
}
if (run.textShadow && !run.emboss && !run.imprint) {
element.style.textShadow = "1px 1px 2px rgba(0,0,0,0.3)";
}
if (run.textOutline) {
element.style.webkitTextStroke = "1px currentColor";
(
element.style as CSSStyleDeclaration & {
webkitTextFillColor?: string;
}
).webkitTextFillColor = "transparent";
}
// Per-run RTL direction (w:rtl). The browser's bidi algorithm reorders
// just this run, independent of the paragraph direction. `false` is an
// explicit override that disables inherited paragraph/style RTL.
if (run.rtl === true) {
element.dir = "rtl";
} else if (run.rtl === false) {
element.dir = "ltr";
}
// Text effect animation (w:effect). Host CSS opts in to the actual
// animation via the docx-text-effect-<name> class plus data-effect.
if (run.textEffect) {
element.classList.add("docx-text-effect", `docx-text-effect-${run.textEffect}`);
element.dataset["effect"] = run.textEffect;
}
if (run.emphasisMark) {
let variant = "filled dot";
if (run.emphasisMark === "comma") {
variant = "filled sesame";
} else if (run.emphasisMark === "circle") {
variant = "filled circle";
}
const position = run.emphasisMark === "underDot" ? "under right" : "over right";
element.style.textEmphasis = variant;
element.style.textEmphasisPosition = position;
(element.style as CSSStyleDeclaration & { webkitTextEmphasis?: string }).webkitTextEmphasis =
variant;
(
element.style as CSSStyleDeclaration & {
webkitTextEmphasisPosition?: string;
}
).webkitTextEmphasisPosition = position;
}
// Hidden run (OOXML w:vanish, §17.3.2.41). Word's print/normal view
// suppresses hidden text entirely, but in editing view it draws the
// run dimmed with a dotted underline so the author can still navigate
// to and edit it. Mirror that: keep the run in flow and selectable —
// `display: none` would orphan PM positions and break cursor movement
// across hidden ranges. The `docx-hidden` class hook lets host CSS
// swap to print-style suppression when a future view-mode toggle ships.
// eigenpal #424 (w:vanish gap 9)
if (run.hidden) {
element.classList.add("docx-hidden");
element.style.opacity = "0.4";
}
// Background color: an explicit highlight (w:highlight) wins over run shading
// (w:shd). Folio carries arbitrary run-background fills as `shading` because
// they fall outside the OOXML named-highlight palette. eigenpal #722 (#712).
const runBackground = run.highlight ?? run.shading;
if (runBackground) {
element.style.backgroundColor = runBackground;
const hasTrackedChangeColor = run.isInsertion || run.isDeletion;
const hasCommentHighlight = run.commentIds !== undefined && run.commentIds.length > 0;
const automaticTextColor =
hasExplicitTextColor || hasTrackedChangeColor || hasCommentHighlight
? undefined
: getAutomaticTextColorForBackground(runBackground);
if (automaticTextColor) {
element.style.color = automaticTextColor;
}
}
// Text decorations
const decorations: string[] = [];
let explicitDecorationStyle = false;
if (run.underline) {
if (!isNoteReferenceRun(run)) {
decorations.push("underline");
}
if (typeof run.underline === "object") {
if (run.underline.style) {
element.style.textDecorationStyle = run.underline.style;
explicitDecorationStyle = true;
}
if (run.underline.color) {
element.style.textDecorationColor = run.underline.color;
}
}
}
if (run.strike) {
decorations.push("line-through");
}
// Hidden runs need a dotted underline alongside any explicit underline/strike.
// Push into the shared `decorations` array (consumed at the end of this
// function) so the line 376 longhand assignment doesn't clobber it. The
// `textDecorationStyle` longhand is set only when no explicit underline
// style has already won — that keeps `w:u w:val="double"` visible if a
// hidden run also carries an underline mark.
if (run.hidden) {
if (!decorations.includes("underline")) {
decorations.push("underline");
}
if (!explicitDecorationStyle) {
element.style.textDecorationStyle = "dotted";
}
}
// Comment highlight
if (run.commentIds && run.commentIds.length > 0) {
element.style.backgroundColor = "rgba(255, 212, 0, 0.08)";
element.style.borderBottom = "1px solid rgba(180, 130, 0, 0.24)";
element.dataset["commentId"] = String(run.commentIds[0]);
}
// Tracked insertion styling — Word-style colored underline per author.
// Suggested insertions swap the author hue for the suggestion hue and paint
// a dotted stroke plus a faint tint so they read as proposals, not edits.
if (run.isInsertion) {
const authorIdx = getAuthorColorIdx(run.changeAuthor ?? "");
const authorColor = AUTHOR_COLORS[authorIdx]!; // SAFETY: getAuthorColorIdx returns index within AUTHOR_COLORS bounds
const strokeColor = run.isSuggestion ? SUGGESTION_COLOR_CSS : authorColor;
element.style.color = strokeColor;
if (!decorations.includes("underline")) {
decorations.push("underline");
}
element.style.textDecorationColor = strokeColor;
element.classList.add("docx-insertion");
element.dataset["tcAuthorIdx"] = String(authorIdx);
if (run.isSuggestion) {
element.classList.add("docx-insertion--suggested");
element.style.textDecorationStyle = "dotted";
element.style.backgroundImage = SUGGESTION_TINT_LAYER_CSS;
element.dataset["provenance"] = "suggested";
if (run.suggestionId) {
element.dataset["suggestionId"] = run.suggestionId;
}
}
// Author tooltip
const insertionParts = [
run.changeAuthor,
run.changeDate ? new Date(run.changeDate).toLocaleDateString() : "",
].filter(Boolean);
if (insertionParts.length > 0) {
element.title = `${run.isSuggestion ? "Suggested" : "Inserted"}: ${insertionParts.join(", ")}`;
}
if (run.changeAuthor) {
element.dataset["changeAuthor"] = run.changeAuthor;
}
if (run.changeDate) {
element.dataset["changeDate"] = run.changeDate;
}
if (run.changeRevisionId !== undefined) {
element.dataset["revisionId"] = String(run.changeRevisionId);
}
}
// Tracked deletion styling — Word-style colored strikethrough per author.
if (run.isDeletion) {
const authorIdx = getAuthorColorIdx(run.changeAuthor ?? "");
const authorColor = AUTHOR_COLORS[authorIdx]!; // SAFETY: getAuthorColorIdx returns index within AUTHOR_COLORS bounds
const strokeColor = run.isSuggestion ? SUGGESTION_COLOR_CSS : authorColor;
element.style.color = strokeColor;
if (!decorations.includes("line-through")) {
decorations.push("line-through");
}
element.style.textDecorationColor = strokeColor;
element.classList.add("docx-deletion");
element.dataset["tcAuthorIdx"] = String(authorIdx);
if (run.isSuggestion) {
element.classList.add("docx-deletion--suggested");
element.style.textDecorationStyle = "dotted";
element.style.backgroundImage = SUGGESTION_TINT_LAYER_CSS;
element.dataset["provenance"] = "suggested";
if (run.suggestionId) {
element.dataset["suggestionId"] = run.suggestionId;
}
}
// Author tooltip
const deletionParts = [
run.changeAuthor,
run.changeDate ? new Date(run.changeDate).toLocaleDateString() : "",
].filter(Boolean);
if (deletionParts.length > 0) {
element.title = `${run.isSuggestion ? "Suggested deletion" : "Deleted"}: ${deletionParts.join(", ")}`;
}
if (run.changeAuthor) {
element.dataset["changeAuthor"] = run.changeAuthor;
}
if (run.changeDate) {
element.dataset["changeDate"] = run.changeDate;
}
if (run.changeRevisionId !== undefined) {
element.dataset["revisionId"] = String(run.changeRevisionId);
}
}
if (decorations.length > 0) {
element.style.textDecorationLine = decorations.join(" ");
}
// Superscript/subscript. Raise/lower the glyph with a paint-only
// `position: relative` offset rather than `vertical-align: super/sub`. CSS
// grows the line box to contain a vertical-align shift, so `super`/`sub`
// inflated the height of any line carrying a superscript (e.g. a footnote
// anchor) past the base-font height the measurer reserved. A relative offset
// moves only where the glyph paints, leaving the line box intact
// (eigenpal/docx-editor#846). The reduced `fontSize` from
// `getRaisedRunFontSize` already keeps the glyph shorter than the line.
if (run.superscript) {
element.style.position = "relative";
element.style.top = "-0.4em";
element.style.fontSize = getRaisedRunFontSize(run);
}
if (run.subscript) {
element.style.position = "relative";
element.style.top = "0.2em";
element.style.fontSize = getRaisedRunFontSize(run);
}
}
function reserveScaledAdvance(
element: HTMLElement,
unscaledWidth: number,
horizontalScale: number | undefined,
): void {
if (horizontalScale === undefined || horizontalScale === 100) {
return;
}
element.style.width = `${unscaledWidth * (horizontalScale / 100)}px`;
}
/**
* Apply PM position data attributes
*/
function applyPmPositions(element: HTMLElement, pmStart?: number, pmEnd?: number): void {
if (pmStart !== undefined) {
element.dataset["pmStart"] = String(pmStart);
}
if (pmEnd !== undefined) {
element.dataset["pmEnd"] = String(pmEnd);
}
}
/**
* Render a text run
*/
function renderTextRun(run: TextRun, doc: Document): HTMLElement {
const span = doc.createElement("span");
span.className = `${PARAGRAPH_CLASS_NAMES.run} ${PARAGRAPH_CLASS_NAMES.text}`;
if (run.footnoteRefId !== undefined) {
span.dataset["noteKind"] = "footnote";
span.dataset["noteId"] = String(run.footnoteRefId);
} else if (run.endnoteRefId !== undefined) {
span.dataset["noteKind"] = "endnote";
span.dataset["noteId"] = String(run.endnoteRefId);
}
// Template fill preview substitution: the run's text is the typed value
// already laid out in place of its {{marker}}, so only a class is needed —
// `highlighted` paints the accent chip without altering the flowed width.
if (run.templatePreview) {
span.classList.add("folio-template-preview-run");
if (run.templatePreview === "highlighted") {
span.classList.add("folio-template-preview-run--highlighted");
}
}
applyRunStyles(span, run);
applyPmPositions(span, run.pmStart, run.pmEnd);
const paintedText = toPaintedText(run.text);
// Handle hyperlinks
if (run.hyperlink) {
const anchor = doc.createElement("a");
anchor.href = run.hyperlink.href;
// Internal bookmark links (starting with #) should scroll within the document
// External links should open in a new tab
if (!run.hyperlink.href.startsWith("#")) {
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
}
if (run.hyperlink.tooltip) {
anchor.title = run.hyperlink.tooltip;
}
anchor.textContent = paintedText;
// TOC entries opt out of the Hyperlink character style — Word renders
// them in the paragraph's own colour, no underline. The bridge sets
// `noDefaultStyle: true` and strips resolved colour/underline; here we
// skip the link fallback so the anchor inherits from the wrapping span.
if (!run.hyperlink.noDefaultStyle) {
// Default Word hyperlink color is blue (#0563c1)
const hyperlinkColor = getHyperlinkTextColor(run, span.style.color);
anchor.style.color = hyperlinkColor;
anchor.style.textDecoration = "underline";
// Override span color to match anchor (prevents color mismatch in selection)
span.style.color = hyperlinkColor;
// Expose the link colour on the anchor (which paints over the span) so
// dark mode inverts its lightness via the same --doc-run-color rule.
// `noDefaultStyle` (e.g. TOC) anchors set no colour and keep inheriting
// the paragraph's inverted colour.
anchor.style.setProperty("--doc-run-color", hyperlinkColor);
span.style.setProperty("--doc-run-color", hyperlinkColor);
}
span.append(anchor);
} else {
// Set text content
span.textContent = paintedText;
}
applyWhitespaceUnderline(span, run);
return span;
}
function isNoteReferenceRun(run: TextRun | TabRun): boolean {
return run.footnoteRefId !== undefined || run.endnoteRefId !== undefined;
}
function removeUnderlineTextDecoration(element: HTMLElement): void {
const textDecorationLines = (element.style.textDecorationLine || "")
.split(/\s+/u)
.filter((line) => line && line !== "underline");
element.style.textDecorationLine = textDecorationLines.join(" ");
}
function applyWhitespaceUnderline(element: HTMLElement, run: TextRun): void {
if (!run.underline || run.text.trim().length > 0) {
return;
}
removeUnderlineTextDecoration(element);
element.style.borderBottom = "1px solid currentColor";
if (typeof run.underline === "object" && run.underline.color) {
element.style.borderBottomColor = run.underline.color;
}
}
/**
* Number of leader characters to fill the tab's inner span. The inner span
* uses `overflow: hidden` so excess characters are clipped invisibly; we just
* need enough to span the widest realistic tab stop at the thinnest leader
* (a dot at small font sizes). 1000 covers wide-landscape pages with ~2px dots.
*/
const LEADER_FILL_COUNT = 1000;
/**
* Render a tab run with calculated width.
*
* Leader characters (dot/hyphen/underscore for TOC entries) render in an
* absolute-positioned inner span over a baseline-aligned zero-width-space.
* The earlier SVG background-image approach sat at the line's bottom edge,
* misaligned with the surrounding text baseline and broken under flex layout
* (where the outer's height collapses to the inner content). The
* outer-with-ZWSP + inner-absolute pattern keeps the tab's baseline anchored
* to the surrounding text and lets the right-tab flex anchor compute a stable
* height for the line.
*/
function renderTabRun(run: TabRun, doc: Document, width: number, leader?: string): HTMLElement {
const span = doc.createElement("span");
span.className = `${PARAGRAPH_CLASS_NAMES.run} ${PARAGRAPH_CLASS_NAMES.tab}`;
span.style.display = "inline-block";
span.style.width = `${width}px`;
applyRunStyles(span, run);
applyTabUnderline(span, run);
applyPmPositions(span, run.pmStart, run.pmEnd);
const leaderChar = leader && leader !== "none" ? getLeaderChar(leader) : null;
if (leaderChar) {
// Outer span holds a zero-width space so its baseline aligns with the
// surrounding text. Inner absolutely-positioned span carries the dots
// and clips horizontally; keeping `overflow: hidden` off the outer
// avoids the inline-block baseline-at-margin-edge problem.
span.style.position = "relative";
span.textContent = "\u200B"; // zero-width space
const inner = doc.createElement("span");
inner.style.position = "absolute";
inner.style.left = "0";
inner.style.right = "0";
inner.style.top = "0";
inner.style.bottom = "0";
inner.style.overflow = "hidden";
inner.style.whiteSpace = "nowrap";
inner.textContent = leaderChar.repeat(LEADER_FILL_COUNT);
span.append(inner);
} else {
// No leader: a single nbsp carries the line-height for layout.
span.textContent = "\u00A0";
}
return span;
}
function canClampTabToRightEdge(
alignment: string,
hasPriorRenderedContent: boolean,
hasPriorTab: boolean,
isLastLine: boolean,
): boolean {
if (alignment === "start" || alignment === "default") {
return hasPriorRenderedContent && (hasPriorTab || isLastLine);
}
return true;
}
function applyTabUnderline(element: HTMLElement, run: TabRun): void {
if (!run.underline) {
return;
}
removeUnderlineTextDecoration(element);
element.style.borderBottom = "1px solid currentColor";
if (typeof run.underline === "object" && run.underline.color) {
element.style.borderBottomColor = run.underline.color;
}
}
/**
* Get leader character for tab
*/
function getLeaderChar(leader: string): string | null {
switch (leader) {
case "dot":
return ".";
case "hyphen":
return "-";
case "underscore":
return "_";
case "middleDot":
return "·";
case "heavy":
return "_";
default:
return null;
}
}
/**
* Render an inline image run (flows with text)
*/
function renderInlineImageRun(run: ImageRun, doc: Document): HTMLElement {
const img = doc.createElement("img");
img.className = `${PARAGRAPH_CLASS_NAMES.run} ${PARAGRAPH_CLASS_NAMES.image}`;
applySanitizedImageSrc(img, run.src);
img.width = run.width;
img.height = run.height;
img.style.width = `${run.width}px`;
img.style.height = `${run.height}px`;
if (run.alt) {
img.alt = run.alt;
}
if (run.transform) {
img.style.transform = run.transform;
// Word rotates around the picture's geometric centre; the CSS default
// happens to match, but be explicit so future transforms can't drift.
img.style.transformOrigin = "center center";
}
// Cropped images clip via an overflow-hidden wrapper; paint the border on
// that wrapper instead of the scaled `<img>` (which would be invisible).
if (!hasImageCrop(run)) {
applyImageBorder(img, run);
}
// Rotated images extend past `run.width × run.height`, so without a bbox
// wrapper the inline line box reserves too little space and the rotated
// picture clips into the line above/below. Wrap the `<img>` in an
// inline-block span sized to the rotated bbox; the img positions
// absolutely at the wrapper centre and rotates around it. Matches Word,
// where `wp:extent` carries the post-rotation bbox.
// eigenpal #424 (rotation bbox gap 8 follow-up).
const rotation = parseRotationDegrees(run.transform);
if (rotation !== 0) {
const bbox = rotatedBoundingBox(run.width, run.height, rotation);
const wrapper = doc.createElement("span");
wrapper.className = PARAGRAPH_CLASS_NAMES.run;
wrapper.style.display = "inline-block";
wrapper.style.position = "relative";
wrapper.style.width = `${bbox.width}px`;
wrapper.style.height = `${bbox.height}px`;
wrapper.style.verticalAlign = "middle";
if (run.distTop) {
wrapper.style.marginTop = `${run.distTop}px`;
}
if (run.distBottom) {
wrapper.style.marginBottom = `${run.distBottom}px`;
}
img.style.position = "absolute";
img.style.left = `${(bbox.width - run.width) / 2}px`;
img.style.top = `${(bbox.height - run.height) / 2}px`;
applyPmPositions(wrapper, run.pmStart, run.pmEnd);
wrapper.append(img);
return wrapper;
}
// eigenpal #424: a cropped inline image needs an overflow-clipped wrapper
// sized to the visible (extent) box, with the inner `<img>` scaled up so
// the cropped region fills it. See applyImageVisualAttrs for the geometry.
if (hasImageVisualAttrs(run)) {
const wrapper = wrapImageWithCrop(img, run, doc, {
display: "inline-block",
widthPx: run.width,
heightPx: run.height,
});
wrapper.className = `${PARAGRAPH_CLASS_NAMES.run} ${PARAGRAPH_CLASS_NAMES.image}`;
wrapper.style.verticalAlign = "middle";
// wp:inline distT/distB: the measurer folds these into maxImageHeightPx;
// applying them as margins on the wrapper keeps the margin-box footprint
// consistent with the line height the measurer reserved.
if (run.distTop) {
wrapper.style.marginTop = `${run.distTop}px`;
}
if (run.distBottom) {
wrapper.style.marginBottom = `${run.distBottom}px`;
}
if (hasImageCrop(run)) {
applyImageBorder(wrapper, run);
}
applyPmPositions(wrapper, run.pmStart, run.pmEnd);
return wrapper;
}
// eigenpal #424 (opacity render pipeline)
if (hasImageVisualAttrs(run)) {
applyImageVisualAttrs(img, run);
}
// Inline images should flow with text
img.style.display = "inline";
img.style.verticalAlign = "middle";
// Fit the image to its container's content width (the text column or table
// cell) while preserving the run's aspect ratio: cap the width at 100% of the
// container and let `aspect-ratio` drive the height. Without this a wide image
// in a narrow cell squashes (the explicit height stays while the width is
// clamped) or overflows the page. The run's own aspect ratio is used — not the
// image's natural one — so a deliberately stretched image keeps its shape.
// (eigenpal/docx-editor#760.) Only the plain inline path opts in: the rotated
// and cropped paths return earlier and need their explicit pixel geometry.
if (run.width > 0 && run.height > 0) {
img.style.height = "auto";
img.style.aspectRatio = `${run.width} / ${run.height}`;
img.style.maxWidth = "100%";
}
// wp:inline distT/distB: the measurer folds these into maxImageHeightPx;
// applying them as margins here keeps the margin-box footprint consistent
// with the line height the measurer reserved.
if (run.distTop) {
img.style.marginTop = `${run.distTop}px`;
}
if (run.distBottom) {
img.style.marginBottom = `${run.distBottom}px`;
}
applyPmPositions(img, run.pmStart, run.pmEnd);
return img;
}
/**
* Render a block image (on its own line, like topAndBottom)
*/
function renderBlockImage(run: ImageRun, doc: Document): HTMLElement {
const container = doc.createElement("div");
container.className = "layout-block-image";
container.style.display = "block";
container.style.textAlign = "center";
container.style.marginTop = `${run.distTop ?? 6}px`;
container.style.marginBottom = `${run.distBottom ?? 6}px`;
const img = doc.createElement("img");
applySanitizedImageSrc(img, run.src);
img.width = run.width;
img.height = run.height;
if (run.alt) {
img.alt = run.alt;
}
if (run.transform) {
img.style.transform = run.transform;
// Word rotates around the picture's geometric centre; be explicit so
// future stacked transforms can't drift. eigenpal #424.
img.style.transformOrigin = "center center";
}
// Cropped images clip via an overflow-hidden wrapper; paint the border on
// that wrapper instead of the scaled `<img>` (which would be invisible).
if (!hasImageCrop(run)) {
applyImageBorder(img, run);
}
// Reserve the rotated bbox on the container so a rotated block image
// doesn't bleed into the next paragraph. The container is sized to the
// rotated bbox; the inner `<img>` positions absolutely at the offset
// that centres it inside the wrapper, then rotates around its own
// centre. Non-rotated images keep the fast path (auto margins for
// horizontal centering). Mirrors the inline path that PR #518 added in
// `renderInlineImageRun` — keep the two in sync until they dedupe.
// eigenpal #424 (rotation bbox gap 8 follow-up).
const rotation = parseRotationDegrees(run.transform);
if (rotation !== 0) {
const bbox = rotatedBoundingBox(run.width, run.height, rotation);
// Width must be explicit: `renderLine` wraps a single-image line in a
// flex container, and an absolutely-positioned `<img>` provides no
// in-flow width, so the wrapper would collapse to 0 and break
// centering.
container.style.width = `${bbox.width}px`;
container.style.height = `${bbox.height}px`;
container.style.position = "relative";
img.style.position = "absolute";
img.style.left = `${(bbox.width - run.width) / 2}px`;
img.style.top = `${(bbox.height - run.height) / 2}px`;
// Tailwind preflight applies `img { max-width: 100%; height: auto }`,
// which would shrink an absolutely-positioned `<img>`. Pin the
// intrinsic dims explicitly, same as the inline path.
img.style.width = `${run.width}px`;
img.style.height = `${run.height}px`;
img.style.marginLeft = "0";
img.style.marginRight = "0";
img.style.marginTop = "0";
}
// eigenpal #424: cropped block images need an overflow-clipped wrapper
// sized to the visible (extent) box; see applyImageVisualAttrs.
if (hasImageVisualAttrs(run)) {
const wrapper = wrapImageWithCrop(img, run, doc, {
display: "inline-block",
widthPx: run.width,
heightPx: run.height,
});
// Tailwind preflight sets img { display: block }, which would defeat
// text-align centring on the container. The inline-block wrapper
// restores centring via the container's text-align: center.
if (hasImageCrop(run)) {
applyImageBorder(wrapper, run);
}
applyPmPositions(container, run.pmStart, run.pmEnd);
container.append(wrapper);
return container;
}
// Global CSS reset (Tailwind preflight) sets img { display: block },
// which makes text-align: center on the container ineffective.
// Use margin: auto on the img itself to center it. Skip for rotated
// images — they are already centred via absolute positioning inside
// the bbox container above.
if (rotation === 0) {
img.style.marginLeft = "auto";
img.style.marginRight = "auto";
}
// eigenpal #424 (opacity render pipeline)
if (hasImageVisualAttrs(run)) {
applyImageVisualAttrs(img, run);
}
applyPmPositions(container, run.pmStart, run.pmEnd);
container.append(img);
return container;
}
/**
* Render an image run based on its display mode
* Note: Floating images (square/tight/through) are handled separately at paragraph level,
* not through this function. If they reach here, render as block.
*/
function renderImageRun(run: ImageRun, doc: Document): HTMLElement {
// Floating images should be handled at paragraph level, not here
// If they reach here (e.g., inside table cells), render as block
let el: HTMLElement;
if (isFloatingImageRun(run) || run.displayMode === "block" || run.wrapType === "topAndBottom") {
el = renderBlockImage(run, doc);
} else {
el = renderInlineImageRun(run, doc);
}
applyImageRevisionStyle(getImageRevisionStyleTarget(el), run);
return el;
}
function isStyleableHTMLElement(value: Element | undefined): value is HTMLElement {
return typeof value === "object" && "style" in value;
}
function getImageRevisionStyleTarget(el: HTMLElement): HTMLElement {
if (!el.className.split(/\s+/u).includes("layout-block-image")) {
return el;
}
const firstChild = el.children[0];
if (isStyleableHTMLElement(firstChild)) {
return firstChild;
}
return el;
}
/**
* A picture that is itself a tracked change gets a coloured outline (green for
* an insertion, red + faded for a deletion), mirroring the text-run treatment.
* `outline` is used over `border` so the image's box size is unchanged and
* line metrics stay stable. eigenpal #641.
*/
function applyImageRevisionStyle(el: HTMLElement, run: ImageRun): void {
if (run.isInsertion) {
el.style.outline = "2px solid #2e7d32";
el.style.outlineOffset = "1px";
el.classList.add("docx-insertion");
} else if (run.isDeletion) {
el.style.outline = "2px solid #c62828";