forked from superdoc/docx-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremeasure.ts
More file actions
2312 lines (2190 loc) · 96.1 KB
/
Copy pathremeasure.ts
File metadata and controls
2312 lines (2190 loc) · 96.1 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 {
ParagraphBlock,
ParagraphMeasure,
ParagraphSpacing,
Line,
LineInlineImageAlignment,
LineSegment,
Run,
ImageRun,
TextRun,
TabRun,
TabStop,
ParagraphIndent,
LeaderDecoration,
ParagraphLineRegion,
} from '@superdoc/contracts';
import {
EMPTY_SDT_PLACEHOLDER_TEXT,
Engines,
getParagraphInlineDirection,
isEmptySdtPlaceholderRun,
sliceRunsForLine,
} from '@superdoc/contracts';
import type { WordParagraphLayoutOutput } from '@superdoc/word-layout';
import {
LIST_MARKER_GAP as _LIST_MARKER_GAP,
SPACE_SUFFIX_GAP_PX as _SPACE_SUFFIX_GAP_PX,
DEFAULT_TAB_INTERVAL_PX as _DEFAULT_TAB_INTERVAL_PX,
} from '@superdoc/common/layout-constants';
import { resolveListTextStartPx } from '@superdoc/common/list-marker-utils';
import {
getCalibratedNaturalSingleLine,
collectCjkJustificationBoundaries,
isCjkBreakOpportunityChar,
nextCodePointBoundary,
resolveKinsokuBoundary,
} from '@superdoc/measuring-dom';
/**
* Type definition for paragraph block attributes that include indentation and tab stops.
* Extracted for cleaner type safety when accessing block.attrs.
*/
type ParagraphBlockAttrs = {
alignment?: 'left' | 'center' | 'right' | 'justify';
indent?: { left?: number; right?: number; firstLine?: number; hanging?: number };
tabs?: TabStop[];
tabIntervalTwips?: number;
decimalSeparator?: string;
spacing?: ParagraphSpacing;
wordLayout?: WordParagraphLayoutOutput;
numberingProperties?: unknown;
/** Word quirk: justified paragraphs ignore first-line indent. Set by pm-adapter. */
suppressFirstLineIndent?: boolean;
};
let canvas: HTMLCanvasElement | null = null;
let ctx: CanvasRenderingContext2D | null = null;
/**
* Retrieves or creates a canvas rendering context for text measurement.
*
* This function manages a singleton canvas context used across all text measurements.
* The canvas context provides the measureText API which is essential for accurate
* text width calculations that match browser rendering.
*
* @returns Canvas 2D rendering context if available in browser environment, null otherwise.
* Returns null in server-side rendering contexts where document is undefined.
*/
function getCtx(): CanvasRenderingContext2D | null {
if (ctx) return ctx;
if (typeof document === 'undefined') return null;
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
return ctx;
}
// ---------------------------------------------------------------------------
// Text-width caches (plans/layout-improvements.md idea 2).
//
// remeasureParagraph historically issued one `ctx.font = ...` assignment plus
// one `ctx.measureText(singleChar)` call PER CHARACTER of every remeasured
// paragraph, with no caching — the dominant cost of a legitimate remeasure
// (multi-column sections, float-narrowed regions, textboxes). Both caches are
// exact under the existing width model:
// - the greedy line breaker sums independent single-character measurements, so
// a per-(font, char) advance cache reproduces identical arithmetic;
// - slice measurement (tab groups / line segments / SDT placeholders) measures
// a whole slice in one measureText call, so results are memoized verbatim by
// (font, text) with letter-spacing applied arithmetically outside the cache.
// Word-chunked measurement was deliberately NOT adopted: measuring whole words
// in one call would let intra-word kerning/ligatures change computed widths
// versus the per-character summing model, shifting line breaks.
//
// Staleness: entries key off the resolved canvas font string, so a late-
// loading font face (same font string, new face) would invalidate them. The
// incrementalLayout pipeline clears these caches whenever the document font
// signature changes; standalone callers can clear via
// clearRemeasureTextCaches(). This matches the exposure of measuring-dom's
// module-level measurement cache.
// ---------------------------------------------------------------------------
const MAX_GLYPH_FONT_ENTRIES = 64;
const MAX_GLYPH_ADVANCES_PER_FONT = 2048;
const MAX_SLICE_CACHE_ENTRIES = 4096;
/** Per-font single-character advance cache: font string -> (char -> width px). */
const glyphAdvancesByFont = new Map<string, Map<string, number>>();
/** Whole-slice base width cache (no letter-spacing): "font\0text" -> width px. */
const sliceWidthCache = new Map<string, number>();
/** Drop cached text widths and the canvas context. Call when registered font faces may have changed. */
export function clearRemeasureTextCaches(): void {
glyphAdvancesByFont.clear();
sliceWidthCache.clear();
ctx = null;
canvas = null;
}
/** Measure a single character's advance for a font, through the glyph cache. */
function measureGlyphAdvance(context: CanvasRenderingContext2D, font: string, char: string): number {
let advances = glyphAdvancesByFont.get(font);
if (!advances) {
if (glyphAdvancesByFont.size >= MAX_GLYPH_FONT_ENTRIES) glyphAdvancesByFont.clear();
advances = new Map();
glyphAdvancesByFont.set(font, advances);
}
const cached = advances.get(char);
if (cached !== undefined) return cached;
context.font = font;
const width = context.measureText(char).width;
if (advances.size >= MAX_GLYPH_ADVANCES_PER_FONT) advances.clear();
advances.set(char, width);
return width;
}
/** Measure a multi-character slice's base width (no letter-spacing), memoized. */
function measureSliceBaseWidth(context: CanvasRenderingContext2D, font: string, text: string): number {
// "\0" cannot appear in a canvas font string, so the first NUL delimits unambiguously.
const key = font + '\u0000' + text;
const cached = sliceWidthCache.get(key);
if (cached !== undefined) return cached;
context.font = font;
const width = context.measureText(text).width;
if (sliceWidthCache.size >= MAX_SLICE_CACHE_ENTRIES) sliceWidthCache.clear();
sliceWidthCache.set(key, width);
return width;
}
/**
* Type guard to determine if a run is a TextRun (has text content and formatting).
*
* In the SuperDoc run model, runs can be various types (text, tab, image, break, etc.).
* TextRuns are the only runs that have text content and typography properties
* (fontSize, fontFamily, bold, italic). This type guard enables safe access to
* these properties by narrowing the Run union type to TextRun.
*
* Run types that are NOT TextRuns:
* - tab: Represents horizontal tab character (no text content)
* - lineBreak: Represents soft line break
* - break: Represents page/column break
* - fieldAnnotation: Represents field metadata
* - image/drawing runs with 'src' property
*
* @param run - The run to check (can be any Run type from the union).
* @returns True if the run is a TextRun with text content and formatting properties,
* false for tabs, breaks, images, and other non-text run types.
*/
function isTextRun(run: Run): run is TextRun {
// Explicitly check for non-text run types
if (run.kind === 'tab' || run.kind === 'lineBreak' || run.kind === 'break' || run.kind === 'fieldAnnotation') {
return false;
}
// Check for image/drawing runs which have 'src' property
if ('src' in run) {
return false;
}
// All other runs are text runs
return true;
}
const isVanishedRun = (run: Run | undefined): boolean => (run as { vanish?: boolean } | undefined)?.vanish === true;
function visibleTextFontSize(run: Run | undefined): number | undefined {
if (!run || isVanishedRun(run) || !isTextRun(run)) return undefined;
return typeof run.fontSize === 'number' ? run.fontSize : undefined;
}
function visibleLineHeightFontSize(run: Run | undefined): number | undefined {
if (!run || isVanishedRun(run)) return undefined;
if (!isTextRun(run) && run.kind !== 'tab') return undefined;
const fontSize = (run as TextRun | TabRun).fontSize;
return typeof fontSize === 'number' ? fontSize : undefined;
}
/**
* Generates a CSS font string for canvas text measurement from a run's formatting.
*
* The canvas measureText API requires a CSS font string (e.g., "italic bold 16px Arial")
* to accurately measure text width. This function converts SuperDoc run formatting
* properties (fontSize, fontFamily, bold, italic) into the CSS font string format.
*
* CSS font string format: [style] [weight] <size> <family>
* - style: "italic" or omitted
* - weight: "bold" or omitted
* - size: font size in pixels (required)
* - family: font family name (required)
*
* @param run - The run containing formatting properties (fontSize, fontFamily, bold, italic).
* For non-text runs (tabs, breaks), uses default formatting values.
* @returns CSS font string suitable for CanvasRenderingContext2D.font property.
* Example outputs: "16px Arial", "italic bold 24px Times New Roman"
*/
function fontString(run: Run): string {
const textRun = isTextRun(run) ? run : null;
const size = textRun?.fontSize ?? 16;
const family = textRun?.fontFamily ?? 'Arial';
const italic = textRun?.italic ? 'italic ' : '';
const bold = textRun?.bold ? 'bold ' : '';
return `${italic}${bold}${size}px ${family}`.trim();
}
/**
* Extracts text content from a run.
*
* Different run types have different text content:
* - Text runs: Have text property with string content
* - Image/drawing runs: Have 'src' property, no text content
* - Line breaks, breaks, field annotations: Special kinds with no text content
*
* @param run - The run to extract text from
* @returns Text content of the run, or empty string for non-text runs
*/
function runText(run: Run): string {
if (isEmptySdtPlaceholderRun(run)) {
return run.sdt?.type === 'structuredContent' && run.sdt.appearance === 'hidden' ? '' : EMPTY_SDT_PLACEHOLDER_TEXT;
}
return 'src' in run ||
run.kind === 'lineBreak' ||
run.kind === 'break' ||
run.kind === 'fieldAnnotation' ||
run.kind === 'math'
? ''
: (run.text ?? '');
}
const runAddressableLength = (run: Run): number => {
const textLength = runText(run).length;
return textLength > 0 ? textLength : run.kind === 'tab' ? 1 : 0;
};
/**
* Determines if a character is considered a "word character" for capitalization.
*
* Word characters are defined as:
* - Digits: 0-9 (ASCII 48-57)
* - Uppercase letters: A-Z (ASCII 65-90)
* - Lowercase letters: a-z (ASCII 97-122)
* - Apostrophe: ' (for contractions like "don't", "it's")
*
* Used by capitalizeText to determine word boundaries. A capital letter is
* applied when a word character follows a non-word character.
*
* @param char - The character to check (single character string)
* @returns True if the character is a word character, false otherwise
*
* @example
* ```typescript
* isWordChar('a'); // true
* isWordChar('Z'); // true
* isWordChar('5'); // true
* isWordChar("'"); // true (for contractions)
* isWordChar(' '); // false
* isWordChar('-'); // false
* ```
*/
const isWordChar = (char: string): boolean => {
if (!char) return false;
const code = char.charCodeAt(0);
return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || char === "'";
};
/**
* Capitalizes the first letter of each word in text.
*
* Implements CSS text-transform: capitalize by uppercasing the first character
* of each word. A word is defined as any sequence of word characters (letters,
* digits, apostrophes) preceded by a non-word character or the start of text.
*
* This function handles proper word boundary detection even when operating on
* a slice of text within a larger string (via fullText and startOffset parameters),
* ensuring correct capitalization at slice boundaries.
*
* @param text - The text to capitalize
* @param fullText - Optional full text context (for proper boundary detection when text is a slice)
* @param startOffset - Optional offset of text within fullText (required if fullText provided)
* @returns Text with first letter of each word capitalized
*
* @example
* ```typescript
* capitalizeText("hello world");
* // Returns: "Hello World"
*
* capitalizeText("don't stop");
* // Returns: "Don't Stop"
*
* // With full text context for slice
* capitalizeText("world", "hello world", 6);
* // Returns: "world" (not "World" because 'w' is mid-word in full context)
* ```
*/
const capitalizeText = (text: string, fullText?: string, startOffset?: number): string => {
if (!text) return text;
const hasFullText = typeof startOffset === 'number' && fullText != null;
let result = '';
for (let i = 0; i < text.length; i += 1) {
const prevChar = hasFullText
? startOffset! + i > 0
? fullText![startOffset! + i - 1]
: ''
: i > 0
? text[i - 1]
: '';
const ch = text[i];
result += isWordChar(ch) && !isWordChar(prevChar) ? ch.toUpperCase() : ch;
}
return result;
};
/**
* Applies CSS text-transform to text.
*
* Implements the CSS text-transform property values:
* - 'uppercase': Convert all characters to uppercase
* - 'lowercase': Convert all characters to lowercase
* - 'capitalize': Capitalize first letter of each word (via capitalizeText)
* - 'none': No transformation (return original text)
*
* Used during text measurement to apply visual transformations without mutating
* the underlying document model. The transform is applied during rendering and
* measurement but does not affect the stored text content.
*
* @param text - The text to transform
* @param transform - CSS text-transform value ('uppercase', 'lowercase', 'capitalize', 'none', undefined)
* @param fullText - Optional full text context (passed to capitalizeText for proper word boundaries)
* @param startOffset - Optional offset within fullText (passed to capitalizeText)
* @returns Transformed text, or original text if transform is 'none' or undefined
*
* @example
* ```typescript
* applyTextTransform("Hello World", "uppercase");
* // Returns: "HELLO WORLD"
*
* applyTextTransform("Hello World", "lowercase");
* // Returns: "hello world"
*
* applyTextTransform("hello world", "capitalize");
* // Returns: "Hello World"
*
* applyTextTransform("hello", undefined);
* // Returns: "hello" (no transformation)
* ```
*/
const applyTextTransform = (
text: string,
transform: 'uppercase' | 'lowercase' | 'capitalize' | 'none' | undefined,
fullText?: string,
startOffset?: number,
): string => {
if (!text || !transform || transform === 'none') return text;
if (transform === 'uppercase') return text.toUpperCase();
if (transform === 'lowercase') return text.toLowerCase();
if (transform === 'capitalize') return capitalizeText(text, fullText, startOffset);
return text;
};
/**
* Single-character variant of applyTextTransform for the line-breaking hot
* loop. Equivalent to `applyTextTransform(text[index], transform, text, index)`
* without the per-character slice/branch overhead.
*/
const transformChar = (
text: string,
index: number,
transform: 'uppercase' | 'lowercase' | 'capitalize' | 'none' | undefined,
/** Exclusive end of the code point at `index`; two units for astral characters. */
end?: number,
): string => {
const char = typeof end === 'number' ? text.slice(index, end) : text[index];
if (!transform || transform === 'none') return char;
if (transform === 'uppercase') return char.toUpperCase();
if (transform === 'lowercase') return char.toLowerCase();
// capitalize: uppercase a word character that follows a non-word character.
const prevChar = index > 0 ? text[index - 1] : '';
return isWordChar(char) && !isWordChar(prevChar) ? char.toUpperCase() : char;
};
// --- Tab helpers (aligned with measuring/dom defaults) ---
const DEFAULT_TAB_INTERVAL_TWIPS = 720; // 0.5in
const TWIPS_PER_INCH = 1440;
const PX_PER_INCH = 96;
const TWIPS_PER_PX = TWIPS_PER_INCH / PX_PER_INCH; // 15 twips per px
/**
* Floating-point tolerance for tab stop comparison (0.1 pixels).
*
* Why this constant exists:
* - Canvas text measurement produces floating-point widths with minor precision variations
* - When checking if current position has passed a tab stop, exact equality is unreliable
* - Without tolerance, tab stops at position X might be skipped when current position is X - 0.0001
*
* Why 0.1px was chosen:
* - Large enough to absorb floating-point rounding errors (typically < 0.05px)
* - Small enough to avoid incorrectly skipping legitimate tab stops
* - Visually imperceptible at standard screen resolutions (< 1/10th of a pixel)
*
* Usage:
* - When finding next tab stop: `tabStops[i].pos <= currentX + TAB_EPSILON`
* - Ensures tab stops within 0.1px of current position are considered "reached"
*/
const TAB_EPSILON = 0.1;
/**
* Floating-point tolerance for line breaking decisions (0.5 pixels).
*
* Why this constant exists:
* - Canvas text measurement can vary slightly between measurement and rendering contexts
* - Different browsers may round sub-pixel measurements differently
* - Without tolerance, lines might break prematurely when text is *almost* at maxWidth
*
* Why 0.5px was chosen:
* - Large enough to absorb typical floating-point rounding errors (0.1-0.3px)
* - Small enough to be visually imperceptible at standard screen resolutions
* - Conservative value that prevents premature line breaks without allowing significant overflow
*
* Usage:
* - When checking if another glyph still fits: `width + glyphWidth > effectiveMaxWidth - WIDTH_FUDGE_PX`
* - Gives layout a 0.5px safety margin before triggering a normal line break
* - Prevents edge cases where measured text at 199.7px breaks on a 200px line
*/
const WIDTH_FUDGE_PX = 0.5;
const twipsToPx = (twips: number): number => twips / TWIPS_PER_PX;
const pxToTwips = (px: number): number => Math.round(px * TWIPS_PER_PX);
/**
* Sanitizes an indent value to ensure it's a valid non-negative finite number.
*
* Handles edge cases where indent values may be undefined, NaN, Infinity, or negative
* from malformed document data or style cascade issues. Negative values are clamped
* to 0 to prevent widening the content area beyond maxWidth.
*
* @param value - The indent value to sanitize (may be undefined, non-finite, or negative)
* @returns The original value if it's a positive finite number, otherwise 0
*/
const sanitizeIndent = (value: number | undefined): number =>
typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0;
const sanitizeRawIndent = (value: number | undefined): number =>
typeof value === 'number' && Number.isFinite(value) ? value : 0;
/**
* Sanitizes the decimal separator to ensure it's a valid value for decimal tab alignment.
*
* OOXML documents may specify locale-specific decimal separators. This function
* normalizes the value to either ',' (comma) or '.' (period, the default).
*
* @param value - The decimal separator value from document attributes
* @returns ',' if the value is a comma, otherwise '.' (default)
*/
const sanitizeDecimalSeparator = (value: unknown): string => (value === ',' ? ',' : '.');
/**
* Safely extracts the width property from a run that may have an optional width.
*
* Used for non-text runs (images, breaks) that may have pre-calculated widths.
*
* @param run - The run to extract width from
* @returns The width value if present and numeric, otherwise 0
*/
const getRunWidth = (run: Run): number => {
const width = (run as { width?: number }).width;
return typeof width === 'number' ? width : 0;
};
/**
* Checks if a break run is a line break (as opposed to page/column break).
*
* @param run - The run to check
* @returns True if the run is a line break
*/
const isLineBreakRun = (run: Run): boolean =>
run.kind === 'lineBreak' || (run.kind === 'break' && (run as { breakType?: string }).breakType === 'line');
/** True when a run is an inline image run. */
const isImageRun = (run: Run): run is ImageRun => run.kind === 'image';
/**
* Tolerance (px) for the "image fits inside the text line box" decision.
*
* MIRRORS `INLINE_IMAGE_BASELINE_TOLERANCE_PX` in `measuring/dom/src/index.ts`.
* The two live in separate packages, so the tiny predicate is duplicated rather
* than shared across a package boundary; the values MUST stay in sync (covered
* by the small-image remeasure test asserting `baseline`).
*/
const INLINE_IMAGE_BASELINE_TOLERANCE_PX = 0.5;
/** One inline-image candidate tracked on the current remeasured line. */
type RemeasureImageCandidate = {
runIndex: number;
imageWidth: number;
imageHeight: number;
hasExplicitVerticalAlign: boolean;
hasVerticalMargins: boolean;
};
const makeRemeasureImageCandidate = (
runIndex: number,
run: ImageRun,
imageWidth: number,
imageHeight: number,
): RemeasureImageCandidate => ({
runIndex,
imageWidth,
imageHeight,
hasExplicitVerticalAlign: run.verticalAlign != null,
hasVerticalMargins: (run.distTop ?? 0) !== 0 || (run.distBottom ?? 0) !== 0,
});
/**
* Resolve measured per-image baseline alignment for one remeasured line.
*
* MIRRORS `resolveInlineImageAlignments` in `measuring/dom/src/index.ts` so a
* narrower-region reflow produces the same glyph-vs-line-expanding decision as
* the initial measurement and the fix is not lost on reflowed lines.
*/
const resolveRemeasureImageAlignments = (
candidates: RemeasureImageCandidate[],
hasVisibleText: boolean,
textLineHeight: number,
): LineInlineImageAlignment[] | undefined => {
if (candidates.length === 0) return undefined;
const alignments: LineInlineImageAlignment[] = [];
for (const candidate of candidates) {
if (candidate.hasExplicitVerticalAlign) continue;
if (candidate.imageWidth <= 0) continue;
if (candidate.imageHeight <= 0) continue;
if (!hasVisibleText) continue;
if (candidate.hasVerticalMargins) continue;
if (candidate.imageHeight > textLineHeight + INLINE_IMAGE_BASELINE_TOLERANCE_PX) continue;
alignments.push({ runIndex: candidate.runIndex, verticalAlign: 'baseline' });
}
return alignments.length > 0 ? alignments : undefined;
};
/**
* Tab stop position and alignment info in pixels.
* Converted from twips for rendering calculations.
*/
type TabStopPx = {
/** Position in pixels from left margin */
pos: number;
/** Alignment type: 'start' (left), 'end' (right), 'center', or 'decimal' */
val: TabStop['val'];
/** Optional leader character style (dots, dashes, etc.) */
leader?: TabStop['leader'];
/** Whether this came from author-defined tabs or the default tab grid. */
source?: TabStop['source'];
};
type PendingTabAlignStart = {
layoutX: number;
paintX: number;
precedingTabEndX?: number;
};
/**
* Type definition for minimal marker run formatting properties.
*
* Used to generate font strings for marker text measurement. Contains only
* the essential typography properties needed for canvas measurement.
*/
type MarkerRun = {
fontFamily?: string;
fontSize?: number;
bold?: boolean;
italic?: boolean;
};
/**
* Generates a CSS font string for measuring list marker text.
*
* Similar to the main fontString() function but specialized for marker runs
* which may have incomplete formatting information. Provides sensible defaults
* for missing properties (16px Arial) to ensure measurement always succeeds.
*
* The CSS font string format is required by canvas.measureText() API:
* [style] [weight] <size> <family>
*
* @param run - Marker run with optional formatting properties (fontFamily, fontSize, bold, italic)
* @returns CSS font string suitable for CanvasRenderingContext2D.font property
*
* @example
* ```typescript
* markerFontString({ fontFamily: 'Arial', fontSize: 14, bold: true });
* // Returns: "bold 14px Arial"
*
* markerFontString({ fontSize: 18, italic: true });
* // Returns: "italic 18px Arial" (defaults to Arial)
*
* markerFontString();
* // Returns: "16px Arial" (all defaults)
* ```
*/
const markerFontString = (run?: MarkerRun): string => {
const size = run?.fontSize ?? 16;
const family = run?.fontFamily ?? 'Arial';
const italic = run?.italic ? 'italic ' : '';
const bold = run?.bold ? 'bold ' : '';
return `${italic}${bold}${size}px ${family}`.trim();
};
/**
* Build tab stop positions in pixels from OOXML tab stop specifications.
*
* Converts tab stops from TWIPS (the unit used in OOXML) to pixels and applies
* paragraph indentation rules to compute the effective tab stop positions. This
* function delegates the complex tab stop computation logic to the Engines module
* which implements the full OOXML specification including default tab intervals,
* explicit tab stops, and indent adjustments.
*
* OOXML tab stop behavior:
* - Explicit tab stops override default tab intervals
* - Default tab interval creates infinite grid of implicit tab stops
* - Paragraph indents can shift or mask tab stops in the indented region
* - Tab stops are measured from the left edge of the paragraph content area
*
* @param indent - Paragraph indentation settings (left, right, firstLine, hanging) in pixels.
* These values affect where tab stops are positioned relative to the paragraph text.
* @param tabs - Array of explicit tab stop definitions from OOXML (position in TWIPS, alignment, leader).
* Each tab stop specifies a position and optional formatting (left/right/center/decimal alignment, leader dots/dashes).
* @param tabIntervalTwips - Default tab interval in TWIPS. If not specified, uses the OOXML default of 720 TWIPS (0.5 inches).
* This creates a regular grid of implicit tab stops at this interval.
* @returns Array of tab stops with positions converted to pixels, preserving alignment and leader information.
* Each tab stop includes: pos (position in pixels), val (alignment type), and optional leader (visual character).
*
* @example
* ```typescript
* // Create tab stops with default interval and one explicit tab at 1 inch
* const tabStops = buildTabStopsPx(
* { left: 0, right: 0, firstLine: 0, hanging: 0 },
* [{ pos: 1440, val: 'left' }], // 1440 TWIPS = 1 inch
* 720 // Default interval = 0.5 inch
* );
* // Returns: [{ pos: 96, val: 'left' }, { pos: 48, val: 'left' }, ...]
* // (96px = 1 inch at 96dpi, 48px = 0.5 inch default interval)
* ```
*/
const buildTabStopsPx = (indent?: ParagraphIndent, tabs?: TabStop[], tabIntervalTwips?: number): TabStopPx[] => {
const paragraphIndentTwips = {
left: pxToTwips(sanitizeIndent(indent?.left)),
right: pxToTwips(sanitizeIndent(indent?.right)),
firstLine: pxToTwips(sanitizeIndent(indent?.firstLine)),
hanging: pxToTwips(sanitizeIndent(indent?.hanging)),
};
const rawParagraphIndentTwips = {
left: pxToTwips(sanitizeRawIndent(indent?.left)),
right: pxToTwips(sanitizeRawIndent(indent?.right)),
firstLine: pxToTwips(sanitizeRawIndent(indent?.firstLine)),
// Hanging is unsigned in OOXML; preserve negative left/right/firstLine only.
hanging: pxToTwips(sanitizeIndent(indent?.hanging)),
};
const stops = Engines.computeTabStops({
explicitStops: tabs ?? [],
defaultTabInterval: tabIntervalTwips ?? DEFAULT_TAB_INTERVAL_TWIPS,
paragraphIndent: paragraphIndentTwips,
rawParagraphIndent: rawParagraphIndentTwips,
});
return stops.map((stop: TabStop) => ({
pos: twipsToPx(stop.pos),
val: stop.val,
leader: stop.leader,
source: stop.source,
}));
};
/**
* Find the next tab stop position after the current cursor position.
*
* Implements the OOXML tab stop resolution algorithm: searches through explicit
* tab stops to find the first one that is strictly after the current X position,
* accounting for floating-point precision with a small epsilon tolerance. If all
* explicit tab stops have been exhausted, falls back to the default tab interval
* to compute an implicit tab stop position.
*
* Algorithm:
* 1. Starting from `startIndex`, iterate through `tabStops` array
* 2. Skip any tab stops that are at or before `currentX` (within epsilon tolerance)
* 3. Return the first tab stop position strictly after `currentX`
* 4. If no explicit tab stop found, add default tab interval to `currentX`
*
* The epsilon tolerance (TAB_EPSILON = 0.1px) handles floating-point rounding
* errors from text measurement and ensures consistent tab stop snapping behavior.
*
* IMPORTANT: The tabStops array must be sorted in ascending order by position.
* This requirement is enforced by buildTabStopsPx which relies on Engines.computeTabStops
* to produce correctly ordered tab stops. The algorithm assumes sorted order for
* correct tab stop selection and index advancement.
*
* @param currentX - Current horizontal cursor position in pixels (where text currently ends).
* This is the reference point from which to find the next tab stop.
* @param tabStops - Array of explicit tab stops sorted by position in ascending order.
* Pre-computed by buildTabStopsPx with positions in pixels.
* @param startIndex - Index in tabStops array to begin searching from (optimization to avoid
* re-scanning earlier tab stops). Typically incremented as tabs are consumed.
* @returns Object containing:
* - target: The X position in pixels where the tab should advance to
* - nextIndex: The array index to start searching from for the next tab (startIndex + consumed stops)
* - stop: The resolved explicit tab stop (if any) including alignment/leader metadata
*
* @example
* ```typescript
* const tabStops = [{ pos: 48, val: 'left' }, { pos: 96, val: 'left' }];
* const result = getNextTabStopPx(30, tabStops, 0);
* // Returns: { target: 48, nextIndex: 1 }
* // (next tab stop after position 30 is at 48px, search index advances to 1)
*
* const result2 = getNextTabStopPx(100, tabStops, 0);
* // Returns: { target: 148, nextIndex: 2 }
* // (no explicit tab after 100, falls back to 100 + default interval 48px)
* ```
*/
const getNextTabStopPx = (
currentX: number,
tabStops: TabStopPx[],
startIndex: number,
): { target: number; nextIndex: number; stop?: TabStopPx } => {
while (startIndex < tabStops.length && tabStops[startIndex].pos <= currentX + TAB_EPSILON) {
startIndex += 1;
}
if (startIndex < tabStops.length) {
return {
target: tabStops[startIndex].pos,
nextIndex: startIndex + 1,
stop: tabStops[startIndex],
};
}
// default tab advance if we've exhausted explicit stops
return { target: currentX + _DEFAULT_TAB_INTERVAL_PX, nextIndex: startIndex };
};
/**
* Measures the pixel width of a slice of text within a run.
*
* Uses the HTML5 Canvas API to measure text width with the same precision as browser
* text rendering. This is essential for accurate line breaking and layout calculations.
* The measurement respects all text formatting properties (font family, size, bold, italic)
* to produce pixel-accurate widths.
*
* Measurement approach:
* - Primary: Uses canvas.measureText() for browser-accurate text measurement
* - Fallback: Uses character count * 60% of font size for server-side rendering
*
* The fallback heuristic (0.6 * fontSize per character) is approximate and intended
* only for non-browser environments where canvas is unavailable. It works reasonably
* for Latin text in proportional fonts but will be less accurate for:
* - Monospace fonts (should use 1.0 * fontSize)
* - Wide characters (CJK scripts, emoji)
* - Condensed/extended font variants
*
* @param run - The run containing text and formatting properties.
* @param fromChar - Start character index (inclusive) within the run's text.
* @param toChar - End character index (exclusive) within the run's text.
* @returns Width of the text slice in pixels (floating-point precision for sub-pixel accuracy).
*/
function measureRunSliceWidth(run: Run, fromChar: number, toChar: number): number {
if (isVanishedRun(run)) return 0;
const context = getCtx();
const fullText = runText(run);
// Only TextRun and TabRun have textTransform property (via RunMarks)
const transform = isTextRun(run) ? run.textTransform : undefined;
const text = applyTextTransform(fullText.slice(fromChar, toChar), transform, fullText, fromChar);
const textRun = isTextRun(run) ? run : null;
const letterSpacing = textRun?.letterSpacing ?? 0;
const horizontalScale = runHorizontalScale(run);
if (!context) {
// Fallback: simple proportional width (approximate)
// When canvas context is unavailable (e.g., server-side rendering),
// estimate character width as 60% of font size (size * 0.6).
// This is a rough approximation based on typical proportional fonts like Arial:
// - Average character width is ~0.5-0.7x the font size
// - 0.6 is a middle ground that works reasonably for most Latin text
// - For 16px font: estimated ~9.6px per character
const size = textRun?.fontSize ?? 16;
return Math.max(1, text.length * (size * 0.6) + Math.max(0, text.length - 1) * letterSpacing) * horizontalScale;
}
const font = fontString(run);
const letterSpacingTotal = Math.max(0, text.length - 1) * letterSpacing;
if (text.length === 1) {
return (measureGlyphAdvance(context, font, text) + letterSpacingTotal) * horizontalScale;
}
return (measureSliceBaseWidth(context, font, text) + letterSpacingTotal) * horizontalScale;
}
const runHorizontalScale = (run: Run | undefined): number => {
if (!run || !('horizontalScale' in run)) return 1;
const value = run.horizontalScale;
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 1;
};
const runLetterSpacing = (run: Run | undefined): number =>
run && isTextRun(run) ? (run.letterSpacing ?? 0) * runHorizontalScale(run) : 0;
/**
* Measurement summary for an aligned tab group contained within a single line.
* Used to right/center/decimal align the grouped content to a tab stop.
*/
type TabAlignmentGroupMeasure = {
/** Total width of all content in the tab group (in pixels) */
totalWidth: number;
/** Width of content before the decimal point (for decimal alignment) */
beforeDecimalWidth?: number;
};
/**
* Scan result for an aligned tab group across runs while reflowing text.
* Provides width info plus where to resume line-breaking after the group.
*/
type TabAlignmentGroupScan = {
/** Total width of all content in the tab group (in pixels) */
totalWidth: number;
/** Width of content before the decimal point (for decimal alignment) */
beforeDecimalWidth?: number;
/** Index of the last run included in this group */
endRun: number;
/** Character offset within the last run */
endChar: number;
/** Run index to resume scanning from after this group */
resumeRun: number;
/** Character offset to resume from within the resume run */
resumeChar: number;
};
/**
* Scans forward from a run/char position until the next tab or line break to
* measure the width of the aligned tab group and capture resume positions.
*
* This function is used during line breaking to handle right, center, and decimal
* tab alignments. It scans ahead to find all content that belongs to the tab group
* (everything between this tab and the next tab or line break) and measures its
* total width.
*
* For decimal tabs, it also tracks the position of the decimal separator to enable
* alignment on that character.
*
* @param runs - Array of runs in the paragraph
* @param startRunIndex - Index of the run to start scanning from
* @param startChar - Character offset within the starting run
* @param decimalSeparator - The decimal separator character ('.' or ',')
* @returns Scan result with width measurements and resume positions
*/
const scanTabAlignmentGroup = (
runs: Run[],
startRunIndex: number,
startChar: number,
decimalSeparator: string,
): TabAlignmentGroupScan => {
let totalWidth = 0;
let beforeDecimalWidth: number | undefined;
let foundDecimal = false;
let endRun = startRunIndex;
let endChar = startChar;
for (let r = startRunIndex; r < runs.length; r += 1) {
const run = runs[r];
if (!run) continue;
if (isVanishedRun(run)) continue;
if (run.kind === 'tab') {
return { totalWidth, beforeDecimalWidth, endRun, endChar, resumeRun: r, resumeChar: 0 };
}
if (isLineBreakRun(run)) {
return { totalWidth, beforeDecimalWidth, endRun, endChar, resumeRun: r, resumeChar: 0 };
}
const text = runText(run);
if (!text) {
const runWidth = getRunWidth(run);
if (runWidth > 0) {
totalWidth += runWidth;
endRun = r;
endChar = 1;
}
continue;
}
const sliceStart = r === startRunIndex ? startChar : 0;
if (sliceStart >= text.length) continue;
const tabIndex = text.indexOf('\t', sliceStart);
const effectiveEnd = tabIndex >= 0 ? tabIndex : text.length;
if (effectiveEnd > sliceStart) {
const sliceWidth = measureRunSliceWidth(run, sliceStart, effectiveEnd);
if (!foundDecimal) {
const decimalIndex = text.slice(sliceStart, effectiveEnd).indexOf(decimalSeparator);
if (decimalIndex >= 0) {
foundDecimal = true;
const beforeWidth = decimalIndex > 0 ? measureRunSliceWidth(run, sliceStart, sliceStart + decimalIndex) : 0;
beforeDecimalWidth = totalWidth + beforeWidth;
}
}
totalWidth += sliceWidth;
endRun = r;
endChar = effectiveEnd;
}
if (tabIndex >= 0) {
return { totalWidth, beforeDecimalWidth, endRun, endChar, resumeRun: r, resumeChar: tabIndex };
}
}
return { totalWidth, beforeDecimalWidth, endRun, endChar, resumeRun: runs.length, resumeChar: 0 };
};
/**
* Measures the width of the aligned tab group within the current line bounds.
*
* Similar to scanTabAlignmentGroup, but constrained to content that has already
* been placed on a specific line. Used during the tab layout pass to calculate
* positioning for right, center, and decimal aligned tabs.
*
* @param runs - Array of runs in the paragraph
* @param line - The line containing the tab group
* @param startRunIndex - Index of the run to start measuring from
* @param startChar - Character offset within the starting run
* @param decimalSeparator - The decimal separator character ('.' or ',')
* @returns Measurement result with total and before-decimal widths
*/
const measureTabAlignmentGroupInLine = (
runs: Run[],
line: Line,
startRunIndex: number,
startChar: number,
decimalSeparator: string,
): TabAlignmentGroupMeasure => {
let totalWidth = 0;
let beforeDecimalWidth: number | undefined;
let foundDecimal = false;
for (let r = startRunIndex; r <= line.toRun; r += 1) {
const run = runs[r];
if (!run) continue;
if (isVanishedRun(run)) continue;
if (run.kind === 'tab') break;
if (isLineBreakRun(run)) break;
const text = runText(run);
if (!text) {
totalWidth += getRunWidth(run);
continue;
}
const sliceStart = r === startRunIndex ? startChar : 0;
const sliceEnd = r === line.toRun ? line.toChar : text.length;
if (sliceStart >= sliceEnd) continue;
const slice = text.slice(sliceStart, sliceEnd);
const tabIndex = slice.indexOf('\t');
const effectiveSlice = tabIndex >= 0 ? slice.slice(0, tabIndex) : slice;
const effectiveSliceEnd = tabIndex >= 0 ? sliceStart + tabIndex : sliceEnd;
if (effectiveSlice.length > 0) {
const sliceWidth = measureRunSliceWidth(run, sliceStart, effectiveSliceEnd);
totalWidth += sliceWidth;
if (!foundDecimal) {
const decimalIndex = effectiveSlice.indexOf(decimalSeparator);
if (decimalIndex >= 0) {
foundDecimal = true;
const beforeWidth = decimalIndex > 0 ? measureRunSliceWidth(run, sliceStart, sliceStart + decimalIndex) : 0;
beforeDecimalWidth = totalWidth - sliceWidth + beforeWidth;
}
}
}
if (tabIndex >= 0) {
break;
}
}
return { totalWidth, beforeDecimalWidth };
};
/**
* Applies tab stop layout to all lines, calculating segment positions and tab leaders.
*
* This is a post-processing pass that runs after initial line breaking. It handles:
* - Right-aligned tabs: Content is positioned to end at the tab stop
* - Center-aligned tabs: Content is centered on the tab stop
* - Decimal-aligned tabs: Content is aligned on the decimal separator
* - Tab leaders: Fills the space before aligned content with dots, dashes, etc.
*
* The function mutates the line objects to add:
* - `segments`: Array of positioned text segments with explicit x coordinates