66 * Side Public License, v 1.
77 */
88
9- import React , { useRef , useEffect , useState , ComponentType } from 'react' ;
9+ import React , { useRef , useEffect , useState , ComponentType , useMemo } from 'react' ;
1010import { throttle } from 'lodash' ;
1111import { useResizeObserver } from '@elastic/eui' ;
1212import { autoScaleWrapperStyle } from './auto_scale.styles' ;
@@ -41,29 +41,36 @@ export function computeScale(
4141 return Math . max ( Math . min ( MAX_SCALE , Math . min ( scaleX , scaleY ) ) , minScale ) ;
4242}
4343
44- export const withAutoScale =
45- ( autoScaleParams ?: AutoScaleParams ) => ( WrappedComponent : ComponentType < any > ) => ( props : any ) => {
44+ export function withAutoScale < T > (
45+ WrappedComponent : ComponentType < T > ,
46+ autoScaleParams ?: AutoScaleParams
47+ ) {
48+ return ( props : T ) => {
4649 const [ scale , setScale ] = useState ( 0 ) ;
4750 const parentRef = useRef < HTMLDivElement > ( null ) ;
4851 const childrenRef = useRef < HTMLDivElement > ( null ) ;
4952 const parentDimensions = useResizeObserver ( parentRef . current ) ;
5053
51- const scaleFn = throttle ( ( ) => {
52- const newScale = computeScale (
53- { clientHeight : parentDimensions . height , clientWidth : parentDimensions . width } ,
54- childrenRef . current ,
55- autoScaleParams ?. minScale
56- ) ;
54+ const scaleFn = useMemo (
55+ ( ) =>
56+ throttle ( ( ) => {
57+ const newScale = computeScale (
58+ { clientHeight : parentDimensions . height , clientWidth : parentDimensions . width } ,
59+ childrenRef . current ,
60+ autoScaleParams ?. minScale
61+ ) ;
5762
58- // Prevent an infinite render loop
59- if ( scale !== newScale ) {
60- setScale ( newScale ) ;
61- }
62- } ) ;
63+ // Prevent an infinite render loop
64+ if ( scale !== newScale ) {
65+ setScale ( newScale ) ;
66+ }
67+ } ) ,
68+ [ parentDimensions , setScale , scale , childrenRef ]
69+ ) ;
6370
6471 useEffect ( ( ) => {
6572 scaleFn ( ) ;
66- } , [ parentDimensions ] ) ;
73+ } , [ scaleFn ] ) ;
6774
6875 return (
6976 < div ref = { parentRef } css = { autoScaleWrapperStyle } >
@@ -78,3 +85,4 @@ export const withAutoScale =
7885 </ div >
7986 ) ;
8087 } ;
88+ }
0 commit comments