|
| 1 | +import { useMotionValueEvent, useScroll } from 'motion/react'; |
| 2 | +import { ReactNode, useEffect, useRef, useState } from 'react'; |
| 3 | +import styled, { css } from 'styled-components'; |
| 4 | + |
| 5 | +type Props = { |
| 6 | + children: ReactNode, |
| 7 | + className?: string, |
| 8 | +}; |
| 9 | + |
| 10 | +const ScrollShadow = ({ children, className }: Props) => { |
| 11 | + const ref = useRef<HTMLDivElement | null>(null); |
| 12 | + const { scrollY } = useScroll({ container: ref }); |
| 13 | + const [isScrolledTop, setIsScrolledTop] = useState(false); |
| 14 | + const [isScrolledBottom, setIsScrolledBottom] = useState(false); |
| 15 | + |
| 16 | + const updateScrollState = () => { |
| 17 | + const el = ref.current; |
| 18 | + if (!el) return; |
| 19 | + |
| 20 | + const { clientHeight, scrollHeight, scrollTop } = el; |
| 21 | + |
| 22 | + setIsScrolledTop(scrollTop > 0); |
| 23 | + setIsScrolledBottom(scrollHeight > clientHeight && scrollTop < (scrollHeight - clientHeight)); |
| 24 | + }; |
| 25 | + |
| 26 | + useEffect(() => { |
| 27 | + updateScrollState(); |
| 28 | + }, []); |
| 29 | + |
| 30 | + useMotionValueEvent(scrollY, 'change', updateScrollState); |
| 31 | + |
| 32 | + return ( |
| 33 | + <Container |
| 34 | + $isScrolledTop={isScrolledTop} |
| 35 | + $isScrolledBottom={isScrolledBottom} |
| 36 | + ref={ref} |
| 37 | + className={className} |
| 38 | + > |
| 39 | + {children} |
| 40 | + </Container> |
| 41 | + ); |
| 42 | +}; |
| 43 | + |
| 44 | +export default ScrollShadow; |
| 45 | + |
| 46 | +const Container = styled.div<{ $isScrolledTop: boolean, $isScrolledBottom: boolean }>` |
| 47 | + width: min(100vw, 440px); |
| 48 | + overflow-y: auto; |
| 49 | +
|
| 50 | + mask-composite: intersect; |
| 51 | +
|
| 52 | + ${({ $isScrolledTop, $isScrolledBottom }) => { |
| 53 | + if ($isScrolledTop && $isScrolledBottom) { |
| 54 | + return css` |
| 55 | + mask-image: linear-gradient(to bottom, transparent, black 40px), |
| 56 | + linear-gradient(to top, transparent, black 40px); |
| 57 | + `; |
| 58 | + } else if ($isScrolledTop) { |
| 59 | + return css` |
| 60 | + mask-image: linear-gradient(to bottom, transparent, black 40px); |
| 61 | + `; |
| 62 | + } else if ($isScrolledBottom) { |
| 63 | + return css` |
| 64 | + mask-image: linear-gradient(to top, transparent, black 40px); |
| 65 | + `; |
| 66 | + } |
| 67 | + }} |
| 68 | +`; |
0 commit comments