-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathrenderer.ts
More file actions
6970 lines (6305 loc) · 265 KB
/
renderer.ts
File metadata and controls
6970 lines (6305 loc) · 265 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
import type {
FlowBlock,
Fragment,
Layout,
Measure,
Page,
PageMargins,
ParaFragment,
ImageFragment,
DrawingFragment,
Run,
TextRun,
ImageRun,
FieldAnnotationRun,
Line,
LineSegment,
ParagraphBlock,
ParagraphMeasure,
ImageBlock,
ImageDrawing,
ParagraphAttrs,
ParagraphBorder,
ListItemFragment,
ListBlock,
ListMeasure,
TableBlock,
TableFragment,
TrackedChangeKind,
TrackedChangesMode,
SdtMetadata,
DrawingBlock,
VectorShapeDrawing,
ShapeGroupDrawing,
ShapeGroupChild,
DrawingGeometry,
PositionedDrawingGeometry,
VectorShapeStyle,
FlowRunLink,
GradientFill,
SolidFillWithAlpha,
ShapeTextContent,
DropCapDescriptor,
TableAttrs,
TableCellAttrs,
PositionMapping,
CustomGeometry,
} from '@superdoc/contracts';
import { calculateJustifySpacing, computeLinePmRange, shouldApplyJustify, SPACE_CHARS } from '@superdoc/contracts';
import { getPresetShapeSvg } from '@superdoc/preset-geometry';
import { applyGradientToSVG, applyAlphaToSVG, validateHexColor } from './svg-utils.js';
import {
CLASS_NAMES,
containerStyles,
containerStylesHorizontal,
spreadStyles,
fragmentStyles,
lineStyles,
pageStyles,
ensurePrintStyles,
ensureLinkStyles,
ensureTrackChangeStyles,
ensureSdtContainerStyles,
ensureFieldAnnotationStyles,
ensureImageSelectionStyles,
ensureNativeSelectionStyles,
type PageStyles,
} from './styles.js';
import { DOM_CLASS_NAMES } from './constants.js';
import { sanitizeHref, encodeTooltip } from '@superdoc/url-validation';
import { renderTableFragment as renderTableFragmentElement } from './table/renderTableFragment.js';
import { assertPmPositions, assertFragmentPmPositions } from './pm-position-validation.js';
import { applyImageClipPath } from './utils/image-clip-path.js';
import {
applySdtContainerStyling,
getSdtContainerKey,
shouldRebuildForSdtBoundary,
type SdtBoundaryOptions,
} from './utils/sdt-helpers.js';
import { SdtGroupedHover } from './utils/sdt-hover.js';
import { computeTabWidth } from './utils/marker-helpers.js';
import { createCustomGeometrySvg } from './utils/custom-geometry-svg.js';
import { generateRulerDefinitionFromPx, createRulerElement, ensureRulerStyles } from './ruler/index.js';
import { toCssFontFamily } from '@superdoc/font-utils';
import {
hashParagraphBorders,
hashTableBorders,
hashCellBorders,
getRunStringProp,
getRunNumberProp,
getRunBooleanProp,
getRunUnderlineStyle,
getRunUnderlineColor,
} from './paragraph-hash-utils.js';
/**
* Minimal type for WordParagraphLayoutOutput marker data used in rendering.
* Extracted to avoid dependency on @superdoc/word-layout package.
*/
type WordLayoutMarker = {
markerText?: string;
justification?: 'left' | 'right' | 'center';
gutterWidthPx?: number;
markerBoxWidthPx?: number;
suffix?: 'tab' | 'space' | 'nothing';
/** Pre-calculated X position where the marker should be placed (used in firstLineIndentMode). */
markerX?: number;
/** Pre-calculated X position where paragraph text should begin after the marker (used in firstLineIndentMode). */
textStartX?: number;
run: {
fontFamily: string;
fontSize: number;
bold?: boolean;
italic?: boolean;
color?: string;
letterSpacing?: number;
vanish?: boolean;
};
};
/**
* Minimal type for wordLayout property used in this renderer.
*
* This is a subset of the full WordParagraphLayoutOutput type from @superdoc/word-layout.
* We extract only the fields needed for rendering to avoid a direct dependency on the
* word-layout package from the renderer. This allows the renderer to work with any object
* that provides these properties, maintaining loose coupling between packages.
*
* The wordLayout property is attached to ParagraphBlock.attrs during block processing
* and contains layout metadata needed for proper list marker and indent rendering.
*
* @property marker - Optional list marker layout containing text, styling, and positioning info
* @property indentLeftPx - Left indent in pixels (used for marker positioning calculations)
* @property firstLineIndentMode - When true, indicates the paragraph uses firstLine indent
* pattern (marker at left+firstLine) instead of standard hanging indent (marker at left-hanging).
* This flag changes how markers are positioned and how tab spacing is calculated.
* @property textStartPx - X position where paragraph text should begin (used for tab width calculation)
* @property tabsPx - Array of explicit tab stop positions in pixels
*/
type MinimalWordLayout = {
marker?: WordLayoutMarker;
indentLeftPx?: number;
/** True for firstLine indent pattern (marker at left+firstLine vs left-hanging). */
firstLineIndentMode?: boolean;
/** X position where paragraph text should begin. */
textStartPx?: number;
/** Array of explicit tab stop positions in pixels. */
tabsPx?: number[];
};
type LineEnd = {
type?: string;
width?: string;
length?: string;
};
type LineEnds = {
head?: LineEnd;
tail?: LineEnd;
};
type EffectExtent = {
left: number;
top: number;
right: number;
bottom: number;
};
type VectorShapeDrawingWithEffects = VectorShapeDrawing & {
lineEnds?: LineEnds;
effectExtent?: EffectExtent;
};
/**
* Type guard to check if a value is a valid MinimalWordLayout object.
*
* This guard validates that the object has the expected structure for MinimalWordLayout
* without unsafe type assertions. It checks for the presence of valid properties and
* ensures type safety when accessing wordLayout from block attributes.
*
* @param value - The value to check (typically from block.attrs?.wordLayout)
* @returns True if the value is a valid MinimalWordLayout object, false otherwise
*
* @example
* ```typescript
* const wordLayout = block.attrs?.wordLayout;
* if (isMinimalWordLayout(wordLayout)) {
* // TypeScript now knows wordLayout is MinimalWordLayout
* const marker = wordLayout.marker;
* const isFirstLineMode = wordLayout.firstLineIndentMode === true;
* }
* ```
*/
function isMinimalWordLayout(value: unknown): value is MinimalWordLayout {
if (typeof value !== 'object' || value === null) {
return false;
}
const obj = value as Record<string, unknown>;
// Check marker property if present
if (obj.marker !== undefined) {
if (typeof obj.marker !== 'object' || obj.marker === null) {
return false;
}
const marker = obj.marker as Record<string, unknown>;
// Validate marker.markerText if present (must be a string)
if (marker.markerText !== undefined && typeof marker.markerText !== 'string') {
return false;
}
// Validate marker.markerX if present
if (marker.markerX !== undefined && typeof marker.markerX !== 'number') {
return false;
}
// Validate marker.textStartX if present
if (marker.textStartX !== undefined && typeof marker.textStartX !== 'number') {
return false;
}
}
// Check indentLeftPx property if present
if (obj.indentLeftPx !== undefined) {
if (typeof obj.indentLeftPx !== 'number') {
return false;
}
}
// Check firstLineIndentMode property if present
if (obj.firstLineIndentMode !== undefined) {
if (typeof obj.firstLineIndentMode !== 'boolean') {
return false;
}
}
// Check textStartPx property if present
if (obj.textStartPx !== undefined) {
if (typeof obj.textStartPx !== 'number') {
return false;
}
}
// Check tabsPx property if present and validate all array elements are numbers
if (obj.tabsPx !== undefined) {
if (!Array.isArray(obj.tabsPx)) {
return false;
}
// Validate that all elements are numbers
for (const tab of obj.tabsPx) {
if (typeof tab !== 'number') {
return false;
}
}
}
return true;
}
/**
* Layout mode for document rendering.
* @typedef {('vertical'|'horizontal'|'book')} LayoutMode
* - 'vertical': Standard page-by-page vertical layout (default)
* - 'horizontal': Pages arranged horizontally side-by-side
* - 'book': Book-style layout with facing pages
*/
export type LayoutMode = 'vertical' | 'horizontal' | 'book';
type PageDecorationPayload = {
fragments: Fragment[];
height: number;
/** Optional measured content height to aid bottom alignment in footers. */
contentHeight?: number;
offset?: number;
marginLeft?: number;
// Optional explicit content width (px) for the decoration container
contentWidth?: number;
headerId?: string;
sectionType?: string;
box?: { x: number; y: number; width: number; height: number };
hitRegion?: { x: number; y: number; width: number; height: number };
};
/**
* Provider function for page decorations (headers and footers).
* Called for each page to generate header or footer content.
*
* @param {number} pageNumber - The page number (1-indexed)
* @param {PageMargins} [pageMargins] - Page margin configuration
* @param {Page} [page] - Full page object from the layout
* @returns {PageDecorationPayload | null} Decoration payload containing fragments and layout info, or null if no decoration
*/
export type PageDecorationProvider = (
pageNumber: number,
pageMargins?: PageMargins,
page?: Page,
) => PageDecorationPayload | null;
/**
* Ruler configuration options for per-page rulers.
*/
export type RulerOptions = {
/** Whether to show rulers on pages (default: false) */
enabled?: boolean;
/** Whether rulers are interactive with drag handles (default: false for per-page) */
interactive?: boolean;
/** Callback when margin handle drag ends (only used if interactive) */
onMarginChange?: (side: 'left' | 'right', marginInches: number) => void;
};
type PainterOptions = {
pageStyles?: PageStyles;
layoutMode?: LayoutMode;
/** Gap between pages in pixels (default: 24px for vertical, 20px for horizontal) */
pageGap?: number;
headerProvider?: PageDecorationProvider;
footerProvider?: PageDecorationProvider;
virtualization?: {
enabled?: boolean;
window?: number;
overscan?: number;
/** Virtualization gap override (defaults to 72px; independent of pageGap) */
gap?: number;
paddingTop?: number;
};
/** Per-page ruler options */
ruler?: RulerOptions;
};
type BlockLookupEntry = {
block: FlowBlock;
measure: Measure;
version: string;
};
/**
* Map of block IDs to their corresponding block data and measurements.
* Used by the renderer to efficiently look up block information during fragment rendering.
* Each entry contains the block definition, its layout measurements, and a version string for cache invalidation.
*
* @typedef {Map<string, BlockLookupEntry>} BlockLookup
*/
export type BlockLookup = Map<string, BlockLookupEntry>;
type FragmentDomState = {
key: string;
signature: string;
fragment: Fragment;
element: HTMLElement;
context: FragmentRenderContext;
};
type PageDomState = {
element: HTMLElement;
fragments: FragmentDomState[];
};
/**
* Rendering context passed to fragment renderers containing page metadata.
* Provides information about the current page position and section for dynamic content like page numbers.
*
* @typedef {Object} FragmentRenderContext
* @property {number} pageNumber - Current page number (1-indexed)
* @property {number} totalPages - Total number of pages in the document
* @property {'body'|'header'|'footer'} section - Document section being rendered
* @property {string} [pageNumberText] - Optional formatted page number text (e.g., "Page 1 of 10")
*/
export type FragmentRenderContext = {
pageNumber: number;
totalPages: number;
section: 'body' | 'header' | 'footer';
pageNumberText?: string;
pageIndex?: number;
};
export type PaintSnapshotLineStyle = {
paddingLeftPx?: number;
paddingRightPx?: number;
textIndentPx?: number;
marginLeftPx?: number;
marginRightPx?: number;
leftPx?: number;
topPx?: number;
widthPx?: number;
heightPx?: number;
display?: string;
position?: string;
textAlign?: string;
justifyContent?: string;
};
export type PaintSnapshotMarkerStyle = {
text?: string;
leftPx?: number;
widthPx?: number;
paddingRightPx?: number;
display?: string;
position?: string;
textAlign?: string;
fontWeight?: string;
fontStyle?: string;
color?: string;
};
export type PaintSnapshotTabStyle = {
widthPx?: number;
leftPx?: number;
position?: string;
borderBottom?: string;
};
export type PaintSnapshotLine = {
index: number;
inTableFragment: boolean;
inTableParagraph: boolean;
style: PaintSnapshotLineStyle;
markers?: PaintSnapshotMarkerStyle[];
tabs?: PaintSnapshotTabStyle[];
};
export type PaintSnapshotPage = {
index: number;
pageNumber?: number;
lineCount: number;
lines: PaintSnapshotLine[];
};
export type PaintSnapshot = {
formatVersion: 1;
pageCount: number;
lineCount: number;
markerCount: number;
tabCount: number;
pages: PaintSnapshotPage[];
};
type PaintSnapshotPageBuilder = {
index: number;
pageNumber: number | null;
lineCount: number;
lines: PaintSnapshotLine[];
};
type PaintSnapshotBuilder = {
formatVersion: 1;
lineCount: number;
markerCount: number;
tabCount: number;
pages: PaintSnapshotPageBuilder[];
};
type PaintSnapshotCaptureOptions = {
inTableFragment?: boolean;
inTableParagraph?: boolean;
wrapperEl?: HTMLElement;
};
function roundSnapshotMetric(value: number): number | null {
if (!Number.isFinite(value)) return null;
return Math.round(value * 1000) / 1000;
}
function readSnapshotPxMetric(styleValue: string | null | undefined): number | null {
if (typeof styleValue !== 'string' || styleValue.length === 0) return null;
const parsed = Number.parseFloat(styleValue);
return Number.isFinite(parsed) ? roundSnapshotMetric(parsed) : null;
}
function readSnapshotStyleValue(styleValue: string | null | undefined): string | null {
if (typeof styleValue !== 'string' || styleValue.length === 0) return null;
return styleValue;
}
function compactSnapshotObject<T extends Record<string, unknown>>(input: T): T {
const out = {} as T;
for (const [key, value] of Object.entries(input)) {
if (value == null) continue;
if (Array.isArray(value) && value.length === 0) continue;
(out as Record<string, unknown>)[key] = value;
}
return out;
}
function snapshotLineStyleFromElement(lineEl: HTMLElement): PaintSnapshotLineStyle {
const style = lineEl?.style;
if (!style) return {};
return compactSnapshotObject({
paddingLeftPx: readSnapshotPxMetric(style.paddingLeft),
paddingRightPx: readSnapshotPxMetric(style.paddingRight),
textIndentPx: readSnapshotPxMetric(style.textIndent),
marginLeftPx: readSnapshotPxMetric(style.marginLeft),
marginRightPx: readSnapshotPxMetric(style.marginRight),
leftPx: readSnapshotPxMetric(style.left),
topPx: readSnapshotPxMetric(style.top),
widthPx: readSnapshotPxMetric(style.width),
heightPx: readSnapshotPxMetric(style.height),
display: readSnapshotStyleValue(style.display),
position: readSnapshotStyleValue(style.position),
textAlign: readSnapshotStyleValue(style.textAlign),
justifyContent: readSnapshotStyleValue(style.justifyContent),
}) as PaintSnapshotLineStyle;
}
function applyWrapperMarginsToSnapshotStyle(
lineStyle: PaintSnapshotLineStyle,
wrapperEl?: HTMLElement,
): PaintSnapshotLineStyle {
if (!wrapperEl?.style) return lineStyle;
return compactSnapshotObject({
...lineStyle,
marginLeftPx: readSnapshotPxMetric(wrapperEl.style.marginLeft) ?? lineStyle.marginLeftPx,
marginRightPx: readSnapshotPxMetric(wrapperEl.style.marginRight) ?? lineStyle.marginRightPx,
}) as PaintSnapshotLineStyle;
}
function snapshotMarkerStyleFromElement(markerEl: HTMLElement): PaintSnapshotMarkerStyle {
const style = markerEl?.style;
if (!style) return {};
return compactSnapshotObject({
text: markerEl?.textContent ?? '',
leftPx: readSnapshotPxMetric(style.left),
widthPx: readSnapshotPxMetric(style.width),
paddingRightPx: readSnapshotPxMetric(style.paddingRight),
display: readSnapshotStyleValue(style.display),
position: readSnapshotStyleValue(style.position),
textAlign: readSnapshotStyleValue(style.textAlign),
fontWeight: readSnapshotStyleValue(style.fontWeight),
fontStyle: readSnapshotStyleValue(style.fontStyle),
color: readSnapshotStyleValue(style.color),
}) as PaintSnapshotMarkerStyle;
}
function collectLineMarkersForSnapshot(lineEl: HTMLElement): PaintSnapshotMarkerStyle[] {
const markers: PaintSnapshotMarkerStyle[] = [];
const parent = lineEl?.parentElement;
if (parent) {
for (const child of Array.from(parent.children)) {
if (!(child instanceof HTMLElement)) continue;
if (!child.classList.contains('superdoc-paragraph-marker')) continue;
markers.push(snapshotMarkerStyleFromElement(child));
}
}
const inlineMarkers = lineEl?.querySelectorAll?.('.superdoc-paragraph-marker') ?? [];
for (const markerEl of Array.from(inlineMarkers)) {
if (!(markerEl instanceof HTMLElement)) continue;
const markerStyle = snapshotMarkerStyleFromElement(markerEl);
const markerText = markerEl.textContent ?? '';
const markerLeft = readSnapshotPxMetric(markerEl.style.left);
if (markers.some((existing) => existing.text === markerText && existing.leftPx === markerLeft)) {
continue;
}
markers.push(markerStyle);
}
return markers;
}
function collectLineTabsForSnapshot(lineEl: HTMLElement): PaintSnapshotTabStyle[] {
const tabs: PaintSnapshotTabStyle[] = [];
const tabElements = lineEl?.querySelectorAll?.('.superdoc-tab') ?? [];
for (const tabEl of Array.from(tabElements)) {
if (!(tabEl instanceof HTMLElement)) continue;
tabs.push(
compactSnapshotObject({
widthPx: readSnapshotPxMetric(tabEl.style.width),
leftPx: readSnapshotPxMetric(tabEl.style.left),
position: readSnapshotStyleValue(tabEl.style.position),
borderBottom: readSnapshotStyleValue(tabEl.style.borderBottom),
}) as PaintSnapshotTabStyle,
);
}
return tabs;
}
const LIST_MARKER_GAP = 8;
/**
* Default page height in pixels (11 inches at 96 DPI).
* Used as a fallback when page size information is not available for ruler rendering.
*/
const DEFAULT_PAGE_HEIGHT_PX = 1056;
/** Default gap used when virtualization is enabled (kept in sync with PresentationEditor layout defaults). */
const DEFAULT_VIRTUALIZED_PAGE_GAP = 72;
const COMMENT_EXTERNAL_COLOR = '#B1124B';
const COMMENT_INTERNAL_COLOR = '#078383';
const COMMENT_INACTIVE_ALPHA = '40'; // ~25% for inactive
const COMMENT_ACTIVE_ALPHA = '66'; // ~40% for active/selected
type LinkRenderData = {
href?: string;
target?: string;
rel?: string;
tooltip?: string | null;
dataset?: Record<string, string>;
blocked: boolean;
};
const LINK_DATASET_KEYS = {
blocked: 'linkBlocked',
docLocation: 'linkDocLocation',
history: 'linkHistory',
rId: 'linkRid',
truncated: 'linkTooltipTruncated',
} as const;
const MAX_HREF_LENGTH = 2048;
const SAFE_ANCHOR_PATTERN = /^[A-Za-z0-9._-]+$/;
/**
* Maximum allowed length for data URLs (10MB).
* Prevents denial of service attacks from extremely large embedded images.
*/
const MAX_DATA_URL_LENGTH = 10 * 1024 * 1024; // 10MB
/**
* Regular expression to validate data URL format for images.
* Only allows common, safe image MIME types with base64 encoding.
* Prevents XSS and malformed data URL attacks.
*/
const VALID_IMAGE_DATA_URL = /^data:image\/(png|jpeg|jpg|gif|svg\+xml|webp|bmp|ico|tiff?);base64,/i;
/**
* Maximum resize multiplier for image metadata.
* Images can be resized up to 3x their original dimensions.
*/
const MAX_RESIZE_MULTIPLIER = 3;
/**
* Fallback maximum dimension for image resizing when original size is small.
* Ensures images can be resized to at least 1000px even if original is smaller.
*/
const FALLBACK_MAX_DIMENSION = 1000;
/**
* Minimum image dimension in pixels.
* Ensures images remain visible and interactive during resizing.
*/
const MIN_IMAGE_DIMENSION = 20;
/**
* Pattern to detect ambiguous link text that doesn't convey destination (WCAG 2.4.4).
* Matches common generic phrases like "click here", "read more", etc.
*/
const AMBIGUOUS_LINK_PATTERNS = /^(click here|read more|more|link|here|this|download|view)$/i;
/**
* Hyperlink rendering metrics for observability.
* Tracks sanitization, blocking, and security-related events.
*/
const linkMetrics = {
sanitized: 0,
blocked: 0,
invalidProtocol: 0,
homographWarnings: 0,
reset() {
this.sanitized = 0;
this.blocked = 0;
this.invalidProtocol = 0;
this.homographWarnings = 0;
},
getMetrics() {
return {
'hyperlink.sanitized.count': this.sanitized,
'hyperlink.blocked.count': this.blocked,
'hyperlink.invalid_protocol.count': this.invalidProtocol,
'hyperlink.homograph_warnings.count': this.homographWarnings,
};
},
};
// Export for testing/monitoring
export { linkMetrics };
const TRACK_CHANGE_BASE_CLASS: Record<TrackedChangeKind, string> = {
insert: 'track-insert-dec',
delete: 'track-delete-dec',
format: 'track-format-dec',
};
const TRACK_CHANGE_FOCUSED_CLASS = 'track-change-focused';
const TRACK_CHANGE_MODIFIER_CLASS: Record<TrackedChangeKind, Record<TrackedChangesMode, string | undefined>> = {
insert: {
review: 'highlighted',
original: 'hidden',
final: 'normal',
off: undefined,
},
delete: {
review: 'highlighted',
original: 'normal',
final: 'hidden',
off: undefined,
},
format: {
review: 'highlighted',
original: 'before',
final: 'normal',
off: undefined,
},
};
type TrackedChangesRenderConfig = {
mode: TrackedChangesMode;
enabled: boolean;
};
/**
* Sanitize a URL to prevent XSS attacks.
* Only allows http, https, mailto, tel, and internal anchors.
*
* @param href - The URL to sanitize
* @returns Sanitized URL or null if blocked
*/
export function sanitizeUrl(href: string): string | null {
if (typeof href !== 'string') return null;
const sanitized = sanitizeHref(href);
return sanitized?.href ?? null;
}
const LINK_TARGET_SET = new Set(['_blank', '_self', '_parent', '_top']);
/**
* Normalize and validate an anchor fragment identifier for use in hyperlinks.
* Strips leading '#' if present and validates against safe character pattern.
*
* @param value - Raw anchor string (with or without leading '#')
* @returns Normalized anchor with leading '#' (e.g., '#section-1'), or null if invalid
*
* @remarks
* SECURITY: Only allows safe characters (A-Z, a-z, 0-9, ., _, -) to prevent HTML attribute injection.
* Rejects characters like quotes, angle brackets, colons, and spaces that could break HTML structure
* or enable XSS attacks when used in href attributes.
*
* @example
* normalizeAnchor('section-1') // Returns: '#section-1'
* normalizeAnchor('#bookmark') // Returns: '#bookmark'
* normalizeAnchor('unsafe<script>') // Returns: null
* normalizeAnchor(' whitespace ') // Returns: null
*/
const normalizeAnchor = (value: string | null | undefined): string | null => {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
if (!trimmed) return null;
// Remove leading # if present, then validate
const anchor = trimmed.startsWith('#') ? trimmed.slice(1) : trimmed;
// SECURITY: Only allow safe characters to prevent attribute injection
// Rejects characters like quotes, angle brackets, spaces that could break HTML
if (!SAFE_ANCHOR_PATTERN.test(anchor)) {
return null;
}
return `#${anchor}`;
};
/**
* Check if a fragment string contains only safe anchor characters.
* Safe characters are alphanumeric, dots, underscores, and hyphens.
*
* @param {string} fragment - Fragment to validate
* @returns {boolean} True if fragment matches safe pattern
* @private
*/
const isValidSafeFragment = (fragment: string): boolean => {
return SAFE_ANCHOR_PATTERN.test(fragment);
};
/**
* URL-encode a fragment string for use in a URL hash.
* Returns null if encoding fails (rare edge case).
*
* @param {string} fragment - Fragment to encode
* @returns {string | null} Encoded fragment or null if encoding fails
* @private
*/
const encodeFragment = (fragment: string): string | null => {
try {
return encodeURIComponent(fragment);
} catch {
return null;
}
};
/**
* Append a document location fragment to an href.
* CRITICAL FIX: URL-encode unsafe characters instead of destroying the entire href.
*
* @param href - Base URL or null
* @param docLocation - Fragment identifier to append
* @returns Combined URL with fragment, or original href if fragment is invalid
*/
const appendDocLocation = (href: string | null, docLocation?: string | null): string | null => {
if (!docLocation?.trim()) return href;
const fragment = docLocation.trim();
if (href?.includes('#')) return href;
const encoded = isValidSafeFragment(fragment) ? fragment : encodeFragment(fragment);
if (!encoded) return href;
return href ? `${href}#${encoded}` : `#${encoded}`;
};
/**
* Build HTML data-* attributes object from hyperlink metadata for version 2 links.
* Extracts relationship ID, document location fragment, and history preferences from link object.
*
* @param link - Flow run link object containing hyperlink metadata
* @returns Record of data attribute keys and string values to be applied to anchor element
*
* @remarks
* Only processes version 2 links (Office Open XML format). Version 1 links return empty object.
* All dataset values are converted to strings for DOM compatibility.
*
* @example
* buildLinkDataset({
* version: 2,
* rId: 'rId5',
* docLocation: 'bookmark1',
* history: true
* })
* // Returns: { rId: 'rId5', docLocation: 'bookmark1', history: 'true' }
*/
const buildLinkDataset = (link: FlowRunLink): Record<string, string> => {
const dataset: Record<string, string> = {};
if (link.version === 2) {
if (link.rId) dataset[LINK_DATASET_KEYS.rId] = link.rId;
if (link.docLocation) dataset[LINK_DATASET_KEYS.docLocation] = link.docLocation;
if (typeof link.history === 'boolean') dataset[LINK_DATASET_KEYS.history] = String(link.history);
}
return dataset;
};
/**
* Resolve the appropriate target attribute for a hyperlink anchor element.
* Validates user-specified targets and auto-sets '_blank' for external HTTP(S) links.
*
* @param link - Flow run link object potentially containing target preference
* @param sanitized - Sanitized URL metadata containing protocol information, or null if sanitization failed
* @returns Valid target string ('_blank', '_self', '_parent', '_top') or undefined if not applicable
*
* @remarks
* Target resolution follows this priority:
* 1. If link.target is specified and valid (in LINK_TARGET_SET), use it
* 2. If URL is external (http/https protocol), default to '_blank' for security
* 3. Otherwise, return undefined (browser default behavior)
*
* @example
* resolveLinkTarget(
* { target: '_self' },
* { protocol: 'https', href: 'https://example.com', isExternal: true }
* ) // Returns: '_self' (user preference honored)
*
* resolveLinkTarget(
* {},
* { protocol: 'https', href: 'https://example.com', isExternal: true }
* ) // Returns: '_blank' (external link default)
*/
const resolveLinkTarget = (
link: FlowRunLink,
sanitized?: ReturnType<typeof sanitizeHref> | null,
): string | undefined => {
if (link.target && LINK_TARGET_SET.has(link.target)) {
return link.target;
}
if (sanitized && (sanitized.protocol === 'http' || sanitized.protocol === 'https')) {
return '_blank';
}
return undefined;
};
/**
* Resolve the rel attribute value for a hyperlink, combining user-specified relationships
* with security-critical values for external links.
*
* @param link - Flow run link object potentially containing rel preference (space-separated string)
* @param target - Resolved target attribute value (e.g., '_blank', '_self')
* @returns Space-separated rel values, or undefined if no rel values apply
*
* @remarks
* SECURITY: Automatically adds 'noopener noreferrer' for target='_blank' links to prevent:
* - Tabnabbing attacks (window.opener access)
* - Referrer leakage to external sites
*
* User-specified rel values are parsed from link.rel (whitespace-separated string),
* deduplicated, and merged with security values.
*
* @example
* resolveLinkRel(
* { rel: 'nofollow external' },
* '_blank'
* ) // Returns: 'nofollow external noopener noreferrer'
*
* resolveLinkRel(
* { rel: 'nofollow noopener ' },
* '_blank'
* ) // Returns: 'nofollow noopener noreferrer' (deduplicated)
*
* resolveLinkRel({}, '_self') // Returns: undefined
*/
const resolveLinkRel = (link: FlowRunLink, target?: string): string | undefined => {
const relValues = new Set<string>();
if (typeof link.rel === 'string' && link.rel.trim()) {
link.rel
.trim()
.split(/\s+/)
.forEach((value) => {
if (value) relValues.add(value);
});
}
if (target === '_blank') {
relValues.add('noopener');
relValues.add('noreferrer');
}
if (relValues.size === 0) {
return undefined;
}
return Array.from(relValues).join(' ');
};
/**
* Apply data-* attributes to an HTML element from a dataset object.
* Safely assigns dataset properties while filtering out null/undefined values.
*
* @param element - Target HTML element to receive data attributes
* @param dataset - Object mapping data attribute keys to string values
*
* @remarks
* Uses the element.dataset API which automatically prefixes keys with 'data-'.
* Only assigns non-null, non-undefined values to prevent empty attributes.
*
* @example
* const anchor = document.createElement('a');
* applyLinkDataset(anchor, {
* rId: 'rId5',
* docLocation: 'bookmark1',
* history: 'true'
* });
* // Resulting HTML: <a data-r-id="rId5" data-doc-location="bookmark1" data-history="true"></a>
*/
const applyLinkDataset = (element: HTMLElement, dataset?: Record<string, string>): void => {
if (!dataset) return;
Object.entries(dataset).forEach(([key, value]) => {
if (value != null) {
element.dataset[key] = value;
}
});
};
/**
* DOM-based document painter that renders layout fragments to HTML elements.
* Manages page rendering, virtualization, headers/footers, and incremental updates.
*
* @class DomPainter
*
* @remarks
* The DomPainter is responsible for:
* - Rendering layout fragments (paragraphs, lists, images, tables, drawings) to DOM elements
* - Managing page-level DOM structure and styling
* - Providing virtualization for large documents (vertical mode only)
* - Handling headers and footers via PageDecorationProvider
* - Incremental re-rendering when only specific blocks change
* - Hyperlink rendering with security sanitization and accessibility
*
* @example
* ```typescript
* const painter = new DomPainter(blocks, measures, {
* layoutMode: 'vertical',
* pageStyles: { width: '8.5in', height: '11in' }
* });
* painter.mount(document.getElementById('editor-container'));
* painter.render(layout);
* ```
*/
export class DomPainter {
private blockLookup: BlockLookup;
private readonly options: PainterOptions;
private mount: HTMLElement | null = null;
private doc: Document | null = null;
private pageStates: PageDomState[] = [];
private currentLayout: Layout | null = null;
private changedBlocks = new Set<string>();
private readonly layoutMode: LayoutMode;
private headerProvider?: PageDecorationProvider;
private footerProvider?: PageDecorationProvider;
private totalPages = 0;
private linkIdCounter = 0; // Counter for generating unique link IDs
private sdtLabelsRendered = new Set<string>(); // Tracks SDT labels rendered across pages
/**
* WeakMap storing tooltip data for hyperlink elements before DOM insertion.
* Uses WeakMap to prevent memory leaks - entries are automatically garbage collected
* when the corresponding element is removed from memory.
* @private
*/