-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathrenderer.ts
More file actions
7928 lines (7159 loc) · 299 KB
/
renderer.ts
File metadata and controls
7928 lines (7159 loc) · 299 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 {
ChartDrawing,
CustomGeometryData,
DrawingBlock,
DrawingFragment,
DrawingGeometry,
DropCapDescriptor,
FieldAnnotationRun,
FlowBlock,
FlowMode,
FlowRunLink,
Fragment,
GradientFill,
ImageBlock,
ImageDrawing,
ImageFragment,
ImageHyperlink,
ImageRun,
Layout,
Line,
LineSegment,
ListBlock,
ListItemFragment,
ListMeasure,
Measure,
Page,
PageMargins,
ParaFragment,
ParagraphAttrs,
ParagraphBlock,
ParagraphBorder,
ParagraphMeasure,
PositionedDrawingGeometry,
Run,
SdtMetadata,
ShapeGroupChild,
ShapeGroupDrawing,
ShapeTextContent,
SolidFillWithAlpha,
TableAttrs,
TableBlock,
TableCellAttrs,
TableFragment,
TableMeasure,
MathRun,
TextRun,
TrackedChangeKind,
TrackedChangesMode,
VectorShapeDrawing,
VectorShapeStyle,
ResolvedLayout,
ResolvedFragmentItem,
ResolvedPage,
ResolvedPaintItem,
ResolvedTableItem,
ResolvedImageItem,
ResolvedDrawingItem,
} from '@superdoc/contracts';
import {
adjustAvailableWidthForTextIndent,
calculateJustifySpacing,
computeLinePmRange,
getCellSpacingPx,
normalizeBaselineShift,
resolveBaseFontSizeForVerticalText,
shouldApplyJustify,
SPACE_CHARS,
} from '@superdoc/contracts';
import { toCssFontFamily } from '@superdoc/font-utils';
import { getPresetShapeSvg } from '@superdoc/preset-geometry';
import { encodeTooltip, sanitizeHref } from '@superdoc/url-validation';
import { DOM_CLASS_NAMES } from './constants.js';
import { createChartElement as renderChartToElement } from './chart-renderer.js';
import {
getRunBooleanProp,
getRunNumberProp,
getRunStringProp,
getRunUnderlineColor,
getRunUnderlineStyle,
hashCellBorders,
hashParagraphBorders,
hashTableBorders,
} from './paragraph-hash-utils.js';
import { assertFragmentPmPositions, assertPmPositions } from './pm-position-validation.js';
import { createRulerElement, ensureRulerStyles, generateRulerDefinitionFromPx } from './ruler/index.js';
import {
CLASS_NAMES,
containerStyles,
containerStylesHorizontal,
ensureFieldAnnotationStyles,
ensureImageSelectionStyles,
ensureLinkStyles,
ensurePrintStyles,
ensureSdtContainerStyles,
ensureTrackChangeStyles,
fragmentStyles,
lineStyles,
pageStyles,
spreadStyles,
type PageStyles,
} from './styles.js';
import { applyAlphaToSVG, applyGradientToSVG, validateHexColor } from './svg-utils.js';
import { renderTableFragment as renderTableFragmentElement } from './table/renderTableFragment.js';
import { applyImageClipPath } from './utils/image-clip-path.js';
import { isMinimalWordLayout as isMinimalWordLayoutShared } from '@superdoc/common/list-marker-utils';
import {
computeTabWidth,
resolvePainterListMarkerGeometry,
resolvePainterListTextStartPx,
} from './utils/marker-helpers.js';
import {
applySdtContainerStyling,
getSdtContainerKey,
shouldRebuildForSdtBoundary,
type SdtBoundaryOptions,
} from './utils/sdt-helpers.js';
import {
computeBetweenBorderFlags,
getFragmentParagraphBorders,
getFragmentHeight,
createParagraphDecorationLayers,
applyParagraphBorderStyles,
applyParagraphShadingStyles,
getParagraphBorderBox,
stampBetweenBorderDataset,
type BetweenBorderInfo,
} from './features/paragraph-borders/index.js';
import { applyRtlStyles, shouldUseSegmentPositioning } from './features/rtl-paragraph/index.js';
import { convertOmmlToMathml } from './features/math/index.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 narrowing to the renderer-local MinimalWordLayout type.
* Delegates structural validation to the shared isMinimalWordLayout guard.
*/
function isMinimalWordLayout(value: unknown): value is MinimalWordLayout {
return isMinimalWordLayoutShared(value);
}
/**
* 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';
// FlowMode is re-exported from @superdoc/contracts
export type { FlowMode } from '@superdoc/contracts';
/**
* Interface for position mapping from ProseMirror transactions.
* Used to efficiently update DOM position attributes without full re-render.
*/
export interface PositionMapping {
/** Transform a position from old to new document coordinates */
map(pos: number, bias?: number): number;
/** Array of step maps - length indicates transaction complexity */
readonly maps: readonly unknown[];
}
export type RenderedLineInfo = {
el: HTMLElement;
top: number;
height: number;
};
/**
* Input to `DomPainter.paint()`.
*
* `resolvedLayout` is the canonical resolved data. The remaining fields are
* bridge data carried for internal rendering of non-paragraph fragments
* (tables, images, drawings) that have not yet been migrated to resolved items.
*/
export type DomPainterInput = {
resolvedLayout: ResolvedLayout;
/** Raw Layout for internal fragment access (bridge — will be removed once all fragment types are resolved). */
sourceLayout: Layout;
blocks: FlowBlock[];
measures: Measure[];
headerBlocks?: FlowBlock[];
headerMeasures?: Measure[];
footerBlocks?: FlowBlock[];
footerMeasures?: Measure[];
};
type OptionalBlockMeasurePair = {
blocks: FlowBlock[];
measures: Measure[];
};
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;
headerFooterRefId?: 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;
flowMode?: FlowMode;
/** 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;
/** Called with the paint snapshot after each paint cycle completes. */
onPaintSnapshot?: (snapshot: PaintSnapshot) => void;
};
// BlockLookup lives in the shared types module (single source of truth)
import type { BlockLookupEntry, BlockLookup } from './features/paragraph-borders/types.js';
export type { BlockLookup, 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 PaintSnapshotAnnotationEntity = {
element: HTMLElement;
pageIndex: number;
pmStart?: number;
pmEnd?: number;
fieldId?: string;
fieldType?: string;
type?: string;
};
export type PaintSnapshotStructuredContentBlockEntity = {
element: HTMLElement;
pageIndex: number;
sdtId: string;
pmStart?: number;
pmEnd?: number;
};
export type PaintSnapshotStructuredContentInlineEntity = {
element: HTMLElement;
pageIndex: number;
sdtId: string;
pmStart?: number;
pmEnd?: number;
};
export type PaintSnapshotImageEntity = {
element: HTMLElement;
pageIndex: number;
kind: 'inline' | 'fragment';
pmStart?: number;
pmEnd?: number;
blockId?: string;
};
export type PaintSnapshotEntities = {
annotations: PaintSnapshotAnnotationEntity[];
structuredContentBlocks: PaintSnapshotStructuredContentBlockEntity[];
structuredContentInlines: PaintSnapshotStructuredContentInlineEntity[];
images: PaintSnapshotImageEntity[];
};
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[];
entities: PaintSnapshotEntities;
};
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 createEmptyPaintSnapshotEntities(): PaintSnapshotEntities {
return {
annotations: [],
structuredContentBlocks: [],
structuredContentInlines: [],
images: [],
};
}
function readSnapshotDatasetNumber(value: string | null | undefined): number | null {
if (typeof value !== 'string' || value.length === 0) return null;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
function resolveSnapshotPageIndex(element: HTMLElement): number | null {
const pageEl = element.closest(`.${DOM_CLASS_NAMES.PAGE}`) as HTMLElement | null;
if (!pageEl) return null;
return readSnapshotDatasetNumber(pageEl.dataset.pageIndex);
}
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 shouldIncludeInlineImageSnapshotElement(element: HTMLElement): boolean {
if (element.classList.contains(DOM_CLASS_NAMES.INLINE_IMAGE_CLIP_WRAPPER)) {
return true;
}
if (!element.classList.contains(DOM_CLASS_NAMES.INLINE_IMAGE)) {
return false;
}
return !element.closest(`.${DOM_CLASS_NAMES.INLINE_IMAGE_CLIP_WRAPPER}`);
}
function collectPaintSnapshotEntitiesFromDomRoot(rootEl: HTMLElement): PaintSnapshotEntities {
const entities = createEmptyPaintSnapshotEntities();
const annotationElements = Array.from(
rootEl.querySelectorAll<HTMLElement>(`.${DOM_CLASS_NAMES.ANNOTATION}[data-pm-start]`),
);
for (const element of annotationElements) {
const pageIndex = resolveSnapshotPageIndex(element);
if (pageIndex == null) continue;
entities.annotations.push(
compactSnapshotObject({
element,
pageIndex,
pmStart: readSnapshotDatasetNumber(element.dataset.pmStart),
pmEnd: readSnapshotDatasetNumber(element.dataset.pmEnd),
fieldId: element.dataset.fieldId || null,
fieldType: element.dataset.fieldType || null,
type: element.dataset.type || null,
}) as PaintSnapshotAnnotationEntity,
);
}
const blockSdtElements = Array.from(
rootEl.querySelectorAll<HTMLElement>(`.${DOM_CLASS_NAMES.BLOCK_SDT}[data-sdt-id]`),
);
for (const element of blockSdtElements) {
const pageIndex = resolveSnapshotPageIndex(element);
const sdtId = element.dataset.sdtId;
if (pageIndex == null || !sdtId) continue;
entities.structuredContentBlocks.push(
compactSnapshotObject({
element,
pageIndex,
sdtId,
pmStart: readSnapshotDatasetNumber(element.dataset.pmStart),
pmEnd: readSnapshotDatasetNumber(element.dataset.pmEnd),
}) as PaintSnapshotStructuredContentBlockEntity,
);
}
const inlineSdtElements = Array.from(
rootEl.querySelectorAll<HTMLElement>(`.${DOM_CLASS_NAMES.INLINE_SDT_WRAPPER}[data-sdt-id]`),
);
for (const element of inlineSdtElements) {
const pageIndex = resolveSnapshotPageIndex(element);
const sdtId = element.dataset.sdtId;
if (pageIndex == null || !sdtId) continue;
entities.structuredContentInlines.push(
compactSnapshotObject({
element,
pageIndex,
sdtId,
pmStart: readSnapshotDatasetNumber(element.dataset.pmStart),
pmEnd: readSnapshotDatasetNumber(element.dataset.pmEnd),
}) as PaintSnapshotStructuredContentInlineEntity,
);
}
const inlineImageElements = Array.from(
rootEl.querySelectorAll<HTMLElement>(
`.${DOM_CLASS_NAMES.INLINE_IMAGE_CLIP_WRAPPER}[data-pm-start], .${DOM_CLASS_NAMES.INLINE_IMAGE}[data-pm-start]`,
),
);
for (const element of inlineImageElements) {
if (!shouldIncludeInlineImageSnapshotElement(element)) continue;
const pageIndex = resolveSnapshotPageIndex(element);
if (pageIndex == null) continue;
entities.images.push(
compactSnapshotObject({
element,
pageIndex,
kind: 'inline',
pmStart: readSnapshotDatasetNumber(element.dataset.pmStart),
pmEnd: readSnapshotDatasetNumber(element.dataset.pmEnd),
}) as PaintSnapshotImageEntity,
);
}
const fragmentImageElements = Array.from(
rootEl.querySelectorAll<HTMLElement>(`.${DOM_CLASS_NAMES.IMAGE_FRAGMENT}[data-pm-start]`),
);
for (const element of fragmentImageElements) {
const pageIndex = resolveSnapshotPageIndex(element);
if (pageIndex == null) continue;
entities.images.push(
compactSnapshotObject({
element,
pageIndex,
kind: 'fragment',
pmStart: readSnapshotDatasetNumber(element.dataset.pmStart),
pmEnd: readSnapshotDatasetNumber(element.dataset.pmEnd),
blockId: element.getAttribute('data-sd-block-id'),
}) as PaintSnapshotImageEntity,
);
}
return entities;
}
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;
// Comment highlight color tokens moved to CommentHighlightDecorator (super-editor).
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',
};
// TRACK_CHANGE_FOCUSED_CLASS moved to CommentHighlightDecorator (super-editor).
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);
};
type ImageFilterSource = Pick<ImageBlock, 'grayscale' | 'gain' | 'blacklevel' | 'lum'>;
const clampLumUnit = (value: number): number => {
return Math.max(-100000, Math.min(100000, value));
};
const parseVmlFixedFraction = (value: string | number | undefined): number | null => {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value !== 'string' || value.length === 0) {
return null;
}
if (value.endsWith('f')) {
const raw = Number.parseInt(value.slice(0, -1), 10);
return Number.isFinite(raw) ? raw / 65536 : null;
}
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? parsed : null;
};
const buildImageFilters = (source: ImageFilterSource): string[] => {
const filters: string[] = [];
if (source.grayscale) {
filters.push('grayscale(100%)');
}
if (source.gain != null || source.blacklevel != null) {
const gain = parseVmlFixedFraction(source.gain);
const blacklevel = parseVmlFixedFraction(source.blacklevel);
if (gain != null) {
const contrast = Math.max(0, gain);
if (contrast > 0) {
filters.push(`contrast(${contrast})`);
}
}
if (blacklevel != null) {
// CSS has no black-point control, so approximate VML blacklevel with a linear
// brightness shift using the same 0..32767 range Word's watermark UI uses.
const brightness = Math.max(0, 1 + blacklevel * (65536 / 32767));
if (brightness > 0) {
filters.push(`brightness(${brightness})`);
}
}
}
if (source.lum) {
// a:lum uses ST_FixedPercentage values expressed in thousandths of a percent.
// Convert those percentage deltas into CSS filter multipliers.
const contrastValue = typeof source.lum.contrast === 'number' ? clampLumUnit(source.lum.contrast) : null;
const brightValue = typeof source.lum.bright === 'number' ? clampLumUnit(source.lum.bright) : null;
if (contrastValue != null) {