File size: 2,244 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { MutableRefObject } from 'react'
import { each, onScroll, useIsomorphicLayoutEffect } from '@react-spring/shared'

import { SpringProps, SpringValues } from '../types'

import { useSpring } from './useSpring'

export interface UseScrollOptions extends Omit<SpringProps, 'to' | 'from'> {
  container?: MutableRefObject<HTMLElement>
}

/**
 * A small utility abstraction around our signature useSpring hook. It's a great way to create
 * a scroll-linked animation. With either the raw value of distance or a 0-1 progress value.
 * You can either use the scroll values of the whole document, or just a specific element.
 *
 * 
 ```jsx
    import { useScroll, animated } from '@react-spring/web'

    function MyComponent() {
      const { scrollYProgress } = useScroll()

      return (
        <animated.div style={{ opacity: scrollYProgress }}>
          Hello World
        </animated.div>
      )
    }
  ```
 * 
 * @param {UseScrollOptions} useScrollOptions options for the useScroll hook.
 * @param {MutableRefObject<HTMLElement>} useScrollOptions.container the container to listen to scroll events on, defaults to the window.
 *
 * @returns {SpringValues<{scrollX: number; scrollY: number; scrollXProgress: number; scrollYProgress: number}>} SpringValues the collection of values returned from the inner hook
 */
export const useScroll = ({
  container,
  ...springOptions
}: UseScrollOptions = {}): SpringValues<{
  scrollX: number
  scrollY: number
  scrollXProgress: number
  scrollYProgress: number
}> => {
  const [scrollValues, api] = useSpring(
    () => ({
      scrollX: 0,
      scrollY: 0,
      scrollXProgress: 0,
      scrollYProgress: 0,
      ...springOptions,
    }),
    []
  )

  useIsomorphicLayoutEffect(() => {
    const cleanupScroll = onScroll(
      ({ x, y }) => {
        api.start({
          scrollX: x.current,
          scrollXProgress: x.progress,
          scrollY: y.current,
          scrollYProgress: y.progress,
        })
      },
      { container: container?.current || undefined }
    )

    return () => {
      /**
       * Stop the springs on unmount.
       */
      each(Object.values(scrollValues), value => value.stop())

      cleanupScroll()
    }
  }, [])

  return scrollValues
}