|
| 1 | +import { createElement, createRef, PureComponent } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'; |
| 4 | + |
| 5 | +export default class ScrollIntoViewIfNeeded extends PureComponent { |
| 6 | + static propTypes = { |
| 7 | + active: PropTypes.bool, |
| 8 | + children: PropTypes.node.isRequired, |
| 9 | + elementType: PropTypes.string, |
| 10 | + options: PropTypes.shape({ |
| 11 | + boundary: PropTypes.node, |
| 12 | + centerIfNeeded: PropTypes.bool, |
| 13 | + duration: PropTypes.number, |
| 14 | + easing: PropTypes.oneOf([ |
| 15 | + 'ease', |
| 16 | + 'easeIn', |
| 17 | + 'easeOut', |
| 18 | + 'easeInOut', |
| 19 | + 'linear', |
| 20 | + ]), |
| 21 | + offset: PropTypes.shape(), |
| 22 | + top: PropTypes.number, |
| 23 | + right: PropTypes.number, |
| 24 | + bottom: PropTypes.number, |
| 25 | + left: PropTypes.number, |
| 26 | + }), |
| 27 | + }; |
| 28 | + |
| 29 | + static defaultProps = { |
| 30 | + active: true, |
| 31 | + elementType: 'div', |
| 32 | + options: { |
| 33 | + duration: 250, |
| 34 | + easing: 'easeOut', |
| 35 | + }, |
| 36 | + }; |
| 37 | + |
| 38 | + constructor(props) { |
| 39 | + super(props); |
| 40 | + this.node = createRef(); |
| 41 | + } |
| 42 | + |
| 43 | + componentDidMount() { |
| 44 | + const { active } = this.props; |
| 45 | + if (active) { |
| 46 | + this.handleScrollIntoViewIfNeeded(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + componentDidUpdate({ active }) { |
| 51 | + const { active: isNowActive } = this.props; |
| 52 | + if (!active && isNowActive) { |
| 53 | + this.handleScrollIntoViewIfNeeded(); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + handleScrollIntoViewIfNeeded = () => { |
| 58 | + const { options } = this.props; |
| 59 | + const { current: node } = this.node; |
| 60 | + scrollIntoViewIfNeeded(node, options); |
| 61 | + }; |
| 62 | + |
| 63 | + render() { |
| 64 | + const { elementType, children } = this.props; |
| 65 | + return createElement(elementType, { ref: this.node, ...this.props }, children); |
| 66 | + } |
| 67 | +} |
0 commit comments