All files / src/utils ScreenClassProvider.jsx

100% Statements 16/16
100% Branches 2/2
100% Functions 5/5
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                252x   252x                   252x         252x                 2667x   2667x                 2667x                 2415x                   8630x 8630x 8630x   8630x 7390x                     10057x 10057x   10057x                    
import React, {Component} from 'react';
 
import {autobind} from 'core-decorators';
import PropTypes from 'prop-types';
import {withTheme} from 'styled-components';
 
import {getScreenClass} from './lib';
 
const defaultData = 'xxl';
 
export const ScreenClassContext = React.createContext(defaultData);
 
/**
 * ScreenClassProvider class.
 *
 * @component
 * @augments {Component<Props, State>}
 * @extends {Component}
 */
class ScreenClassProvider extends Component {
    static propTypes = {
        children: PropTypes.node.isRequired,
        theme: PropTypes.object.isRequired
    }
 
    static defaultProps = {}
 
    /**
     * Creates an instance of ScreenClassProvider.
     *
     * @param {Object} props Component props.
     * @memberof ScreenClassProvider
     */
    constructor(props) {
        super(props);
 
        this.state = {screenClass: 'xxl'};
    }
 
    /**
     * Adds the resize handler to get the ScreenClass.
     *
     * @memberof ScreenClassProvider
     */
    componentDidMount() {
        window.addEventListener('resize', this.getScreenClass);
    }
 
    /**
     * Removes the resize handler to get the ScreenClass.
     *
     * @memberof ScreenClassProvider
     */
    componentWillUnmount() {
        window.removeEventListener('resize', this.getScreenClass);
    }
 
    /**
     * Calculates the ScreenClass.
     *
     * @memberof ScreenClassProvider
     */
    @autobind
    getScreenClass() {
        const {screenClass} = this.state;
        const {theme} = this.props;
        const newScreenClass = getScreenClass(theme);
 
        if (newScreenClass !== screenClass) {
            this.setState({screenClass: newScreenClass});
        }
    }
 
    /**
     * Renders the modal provider and childs.
     *
     * @returns {JSX} The ScreenClassProvider.
     * @memberof ScreenClassProvider
     */
    render() {
        const {screenClass} = this.state;
        const {children} = this.props;
 
        return (
            <ScreenClassContext.Provider
                value={screenClass}
            >
                {children}
            </ScreenClassContext.Provider>
        );
    }
}
 
export default withTheme(ScreenClassProvider);