1- import React from 'react' ;
1+ import React , { useState , useMemo } from 'react' ;
22import useIntersectionObserver from './useIntersectionObserver' ;
33
44const useRootMargin = offset => {
55 return `-${ offset * 100 } % 0px -${ 100 - offset * 100 } % 0px` ;
66}
77
8- const useProgressRootMargin = ( direction , offset ) => {
9- if ( direction === 'down' ) return `${ offset * 100 } % 0px -${ 100 - offset * 100 } % 0px`
10- return `-${ offset * 100 } % 0px ${ offset * 100 } % 0px` ;
8+ const useProgressRootMargin = ( direction , offset , node , innerHeight ) => {
9+ if ( ! node ) return '0px' ;
10+ const offsetHeight = ( node . offsetHeight / innerHeight ) ;
11+ if ( direction === 'down' ) return `${ ( offsetHeight - offset ) * 100 } % 0px ${ ( offset * 100 ) - 100 } % 0px` ;
12+ return `-${ offset * 100 } % 0px ${ ( offsetHeight * 100 ) - ( 100 - ( offset * 100 ) ) } % 0px` ;
1113}
1214
1315const Step = props => {
@@ -22,23 +24,28 @@ const Step = props => {
2224 offset,
2325 scrollamaId,
2426 progressThreshold,
27+ innerHeight,
2528 } = props ;
2629
2730 const scrollTop = document . documentElement . scrollTop ;
2831 const direction = lastScrollTop < scrollTop ? 'down' : 'up' ;
2932
30- const progressRootMargin = useProgressRootMargin ( direction , offset ) ;
3133 const rootMargin = useRootMargin ( offset ) ;
3234
33- const [ node , setNode ] = React . useState ( null ) ;
34- const [ isIntersecting , setIsIntersecting ] = React . useState ( false ) ;
35+ const [ node , setNode ] = useState ( null ) ;
36+ const [ isIntersecting , setIsIntersecting ] = useState ( false ) ;
3537
3638 const [ entry ] = useIntersectionObserver ( {
3739 rootMargin,
3840 threshold : 0 ,
3941 nodeRef : node ,
4042 } ) ;
4143
44+ const progressRootMargin = useMemo (
45+ ( ) => useProgressRootMargin ( direction , offset , node , innerHeight ) ,
46+ [ direction , offset , node , innerHeight ]
47+ ) ;
48+
4249 const [ scrollProgressEntry ] = useIntersectionObserver ( {
4350 rootMargin : progressRootMargin ,
4451 threshold : progressThreshold ,
@@ -50,7 +57,6 @@ const Step = props => {
5057 if ( isIntersecting ) {
5158 const { height, top } = scrollProgressEntry . target . getBoundingClientRect ( ) ;
5259 const progress = Math . min ( 1 , Math . max ( 0 , ( window . innerHeight * offset - top ) / height ) ) ;
53-
5460 onStepProgress &&
5561 onStepProgress ( {
5662 progress,
0 commit comments