all files / src/ anchor.js

93.57% Statements 160/171
95.24% Branches 80/84
100% Functions 34/34
64.52% Lines 20/31
40 statements, 12 functions, 38 branches Ignored     
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                                                                                                                           
/**
 * Exports a helper function which wraps clickable elements, hijacking onClick and passing it to the scroller
 */
import React, { PropTypes as PT } from 'react';
import ReactDOM from 'react-dom';
import scroller from './scroller';
import ScrollSpy from './scroll-spy';
 
function handleClick(onClick, href, event) {
    event.stopPropagation();
    event.preventDefault();
 
    Iif (onClick) {
        onClick(event);
    }
 
    scroller.prepareToScroll(href);
}
 
function anchor(Component) {
    class AnchorComponent extends React.Component {
        constructor(props) {
            super(props);
 
            this._handleScroll = this._handleScroll.bind(this);
        }
 
        componentDidMount() {
            ScrollSpy.registerLink(this);
        }
 
        componentWillUnmount() {
            ScrollSpy.unregisterLink(this);
        }
 
        _handleScroll(scrollOffset, container, { panel, panelComp }) {
            const link = ReactDOM.findDOMNode(this);
            const cords = panel.getBoundingClientRect();
            const containeRect = container.getBoundingClientRect();
 
            let elemTopBound = 0;
            if (container === document.body) {
                elemTopBound = cords.top - containeRect.top - 64;
            } else {
                elemTopBound = cords.top + scrollOffset - containeRect.top - 64;
            }
            const elemBottomBound = elemTopBound + cords.height;
 
            return {
                link,
                activeClass: this.props.activeClass,
                hasActive: link.classList.contains(this.props.activeClass),
                isInside: panelComp.props.isInside(scrollOffset, elemTopBound, elemBottomBound, cords, containeRect)
            };
        }
 
        render() {
            const { onClick, ...props } = this.props; // eslint-disable-line no-use-before-define
            const restProps = {
                ...props,
                onClick: handleClick.bind(this, onClick, props.href)
            };
            return <Component {...restProps} />;
        }
    }
 
    AnchorComponent.displayName = `AnchorComponent(${Component.displayName || Component.name})`;
    AnchorComponent.propTypes = {
        href: PT.string.isRequired,
        onClick: PT.func,
        activeClass: PT.string
    };
    AnchorComponent.defaultProps = {
        activeClass: 'scroll-spy-active'
    };
 
    return AnchorComponent;
}
 
export default anchor;