|
| 1 | +import * as React from 'react' |
| 2 | +import { Icon } from '@alifd/next' |
| 3 | + |
| 4 | +const styles = { |
| 5 | + scrollIndicator: { |
| 6 | + position: 'fixed' as 'fixed', |
| 7 | + display: 'flex' as 'flex', |
| 8 | + justifyContent: 'center' as 'center', |
| 9 | + alignItems: 'center' as 'center', |
| 10 | + left: 'calc(50% - 8px)', |
| 11 | + borderRadius: '100%', |
| 12 | + zIndex: 100, |
| 13 | + bottom: '2.2rem', |
| 14 | + boxShadow: '0 0 0 5px transparent', |
| 15 | + }, |
| 16 | +} |
| 17 | + |
| 18 | +type Props = { |
| 19 | + item: string |
| 20 | + children: React.ReactElement |
| 21 | +} |
| 22 | + |
| 23 | +const ScrollContent = ({ item, children }: Props) => { |
| 24 | + const [showScrollIndicator, setShowScrollIndicator] = React.useState<'UNDETERMINED' | 'SHOW' | 'HIDE'>('UNDETERMINED') |
| 25 | + const pageTopRef: React.RefObject<any> = React.useRef(null) |
| 26 | + const pageBottomRef: React.RefObject<any> = React.useRef(null) |
| 27 | + |
| 28 | + const scrollToTop = () => { |
| 29 | + pageTopRef.current.scrollIntoView({ behavior: 'smooth' }) |
| 30 | + let hideTimeout: any |
| 31 | + |
| 32 | + // API to detect if an HTML element is in the viewport |
| 33 | + // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API |
| 34 | + const observer = new IntersectionObserver( |
| 35 | + ([entry]) => { |
| 36 | + // show a scroll indicator to let the user know |
| 37 | + // they can scroll down for more |
| 38 | + const isVisible = entry.isIntersecting |
| 39 | + if (!isVisible && showScrollIndicator === 'UNDETERMINED') { |
| 40 | + setShowScrollIndicator('SHOW') |
| 41 | + } |
| 42 | + hideTimeout = setTimeout(() => { |
| 43 | + setShowScrollIndicator('HIDE') |
| 44 | + observer.unobserve(pageBottomRef.current) |
| 45 | + }, 2000) |
| 46 | + }, |
| 47 | + { rootMargin: '0px' }, |
| 48 | + ) |
| 49 | + |
| 50 | + const showTimeout = setTimeout(() => { |
| 51 | + // detect if bottom of page is visible |
| 52 | + |
| 53 | + if (pageBottomRef.current) { |
| 54 | + observer.observe(pageBottomRef.current) |
| 55 | + } |
| 56 | + }, 600) |
| 57 | + return () => { |
| 58 | + // cleanup timeouts & subs |
| 59 | + observer.unobserve(pageBottomRef.current) |
| 60 | + clearTimeout(showTimeout) |
| 61 | + clearTimeout(hideTimeout) |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + React.useEffect(scrollToTop, [item]) |
| 66 | + |
| 67 | + return ( |
| 68 | + <div css={{ position: 'relative' }}> |
| 69 | + <div ref={pageTopRef} /> |
| 70 | + {children} |
| 71 | + {showScrollIndicator === 'SHOW' ? ( |
| 72 | + <div style={styles.scrollIndicator}> |
| 73 | + <Icon type="arrow-down" size="small" /> |
| 74 | + </div> |
| 75 | + ) : null} |
| 76 | + <div ref={pageBottomRef} /> |
| 77 | + </div> |
| 78 | + ) |
| 79 | +} |
| 80 | + |
| 81 | +export default ScrollContent |
0 commit comments