-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathindex.ts
More file actions
3758 lines (3499 loc) · 126 KB
/
Copy pathindex.ts
File metadata and controls
3758 lines (3499 loc) · 126 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 { TabStop } from './engines/tabs.js';
import type { PageNumberChapterSeparator, PageNumberFieldFormat, PageNumberFormat } from './page-number-formatting.js';
import type { TrackedChangeSemanticColorKey } from './semantic-colors.js';
import type { AnchorAlignH, AnchorAlignV, AnchorHRelative, AnchorVRelative } from './graphic-placement.js';
export { computeTabStops, layoutWithTabs, calculateTabWidth } from './engines/tabs.js';
// Re-export TabStop for external consumers
export type { TabStop };
// Direction context types (orthogonal axes for RTL/BIDI).
// See `direction-context.ts` for the spec rationale and axis semantics.
export type {
BaseDirection,
WritingMode,
SectionDirectionContext,
TableDirectionContext,
CellDirectionContext,
ParagraphDirectionContext,
RunBidiContext,
RunScriptContext,
} from './direction-context.js';
export { getParagraphInlineDirection, getTableVisualDirection } from './direction-context.js';
import type {
BaseDirection,
ParagraphDirectionContext,
RunBidiContext,
RunScriptContext,
TableDirectionContext,
} from './direction-context.js';
// Export table contracts
export {
OOXML_PCT_DIVISOR,
resolveTableWidthAttr,
type TableWidthAttr,
type TableColumnSpec,
} from './engines/tables.js';
export { effectiveTableCellSpacing } from './table-cell-spacing.js';
export {
createHeaderFooterResolutionIndex,
selectHeaderFooterVariantForPage,
resolveEffectiveHeaderFooterRef,
type HeaderFooterResolutionIndex,
type HeaderFooterKind,
type HeaderFooterVariant,
type HeaderFooterSectionRefs,
type HeaderFooterResolutionSection,
type HeaderFooterVariantSelectionInput,
type HeaderFooterEffectiveRefInput,
type HeaderFooterEffectiveRefResult,
} from './header-footer-resolution.js';
// Table column rescaling (moved from layout-engine for cross-stage use)
export { rescaleColumnWidths } from './table-column-rescale.js';
// Cell spacing resolution (moved from measuring-dom for cross-stage use)
export { getCellSpacingPx } from './cell-spacing.js';
// OOXML z-index normalization (moved from pm-adapter for cross-stage use)
export {
normalizeZIndex,
coerceRelativeHeight,
isPlainObject,
OOXML_Z_INDEX_BASE,
resolveFloatingZIndex,
getFragmentZIndex,
} from './ooxml-z-index.js';
// Export justify utilities
export {
shouldApplyJustify,
calculateJustifySpacing,
calculateInterCharacterJustifySpacing,
interCharacterJustifyAdvanceBeforeOffset,
getFirstLineIndentOffset,
adjustAvailableWidthForTextIndent,
SPACE_CHARS,
type ShouldApplyJustifyParams,
type CalculateJustifySpacingParams,
type CalculateInterCharacterJustifySpacingParams,
} from './justify-utils.js';
export {
parseInsetClipPathForScale,
formatInsetClipPathTransform,
type InsetClipPathScale,
} from './clip-path-inset.js';
export {
SUBSCRIPT_SUPERSCRIPT_SCALE,
normalizeBaselineShift,
hasExplicitBaselineShift,
isSuperscriptOrSubscript,
usesDefaultScriptLayout,
scaleFontSizeForVerticalText,
resolveBaseFontSizeForVerticalText,
type VerticalTextAlign,
} from './vertical-text.js';
export { computeFragmentPmRange, computeLinePmRange, type LinePmRange } from './pm-range.js';
export {
resolveAnchoredGraphicY,
resolveAnchoredGraphicX,
resolveFooterPageFrameOriginY,
isPositionedParagraphFrame,
isPagePositionedParagraphFrame,
isPagePositionedFloatingTable,
isAnchorHRelative,
isAnchorVRelative,
isAnchorAlignH,
isAnchorAlignV,
ANCHOR_H_RELATIVE_VALUES,
ANCHOR_V_RELATIVE_VALUES,
ANCHOR_H_ALIGN_VALUES,
ANCHOR_V_ALIGN_VALUES,
type ColumnLayoutForAnchor,
type ResolveAnchoredGraphicYInput,
type ResolveAnchoredGraphicXContext,
type AnchorHRelative,
type AnchorVRelative,
type AnchorAlignH,
type AnchorAlignV,
} from './graphic-placement.js';
// Editor-neutral layout identity primitives (prep-001).
// Additive only — `pmStart`/`pmEnd` and PM-shaped fields remain available
// alongside these on every fragment/run.
export {
LAYOUT_BOUNDARY_SCHEMA,
bodyStoryLocator,
namedStoryLocator,
computeLayoutFragmentId,
buildLayoutSourceIdentity,
buildLayoutSourceIdentityForFragment,
} from './layout-identity.js';
export type {
LayoutBlockRef,
LayoutFragmentId,
LayoutPartialRowIdentity,
LayoutSourceIdentity,
LayoutStoryKind,
LayoutStoryLocator,
} from './layout-identity.js';
import type { LayoutSourceIdentity } from './layout-identity.js';
// Editor-neutral measured segment-geometry substrate (Phase 1 / 001).
// Additive only — promotes per-line / per-segment geometry the measure/layout
// pipeline already computes to a first-class neutral output. See
// `segment-geometry.ts`.
export { LAYOUT_SEGMENT_GEOMETRY_SCHEMA } from './segment-geometry.js';
export type {
NeutralTextDirection,
NeutralSegmentGeometry,
NeutralLineGeometryFlags,
NeutralLineGeometry,
NeutralGeometryDiagnostic,
NeutralFragmentGeometry,
NeutralSegmentGeometryReadback,
} from './segment-geometry.js';
export {
cloneColumnLayout,
columnLayoutsEqual,
columnRenderLayoutsEqual,
findColumnContaining,
getColumnAtX,
getColumnGapAfter,
getColumnGeometry,
getColumnSeparatorPositions,
getColumnWidth,
getColumnX,
normalizeColumnLayout,
resolveColumnCount,
resolveColumnLayout,
resolveColumnMode,
widthsEqual,
} from './column-layout.js';
export type { ColumnGeometry, NormalizedColumnLayout } from './column-layout.js';
export {
authorFromTrackedChangeMeta,
authorIdentityKey,
composeAuthorColorResolver,
fallbackAuthorColor,
stampTrackedChangeColors,
} from './author-colors.js';
export type { AuthorColorsConfig, TrackChangeAuthorColorResolver } from './author-colors.js';
export {
DEFAULT_TRACKED_CHANGE_SEMANTIC_COLORS,
TRACKED_CHANGE_AFFECTED_RANGE_KEYS,
TRACKED_CHANGE_CONFIGURABLE_SEMANTIC_COLOR_KEYS,
TRACKED_CHANGE_SEMANTIC_COLOR_KEYS,
TRACKED_CHANGE_SEMANTIC_TARGET_KINDS,
composeSemanticColorResolver,
defaultSemanticColor,
isConfigurableSemanticColorKey,
semanticColorAnchorScope,
semanticColorTargetKind,
stampTrackedChangeSemanticColors,
structuralSemanticColorKey,
trackedChangeLayersSignature,
trackedChangeMetaSignature,
} from './semantic-colors.js';
export type {
SemanticColorsConfig,
TrackChangeSemanticColorResolver,
TrackedChangeConfigurableSemanticColorKey,
TrackedChangeSemanticColorKey,
TrackedChangeSemanticColorResolverInput,
TrackedChangeSemanticTargetKind,
} from './semantic-colors.js';
export {
getSdtContainerKey,
getSdtContainerKeyForBlock,
getSdtContainerMetadata,
hasExplicitSdtContainerKey,
isSdtContainerMetadata,
} from './sdt-container.js';
export {
resolveInheritedHeaderFooterRef,
resolveInheritedHeaderFooterRefWithType,
type HeaderFooterRefIdentifier,
type HeaderFooterRefMap,
type ResolvedInheritedHeaderFooterRef,
type ResolveInheritedHeaderFooterRefInput,
} from './header-footer-inheritance.js';
export {
formatChapterPageNumberText,
formatIntegerWithNumericPicture,
formatPageNumber,
formatPageNumberFieldValue,
formatSectionPageNumberText,
type PageNumberFieldFormat,
type PageNumberChapterSeparator,
type PageNumberFormat,
} from './page-number-formatting.js';
export { buildPageRefAnchorMap } from './page-ref-anchor.js';
export {
DRAWING_DIAGNOSTIC_CODES,
DRAWING_DIAGNOSTIC_CODE_ALIASES,
DRAWING_SUPPORT_TAXONOMY,
DRAWING_FAMILIES,
canonicalDrawingDiagnosticCode,
getDrawingFamilySpec,
isSupportedDrawingFamily,
type DrawingContractTarget,
type DrawingDiagnosticCode,
type DrawingFamily,
type DrawingFamilySpec,
type DrawingSupportLevel,
type DrawingTaxonomyDrawingKind,
} from './drawing-taxonomy.js';
/** Inline field annotation metadata extracted from w:sdt nodes. */
export type FieldAnnotationMetadata = {
type: 'fieldAnnotation';
variant?: 'text' | 'image' | 'signature' | 'checkbox' | 'html' | 'link';
fieldId: string;
fieldType?: string;
displayLabel?: string;
defaultDisplayLabel?: string;
alias?: string;
fieldColor?: string;
borderColor?: string;
highlighted?: boolean;
fontFamily?: string | null;
fontSize?: string | number | null;
textColor?: string | null;
textHighlight?: string | null;
linkUrl?: string | null;
imageSrc?: string | null;
rawHtml?: unknown;
size?: {
width?: number;
height?: number;
} | null;
extras?: Record<string, unknown> | null;
multipleImage?: boolean;
hash?: string | null;
generatorIndex?: number | null;
sdtId?: string | null;
hidden?: boolean;
visibility?: 'visible' | 'hidden';
isLocked?: boolean;
formatting?: {
bold?: boolean;
italic?: boolean;
underline?: boolean;
};
marks?: Record<string, unknown>;
};
export type StructuredContentLockMode = 'unlocked' | 'sdtLocked' | 'contentLocked' | 'sdtContentLocked';
/**
* Visual chrome / labelling behavior of an SDT, mirroring
* `<w15:appearance w15:val="…">` (ECMA-376 §17.5.2.6 / OOXML 2010+).
*
* - `'boundingBox'` (default): visible chrome around the SDT content.
* - `'tags'`: tags-only mode (start/end markers).
* - `'hidden'`: no chrome at all; the SDT exists in the document but is
* visually transparent. The alias label MUST NOT leak into the rendered
* DOM textContent (a11y / copy-paste behavior).
*/
export type StructuredContentAppearance = 'boundingBox' | 'tags' | 'hidden';
export type StructuredContentMetadata = {
type: 'structuredContent';
scope: 'inline' | 'block';
id?: string | null;
tag?: string | null;
alias?: string | null;
lockMode?: StructuredContentLockMode;
/** Appearance from the SDT's `<w15:appearance>` element, when present. */
appearance?: StructuredContentAppearance;
sdtPr?: unknown;
};
export type DocumentSectionMetadata = {
type: 'documentSection';
id?: string | null;
title?: string | null;
description?: string | null;
sectionType?: string | null;
isLocked?: boolean;
sdBlockId?: string | null;
};
export type DocPartMetadata = {
type: 'docPartObject';
gallery?: string | null;
uniqueId?: string | null;
alias?: string | null;
instruction?: string | null;
};
/**
* Union of all SDT (Structured Document Tag) metadata variants.
*
* Word SDTs are flexible containers that can represent:
* - Field annotations: inline placeholders for user input
* - Structured content: containers with semantic tags (inline or block-level)
* - Document sections: locked or conditional regions with titles
* - Doc parts: special objects like tables of contents
*/
export type SdtMetadata =
| FieldAnnotationMetadata
| StructuredContentMetadata
| DocumentSectionMetadata
| DocPartMetadata;
export const CONTRACTS_VERSION = '1.2.0';
/** Unique identifier for a block in the document. Format: `${pos}-${type}`. */
export type BlockId = string;
/**
* Optional DOCX source evidence carried through the render pipeline.
*
* Phase 3 keeps this deliberately optional and payload-shaped so existing
* layout snapshots remain valid while source-linked intelligence consumers can
* preserve exact DOCX/source-tree anchors where available.
*/
export type SourceAnchor = {
sourceNodeId?: string;
occurrenceId?: string;
rawFactIds?: string[];
schemaQNames?: Array<{
qName: string;
namespaceUri?: string;
prefix?: string;
localName?: string;
ownerElementQName?: string;
}>;
featureKey?: string;
conceptKey?: string;
sourceRef?: {
partUri: string;
xpathLikePath: string;
rawFactId?: string;
occurrenceId?: string;
};
anchorConfidence?: 'high' | 'medium' | 'low';
pmNodeId?: string;
pmRange?: {
from: number;
to: number;
};
flowBlockId?: string;
layoutFragmentId?: string;
paintItemId?: string;
};
/** Tab leader type for filling space before tab stops. */
export type LeaderType = 'dot' | 'heavy' | 'hyphen' | 'middleDot' | 'underscore';
export type TrackedChangeKind = 'insert' | 'delete' | 'format';
export type TrackedChangesMode = 'review' | 'original' | 'final' | 'off';
/**
* Identity of a tracked-change author, used to resolve a per-author color.
*
* Mirrors the author metadata carried on {@link TrackedChangeMeta}
* (`author` → `name`, `authorEmail` → `email`, `authorImage` → `image`).
* Hosts configure per-author colors through this shape (see the
* `modules.trackChanges.authorColors` config on the `superdoc` package).
*/
export type TrackChangeAuthor = {
name?: string;
email?: string;
image?: string;
};
/** Formatting mark for track-format metadata. */
export type RunMark = {
type: string;
attrs?: Record<string, unknown> | null;
};
export type TrackedChangeMeta = {
kind: TrackedChangeKind;
id: string;
overlapParentId?: string;
relationship?: 'parent' | 'child' | 'standalone';
/**
* Internal story key identifying which content story owns this tracked
* change (`'body'`, `'hf:part:…'`, `'fn:…'`, `'en:…'`).
*
* Set by the PM adapter during conversion and stamped on the rendered DOM
* as `data-story-key` so downstream code can distinguish anchors across
* stories without re-resolving the story runtime.
*/
storyKey?: string;
author?: string;
authorEmail?: string;
authorImage?: string;
/**
* Paint-ready per-author color, resolved upstream (in/around the
* pm-adapter data-preparation pass) from the author identity. DomPainter
* reads only this field and stamps the element-scoped tracked-change CSS
* variables from it — it never invokes resolvers or touches app config.
* Undefined when per-author colors are disabled or unconfigured, in which
* case the static default tracked-change palette applies.
*/
color?: string;
/**
* Semantic visual color category for this change, e.g. `insertion`,
* `deletion`, `move-from`, `table-cell-insertion`, `cell-merge`.
* Independent of the author identity, so the same author can receive
* different colors for different review roles.
*/
semanticColorKey?: TrackedChangeSemanticColorKey;
/**
* Paint-ready semantic color, resolved upstream from
* {@link semanticColorKey}. Additive to and independent of the per-author
* `color`. DomPainter uses author color for plain insertion/deletion
* highlights when present, while side/structural semantic categories
* (`move-from`, `table-cell-insertion`, `cell-merge`, etc.) keep semantic
* visual precedence. Undefined when semantic colors are disabled or this layer
* carries no semantic category.
*/
semanticColor?: string;
/** Raw tracked-change type carried for semantic resolution/projection. */
type?: string;
/** Logical subtype carried for semantic resolution/projection. */
subtype?: string;
/** Target kind (e.g. text/cell/row/table) for semantic resolution. */
targetKind?: string;
/**
* Scope of the semantic paint anchor when paint applies to an affected range
* rather than a single direct marker (e.g. `'affected-range'` for a derived
* cell split).
*/
semanticAnchorScope?: string;
date?: string;
before?: RunMark[];
after?: RunMark[];
};
/**
* Tracked-change review metadata attached to a list marker glyph (Plan 5).
*
* A list marker is generated chrome, not a text run, so run-level tracked-change
* decorations never reach it automatically. When a paragraph's visible marker is
* affected by a guide-relevant tracked change (list add/remove, numbering/level
* change, list item insert/delete, paragraph-mark insert/delete, or a moved list
* item), the projection attaches this metadata so the painter can stamp the same
* review identity/classes/CSS variables the run path uses and paint Word-like
* marker glyph color + underline.
*
* It reuses the canonical {@link TrackedChangeMeta} so marker and run review
* metadata never drift, plus an optional `groupedIds` for the
* `data-track-change-ids` attribute when more than one change affects one marker.
*/
export type MarkerTrackedChange = TrackedChangeMeta & {
/** All tracked-change ids affecting this marker, for `data-track-change-ids`. */
groupedIds?: readonly string[];
};
/**
* HTML anchor target. DOCX `w:tgtFrame` may be one of the reserved browsing
* context names (`_blank`, `_self`, `_parent`, `_top`) or an arbitrary named
* frame/window such as `report-frame`.
*/
export type FlowRunLinkTarget = string;
export type FlowRunLink = {
version?: 1 | 2;
href?: string;
title?: string;
target?: FlowRunLinkTarget;
rel?: string;
tooltip?: string;
anchor?: string;
docLocation?: string;
rId?: string;
name?: string;
history?: boolean;
};
export const EMPTY_SDT_PLACEHOLDER_TEXT = 'Click or tap here to enter text';
export type SdtVisualPlaceholder = 'emptyInlineSdt' | 'emptyBlockSdt';
/**
* Common formatting marks that can be applied to any run type.
* Used by TextRun, TabRun, and other run types that support inline formatting.
*/
export type RunMarks = {
/** Bold text styling. */
bold?: boolean;
/** Italic text styling. */
italic?: boolean;
/** Additional letter spacing in pixels (positive for expanded, negative for condensed). */
letterSpacing?: number;
/** Horizontal glyph scale as a unitless multiplier (`1` = 100%, `0.9` = 90%). */
horizontalScale?: number;
/** Text color as hex string (e.g., "#FF0000"). */
color?: string;
/** Underline decoration with optional style and color. */
underline?: {
/** Underline style (defaults to 'single'). */
style?: 'single' | 'double' | 'dotted' | 'dashed' | 'wavy';
/** Underline color as hex string (defaults to text color). */
color?: string;
} | null;
/** Strikethrough text decoration. */
strike?: boolean;
/** Word `w:dstrike`: the strikethrough is drawn as two lines instead of one. */
doubleStrike?: boolean;
/** Word `w:outline`: glyphs are drawn as an outline with no fill. */
outline?: boolean;
/** Word `w:shadow`: a drop shadow is drawn behind the glyphs. */
shadow?: boolean;
/** Word `w:emboss`: glyphs are shaded to look raised out of the page. */
emboss?: boolean;
/** Word `w:imprint`: glyphs are shaded to look pressed into the page. */
imprint?: boolean;
/** Highlight (background) color as hex string. */
highlight?: string;
/** Text transformation (case modification). */
textTransform?: 'uppercase' | 'lowercase' | 'capitalize' | 'none';
/** Word hidden-text formatting (`w:vanish`): styleable runs remain addressable but do not paint or measure. */
vanish?: boolean;
/** Vertical alignment for superscript/subscript text. */
vertAlign?: 'superscript' | 'subscript' | 'baseline';
/**
* Explicit baseline shift in points (positive = raise, negative = lower).
* Rendering normalizes a shift of zero to "no explicit shift".
*/
baselineShift?: number;
/** Paint-only Word 2010+ text effects (`w14:textFill`, outline, shadow, reflection). */
textEffects?: TextEffects;
};
export type PageReferenceRelativePositionText = 'above' | 'below';
export type FieldResultFormat = 'charformat' | 'mergeformat';
export type NumericPictureFormat = {
/** Raw argument after the \# switch, without surrounding quotes. */
picture: string;
};
export interface PageRefLocation {
physicalPage: number;
displayNumber: number;
displayText: string;
pageFormat?: PageNumberFormat;
chapterNumberText?: string;
chapterSeparator?: PageNumberChapterSeparator;
sectionIndex?: number;
pmPosition?: number;
}
export type CrossReferenceMetadata = {
/** Cross-reference family parsed from the field instruction. */
kind: 'ref' | 'noteRef' | 'styleRef';
/** Original field instruction, retained so Word switches remain authoritative. */
instruction: string;
/** Bookmark name for REF/NOTEREF, or style name for STYLEREF. */
target: string;
/** STYLEREF `\\l`: prefer the following/last matching paragraph. */
preferFollowing?: boolean;
};
export type TextRun = RunMarks & {
kind?: 'text';
text: string;
fontFamily: string;
fontSize: number;
/** Comment annotations applied to this run (supports overlapping comments). */
comments?: Array<{
commentId: string;
importedId?: string;
internal?: boolean;
trackedChange?: boolean;
trackedChangeThreadParentId?: string;
}>;
/**
* Custom data attributes propagated from ProseMirror marks (keys must be data-*).
*/
dataAttrs?: Record<string, string>;
sdt?: SdtMetadata;
/** Layout-only placeholder for visual affordances that do not represent document text. */
visualPlaceholder?: SdtVisualPlaceholder;
link?: FlowRunLink;
/** Token annotations for dynamic content (page numbers, etc.). */
token?: 'pageNumber' | 'totalPageCount' | 'pageReference' | 'sectionPageCount' | 'seq';
/** Explicit formatting requested by PAGE/NUMPAGES/SECTIONPAGES field switches. */
pageNumberFieldFormat?: PageNumberFieldFormat;
/** Absolute ProseMirror position (inclusive) of first character in this run. */
pmStart?: number;
/** Absolute ProseMirror position (exclusive) after the last character. */
pmEnd?: number;
/** Metadata for page reference tokens (only when token === 'pageReference'). */
pageRefMetadata?: {
bookmarkId: string;
instruction: string;
/** True when the instruction has \p. */
relativePosition?: boolean;
/** General numeric formatting switch for the PAGEREF page value. */
pageNumberFieldFormat?: PageNumberFieldFormat;
/** Raw numeric picture from \#. */
numericPictureFormat?: NumericPictureFormat;
/** CHARFORMAT / MERGEFORMAT, if present. */
fieldResultFormat?: FieldResultFormat;
};
/** Metadata for REF/NOTEREF/STYLEREF live result resolution before measurement. */
crossReferenceMetadata?: CrossReferenceMetadata;
/** Metadata for SEQ tokens (resolved by the document runtime before layout measurement). */
seqMetadata?: {
identifier: string;
instruction?: string;
fieldArgument?: string;
sequenceMode?: 'next' | 'current';
hideResult?: boolean;
restartNumber?: number | null;
restartLevel?: number | null;
format?: string;
hasGeneralFormat?: boolean;
pageNumberFieldFormat?: PageNumberFieldFormat | null;
numericPictureFormat?: NumericPictureFormat | null;
cachedText?: string;
};
/** Tracked-change metadata from ProseMirror marks. */
trackedChange?: TrackedChangeMeta;
/** All tracked-change layers on this run, preserving overlap order. */
trackedChanges?: TrackedChangeMeta[];
/**
* Run-level bidi signals preserved from the source DOCX (run rtl flag,
* embedding/override directions). Direction-only - script formatting lives
* on `script`. Populated by pm-adapter from raw run properties; not yet
* rendered (Wave 1c consumes embedding/override).
*/
bidi?: RunBidiContext;
/**
* Run-level script context preserved from the source DOCX (complex-script
* flag, per-script language metadata). Wave 1b uses `complexScript` to gate
* the formatting-stack selection (Latin variants vs CS variants).
*/
script?: RunScriptContext;
};
export type TabRun = RunMarks & {
kind: 'tab';
text: '\t';
/**
* Font of the tab, inherited from the paragraph's resolved run properties. A tab has
* no glyphs, but its font drives the line height (so a tab-only line matches a text
* line) and the underline weight. Optional: not every producer sets it.
*/
fontFamily?: string;
fontSize?: number;
/** Width in pixels (assigned by measurer/resolver). */
width?: number;
tabStops?: TabStop[];
tabIndex?: number;
leader?: LeaderType | null;
decimalChar?: string;
indent?: ParagraphIndent;
pmStart?: number;
pmEnd?: number;
/** SDT metadata if tab is inside a structured document tag. */
sdt?: SdtMetadata;
};
export type LineBreakRun = {
kind: 'lineBreak';
/**
* Optional attributes carried through from the source document.
* Mirrors OOXML <w:br> attributes (type/clear) to preserve fidelity.
*/
attrs?: {
lineBreakType?: string;
clear?: string;
};
pmStart?: number;
pmEnd?: number;
};
export type ImageLuminanceAdjustment = {
/** OOXML a:lum/@bright in raw units (-100000..100000). */
bright?: number;
/** OOXML a:lum/@contrast in raw units (-100000..100000). */
contrast?: number;
};
export type ImageAlphaModFix = {
/** OOXML a:alphaModFix/@amt in raw fixed-percentage units (0..100000). */
amt: number;
};
/** Hyperlink metadata from OOXML a:hlinkClick on a DrawingML image. */
export type ImageHyperlink = { url: string; tooltip?: string };
/**
* Vertical alignment mode for an inline {@link ImageRun}.
*
* - `'top'`: the image box top aligns to the top of the line box. This is the
* legacy default and the behavior for inline images that are taller than the
* text-derived line height (they expand the line).
* - `'bottom'`: legacy baseline-ish alignment preserved for existing callers.
* - `'baseline'`: the image box bottom aligns to the text baseline. Intended for
* small, glyph-like inline images (for example tiny PNG section numbers used
* as text) that fit inside the text-derived line box and should sit on the
* baseline next to the surrounding text instead of floating above it.
*/
export type ImageRunVerticalAlign = 'top' | 'bottom' | 'baseline';
/**
* Paint-only frame authored on a DrawingML picture (`pic:spPr/a:ln`).
*
* The frame is intentionally separate from the image dimensions: DrawingML
* strokes are centered on the picture geometry and must not enlarge the
* layout box. Keeping this as a shared contract lets inline and anchored
* pictures use the same extraction and paint path.
*/
export type ImageOutline = {
color: string;
/** Physical CSS-pixel width resolved from `a:ln/@w`. */
width: number;
};
/**
* Explicit fail-closed rendering metadata for content that keeps its authored
* layout box but cannot be painted faithfully.
*
* The producer owns the diagnostic identity; painters only expose it on the
* visible, accessible placeholder. This keeps support decisions out of the DOM
* layer and makes degraded output observable in browser regression proofs.
*/
export type RenderPlaceholder = {
diagnosticIds: string[];
accessibleName: string;
};
/**
* Inline image run for images that flow with text on the same line.
* Unlike ImageBlock (anchored/floating images), ImageRun is part of the paragraph's run array
* and participates in line breaking alongside text.
*
* Corresponds to Microsoft Word's inline images (<wp:inline> in DOCX).
*
* @example
* // A paragraph with text and inline image:
* {
* kind: 'paragraph',
* runs: [
* { kind: 'text', text: 'Here is an image: ', ... },
* { kind: 'image', src: 'data:...', width: 100, height: 50, ... },
* { kind: 'text', text: ' within text.', ... }
* ]
* }
*/
export type ImageRun = {
kind: 'image';
/** Image source URL (data URI or external URL). */
src: string;
/** Image width in pixels. */
width: number;
/** Image height in pixels. */
height: number;
/** Font family of the owning OOXML run, used to compose an image-only line box. */
fontFamily?: string;
/** Font size of the owning OOXML run, used to compose an image-only line box. */
fontSize?: number;
/** Alternative text for accessibility. */
alt?: string;
/** Image title (tooltip). */
title?: string;
/** Visible fail-closed replacement when the image source cannot be painted. */
placeholder?: RenderPlaceholder;
/** DrawingML docPr/@id of the picture (used to target the Document API for interactive resize). */
imageId?: string;
/** Opaque Document API identity when projection can resolve it without a catalog read. */
imageMutationId?: string;
/** Clip-path value for cropped images. */
clipPath?: string;
/** DrawingML picture frame; paint-only and excluded from layout sizing. */
outline?: ImageOutline;
/**
* Spacing around the image (from DOCX distT/distB/distL/distR attributes).
* Applied as CSS margins in the DOM painter.
* All values in pixels.
*/
distTop?: number;
distBottom?: number;
distLeft?: number;
distRight?: number;
/**
* Vertical alignment of image relative to the line box / text baseline.
*
* When omitted, the painter falls back to legacy `'top'`. See
* {@link ImageRunVerticalAlign} for the semantics of each mode. An authored
* value here is treated as the source of truth and always wins over the
* measured per-line alignment in {@link Line.inlineImageAlignments}.
*/
verticalAlign?: ImageRunVerticalAlign;
/** Absolute ProseMirror position (inclusive) of this image run. */
pmStart?: number;
/** Absolute ProseMirror position (exclusive) after this image run. */
pmEnd?: number;
/** SDT metadata if image is wrapped in a structured document tag. */
sdt?: SdtMetadata;
/** Tracked-change metadata from OOXML wrappers that own this inline image. */
trackedChange?: TrackedChangeMeta;
/** All tracked-change layers on this inline image, preserving overlap order. */
trackedChanges?: TrackedChangeMeta[];
/**
* Custom data attributes propagated from ProseMirror marks (keys must be data-*).
*/
dataAttrs?: Record<string, string>;
// Image transformations from OOXML a:xfrm (applies to inline images)
rotation?: number; // Rotation angle in degrees
flipH?: boolean; // Horizontal flip
flipV?: boolean; // Vertical flip
// VML image adjustments for watermark effects
gain?: string | number; // Brightness/washout (VML hex string or number)
blacklevel?: string | number; // Contrast adjustment (VML hex string or number)
// OOXML image effects
grayscale?: boolean; // Apply grayscale filter to image
lum?: ImageLuminanceAdjustment; // DrawingML luminance adjustment from a:lum
alphaModFix?: ImageAlphaModFix; // DrawingML fixed alpha adjustment from a:alphaModFix
/** Image hyperlink from OOXML a:hlinkClick. When set, clicking the image opens the URL. */
hyperlink?: ImageHyperlink;
};
export type BreakRun = RunMarks & {
kind: 'break';
/** Optional break type (e.g., 'line', 'page', 'column') */
breakType?: 'line' | 'page' | 'column' | string;
/**
* Font metrics inherited from the run carrying the break.
*
* Block-level break runs do not paint text directly, but the v2 exact
* composition path may split a break-only paragraph into a page/column break
* plus a synthetic empty paragraph. That synthetic paragraph must keep the
* source paragraph mark's metrics so blank-line height matches Word/V1.
*/
fontFamily?: string;
fontSize?: number;
pmStart?: number;
pmEnd?: number;
sdt?: SdtMetadata;
trackedChange?: TrackedChangeMeta;
trackedChanges?: TrackedChangeMeta[];
};
/**
* Inline field annotation run for interactive form fields displayed as styled "pills".
* Renders as a bordered, rounded inline element with displayLabel or type-specific content.
*
* Corresponds to a field-annotation document node rendered as a styled inline element.
*
* @example
* // A paragraph with text and field annotation:
* {
* kind: 'paragraph',
* runs: [
* { kind: 'text', text: 'Enter name: ', ... },
* { kind: 'fieldAnnotation', variant: 'text', displayLabel: 'Full Name', fieldColor: '#980043', ... },
* ]
* }
*/
export type FieldAnnotationRun = {
kind: 'fieldAnnotation';
/** The variant/type of field annotation. */
variant: 'text' | 'image' | 'signature' | 'checkbox' | 'html' | 'link';
/** Display text shown inside the pill (fallback for all types). */
displayLabel: string;
/** Unique field identifier. */
fieldId?: string;
/** Field type identifier (e.g., 'TEXTINPUT', 'SIGNATURE'). */
fieldType?: string;
/** Background color as hex string (e.g., "#980043"). Applied with alpha. */
fieldColor?: string;
/** Border color as hex string (e.g., "#b015b3"). */
borderColor?: string;
/** Whether to show the pill styling (border, background). Defaults to true. */
highlighted?: boolean;
/** Whether the field is hidden (display: none). */
hidden?: boolean;
/** CSS visibility value. */
visibility?: 'visible' | 'hidden';
// Type-specific content
/** Image source URL for image/signature variants. */
imageSrc?: string | null;
/** Link URL for link variant. */
linkUrl?: string | null;
/** Raw HTML content for html variant. */
rawHtml?: string | null;
// Sizing
/** Explicit size for the annotation (used for images). */
size?: {
width?: number;
height?: number;
} | null;
// Typography (applied to the displayLabel text)
/** Font family for the label text. */
fontFamily?: string | null;
/** Font size in points or pixels (e.g., "12pt", 14). */
fontSize?: string | number | null;
/** Text color as hex string. */
textColor?: string | null;
/** Text highlight/background color (overrides fieldColor). */
textHighlight?: string | null;
/** Bold text styling. */
bold?: boolean;
/** Italic text styling. */
italic?: boolean;
/** Underline text styling. */
underline?: boolean;
/** Absolute ProseMirror position (inclusive) of this run. */
pmStart?: number;
/** Absolute ProseMirror position (exclusive) after this run. */
pmEnd?: number;
/** Full SDT metadata if available. */
sdt?: SdtMetadata;
};
export type MathRun = {
kind: 'math';
/** OMML XML as JSON (xml2json format) for the renderer to convert to MathML. */
ommlJson: unknown;
/** Plain text content for measurement fallback and accessibility. */
textContent: string;
/** Estimated width in pixels. */
width: number;
/** Estimated height in pixels. */
height: number;
/** Absolute ProseMirror position (inclusive) of this math run. */
pmStart?: number;
/** Absolute ProseMirror position (exclusive) after this math run. */
pmEnd?: number;
/** SDT metadata if math is wrapped in a structured document tag. */
sdt?: SdtMetadata;
};
export type Run = TextRun | TabRun | ImageRun | LineBreakRun | BreakRun | FieldAnnotationRun | MathRun;
/** Layout-affecting inline-box values, resolved to logical CSS pixel sides. */
export type ResolvedInlineBoxLayout = {
paddingInlineStart: number;
paddingInlineEnd: number;
paddingBlockStart: number;
paddingBlockEnd: number;
gapBefore: number;