All files / src/media-query index.js

100% Statements 17/17
100% Branches 6/6
100% Functions 8/8
100% Lines 17/17
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                      3x             8x 3x 5x 1x 4x 3x   1x     4x         2x 2x       2x       2x 2x   2x       1x       4x        
/* Copyright © 2016 Kuali, Inc. - All Rights Reserved
 * You may use and modify this code under the terms of the Kuali, Inc.
 * Pre-Release License Agreement. You may not distribute it.
 *
 * You should have received a copy of the Kuali, Inc. Pre-Release License
 * Agreement with this file. If not, please write to license@kuali.co.
 */
 
import { throttle } from 'lodash'
import React, { Component } from 'react'
 
const breakpoints = {
  sm: 768,
  md: 992,
  lg: 1200,
}
 
export function getSize({ innerWidth: width }) {
  if (width <= breakpoints.sm) {
    return 'small'
  } else if (width <= breakpoints.md) {
    return 'medium'
  } else if (width <= breakpoints.lg) {
    return 'large'
  }
  return 'huge'
}
 
export default (OldComponent) => class MediaQueryify extends Component {
 
  static displayName = 'MediaQueryHoc';
 
  constructor() {
    super()
    this.state = { mq: getSize(window) }
  }
 
  componentDidMount() {
    this.setupListeners()
  }
 
  setupListeners() {
    this.onResize = throttle(() => {
      this.setState({ mq: getSize(window) })
    }, 100)
    window.addEventListener('resize', this.onResize)
  }
 
  componentWillUnmount() {
    window.removeEventListener('resize', this.onResize)
  }
 
  render() {
    return <OldComponent mq={this.state.mq} {...this.props} />
  }
 
}