All files Carousel.js

100% Statements 80/80
95.24% Branches 40/42
100% Functions 29/29
100% Lines 80/80
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260      1x       16x 16x   28x 21x     21x 16x 2x 2x   2x                   2x 2x       16x 2x 2x 1x 1x     16x 2x 2x 1x 1x         16x                               16x 16x 8x         16x         13x 13x 13x     13x   13x 13x         11x 11x 1x 1x         11x 1x   10x 1x   9x 8x   1x       11x 11x 11x         9x 9x 9x             9x 9x           9x           9x             28x 28x 60x 47x       47x 47x   13x         29x   29x 2x                       27x               1x               1x                             1x 47x     47x 26x 2x   24x   21x           1x           1x                       1x 5x     11x           1x            
import React from 'react';
import PropTypes from 'prop-types';
 
const Context = React.createContext();
 
class Carousel extends React.Component {
    constructor (props) {
        super(props);
        const slideCount = React.Children
            .map(props.children, (C, i) => {
                if (C.type === Slide) {
                    return React.cloneElement(C, {key: i, index: i});
                }
            })
            .filter(C => React.isValidElement(C)).length;
        const setActiveSlideIndex = index => {
            this.intervalId = clearInterval(this.intervalId);
            this.internalSetState(
                prevState => {
                    return {
                        activeSlideIndex: this.getNextSlideIndex(
                            index,
                            prevState.activeSlideIndex,
                            slideCount,
                            props.loop,
                        ),
                    };
                },
                () => {
                    this.initInterval();
                    this.onSlideChange();
                },
            );
        };
        const stop = () => {
            const {isPlaying} = this.state;
            if (isPlaying) {
                this.intervalId = clearInterval(this.intervalId);
                this.internalSetState({isPlaying: false});
            }
        };
        const play = () => {
            const {isPlaying} = this.state;
            if (!isPlaying) {
                this.internalSetState({isPlaying: true}, () => {
                    this.initInterval();
                });
            }
        };
 
        this.state = {
            slideCount,
            setActiveSlideIndex,
            stop,
            play,
            isPlaying: props.autoplay,
            autoplay: props.autoplay,
            interval: props.interval,
            direction: props.direction,
            loop: props.loop,
            onSlideChange: props.onSlideChange,
            activeSlideIndex: 0,
        };
    }
 
    componentDidMount () {
        const {autoplay, slideCount} = this.state;
        if (autoplay && slideCount >= 2) {
            this.initInterval();
        }
    }
 
    componentWillUnmount () {
        this.intervalId = clearInterval(this.intervalId);
    }
 
    // God bless Kent C. Dodds
    internalSetState (changes, callback) {
        this.setState((state, props) => {
            const stateToSet = [changes]
                .map(c => (typeof c === 'function' ? c(state, props) : c))
                .map(
                    c =>
                        props.stateReducer ? props.stateReducer(state, c) : c,
                )
                .map(({type: ignoredType, ...c}) => c)[0];
            return stateToSet;
        }, callback);
    }
 
    onSlideChange = () => {
        const {onSlideChange} = this.state;
        if (onSlideChange) {
            const {activeSlideIndex} = this.state;
            onSlideChange(activeSlideIndex);
        }
    };
    // Sorry, I'm bad at computer science, Ryan
    getNextSlideIndex = (index, prevIndex, slideCount, loop) => {
        if (index > slideCount - 1 && loop) {
            return 0;
        }
        if (index < 0) {
            return slideCount - 1;
        }
        if (index >= 0 && index < slideCount) {
            return index;
        }
        return prevIndex;
    };
 
    initInterval = () => {
        const {interval} = this.state;
        Eif (!this.intervalId) {
            this.intervalId = setInterval(this.goToNextSlide, interval);
        }
    };
 
    goToNextSlide = () => {
        const {isPlaying} = this.state;
        Eif (isPlaying) {
            this.internalSetState(
                prevState => {
                    const {
                        slideCount,
                        activeSlideIndex,
                        direction,
                        loop,
                    } = this.state;
                    const nextIndex = this.getNextSlideIndex(
                        activeSlideIndex + direction,
                        prevState.activeSlideIndex,
                        slideCount,
                        loop,
                    );
                    return {
                        activeSlideIndex: nextIndex,
                        isPlaying: nextIndex !== prevState.activeSlideIndex,
                    };
                },
                () => {
                    this.onSlideChange();
                },
            );
        }
    };
 
    renderChildren = children => {
        let slideIndex = 0;
        return React.Children.map(children, (C, i) => {
            if (C.type === Slide) {
                const clone = React.cloneElement(C, {
                    key: i,
                    index: slideIndex,
                });
                slideIndex += 1;
                return clone;
            }
            return C;
        });
    };
 
    render () {
        const {children, as: Component, ...props} = this.props;
 
        if (Component) {
            return (
                <Context.Provider value={this.state}>
                    <Component {...props}>
                        {typeof children === 'function' ? (
                            children
                        ) : (
                            this.renderChildren(children)
                        )}
                    </Component>
                </Context.Provider>
            );
        }
        return (
            <Context.Provider value={this.state}>
                {this.renderChildren(children)}
            </Context.Provider>
        );
    }
}
 
Carousel.defaultProps = {
    autoplay: true,
    interval: 2500,
    direction: 1,
    loop: true,
    onSlideChange: null,
};
 
Carousel.propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.element,
        PropTypes.arrayOf(
            PropTypes.oneOfType([PropTypes.element, PropTypes.array]),
        ),
        PropTypes.func,
    ]).isRequired,
    autoplay: PropTypes.bool,
    interval: PropTypes.number,
    direction: PropTypes.number,
    loop: PropTypes.bool,
    onSlideChange: PropTypes.func,
};
 
const Slide = ({index, children, as: Component, preventUnmount, ...props}) => {
    return (
        <Context.Consumer>
            {({activeSlideIndex}) => {
                if (index === activeSlideIndex || preventUnmount) {
                    if (Component) {
                        return <Component {...props}>{children}</Component>;
                    }
                    return children;
                }
                return null;
            }}
        </Context.Consumer>
    );
};
 
Slide.defaultProps = {
    index: undefined,
    as: undefined,
    preventUnmount: false,
};
 
Slide.propTypes = {
    children: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
        .isRequired,
    index: PropTypes.number,
    as: PropTypes.oneOfType([
        PropTypes.element,
        PropTypes.func,
        PropTypes.string,
    ]),
    preventUnmount: PropTypes.bool,
};
 
const Control = ({children}) => {
    return (
        <Context.Consumer>
            {props => {
                return children({...props});
            }}
        </Context.Consumer>
    );
};
 
Control.propTypes = {
    children: PropTypes.func.isRequired,
};
 
export default Carousel;
export {Slide, Control};