@@ -5,31 +5,40 @@ const FontSizer = ({
5
5
Component = "div" ,
6
6
maxHeight = 100 ,
7
7
maxWidth = 100 ,
8
- maxFontSize = 500 ,
8
+ maxFontSize = 50 ,
9
9
minFontSize = 10 ,
10
10
cacheKey,
11
11
...rest
12
12
} ) => {
13
13
const [ ref , setRef ] = useState ( )
14
+ const cancelRef = useRef ( false )
14
15
15
16
useEffect ( ( ) => {
16
17
if ( ! ref ) return
17
18
18
- requestAnimationFrame ( ( ) => {
19
+ const timeoutId = setTimeout ( ( ) => {
20
+ cancelRef . current = false
19
21
let fontSize = maxFontSize
20
22
21
23
ref . style . animation = "font-size 02s"
22
24
ref . style . fontSize = fontSize + "px"
23
25
24
- const widthScale = maxWidth / ref . offsetWidth
25
- const heightScale = maxHeight / ref . offsetHeight
26
-
27
- const scaleFactor = Math . min ( widthScale , heightScale )
28
- fontSize = Math . floor ( maxFontSize * scaleFactor ) || 1
29
-
30
- ref . style . fontSize = fontSize + "px"
26
+ while (
27
+ ! cancelRef . current &&
28
+ fontSize > minFontSize &&
29
+ ( ref . offsetWidth > maxWidth || ref . offsetHeight > maxHeight )
30
+ ) {
31
+ const delta = Math . ceil ( fontSize / 100 )
32
+ fontSize = fontSize - delta
33
+ ref . style . fontSize = fontSize + "px"
34
+ }
31
35
} )
32
- } , [ children , maxHeight , maxWidth , ref , cacheKey ] )
36
+
37
+ return ( ) => {
38
+ cancelRef . current = true
39
+ clearTimeout ( timeoutId )
40
+ }
41
+ } , [ children , maxHeight , maxWidth , ref ] )
33
42
34
43
return (
35
44
< Component truncate ref = { setRef } { ...rest } >
0 commit comments