@@ -41,27 +41,39 @@ const computeFontSize = (
41
41
while ( fontSize < MAX_FONT_SIZE ) {
42
42
let linesUsed = 0 ;
43
43
44
- for ( let idx = 0 , len = lines . length ; idx < len ; idx ++ ) {
45
- const line = lines [ idx ] ;
44
+ for (
45
+ let lineIdx = 0 , lineLen = lines . length ;
46
+ lineIdx < lineLen ;
47
+ lineIdx ++
48
+ ) {
49
+ linesUsed += 1 ;
50
+
51
+ const line = lines [ lineIdx ] ;
52
+ const words = line . split ( ' ' ) ;
53
+
54
+ // Layout the words using the current `fontSize`, line wrapping
55
+ // whenever we reach the end of the current line.
46
56
let spaceInLineRemaining = bounds . width ;
47
- linesUsed += line . split ( ' ' ) . reduce ( ( used , word , i , words ) => {
48
- word = i === words . length - 1 ? word : word + ' ' ;
57
+ for ( let idx = 0 , len = words . length ; idx < len ; idx ++ ) {
58
+ const isLastWord = idx === len - 1 ;
59
+ const word = isLastWord ? words [ idx ] : words [ idx ] + ' ' ;
49
60
const widthOfWord = font . widthOfTextAtSize ( word , fontSize ) ;
50
61
spaceInLineRemaining -= widthOfWord ;
51
62
if ( spaceInLineRemaining <= 0 ) {
52
- used ++ ;
63
+ linesUsed += 1 ;
53
64
spaceInLineRemaining = bounds . width - widthOfWord ;
54
65
}
55
- return used ;
56
- } , 1 ) ;
66
+ }
57
67
}
58
68
69
+ // Return if we exceeded the allowed width
59
70
if ( ! multiline && linesUsed > lines . length ) return fontSize - 1 ;
60
71
61
72
const height = font . heightAtSize ( fontSize ) ;
62
73
const lineHeight = height + height * 0.2 ;
63
74
const totalHeight = lineHeight * linesUsed ;
64
75
76
+ // Return if we exceeded the allowed height
65
77
if ( totalHeight > Math . abs ( bounds . height ) ) return fontSize - 1 ;
66
78
67
79
fontSize += 1 ;
0 commit comments