File size: 1,257 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
import { useEffect } from "react"

type ScrollAlignment = "nearest" | "center"

export function useScrollIntoView(
  containerRef: React.RefObject<HTMLElement>,
  itemSelector: string,
  alignment: ScrollAlignment = "nearest",
) {
  useEffect(() => {
    const container = containerRef.current
    const item = container?.querySelector(itemSelector)

    if (!container || !item) return

    const isInView = () => {
      const containerRect = container.getBoundingClientRect()
      const itemRect = item.getBoundingClientRect()

      return (
        itemRect.top >= containerRect.top &&
        itemRect.bottom <= containerRect.bottom
      )
    }

    if (!isInView()) {
      const containerRect = container.getBoundingClientRect()
      const itemRect = item.getBoundingClientRect()

      const scrollTop = container.scrollTop
      const itemTop = itemRect.top - containerRect.top + scrollTop

      let targetScrollTop = itemTop
      if (alignment === "center") {
        const containerHeight = container.clientHeight
        const itemHeight = item.clientHeight
        targetScrollTop = itemTop - containerHeight / 2 + itemHeight / 2
      }

      container.scrollTop = targetScrollTop
    }
  }, [containerRef, itemSelector, alignment])
}