All files / src/components/Avatar index.jsx

95.65% Statements 22/23
85.71% Branches 12/14
85.71% Functions 6/7
95.45% Lines 21/22
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                        15x 15x               15x   15x 15x 15x 30x       15x 5x     10x 1x     9x 1x     8x       30x 14x       16x 16x       15x     15x       7x                            
import styles from './style.postcss';
 
import React, { PureComponent } from 'react';
import classnames from 'classnames';
import is from 'is_js';
import Gender from 'domain/Gender';
import PropTypes from 'prop-types';
 
import generateUserInitialsAvatarSvgUri from './generateUserInitialsAvatarSvg';
 
class Avatar extends PureComponent {
  constructor(props) {
    super(props);
    this._setUp(props);
  }
 
  componentWillUpdate(props) {
    this._setUp(props);
  }
 
  _setUp(props) {
    this._default = this._getDefaultAvatar(props);
 
    const images = [];
    images.push(this._getCssValueForUrl(props.src));
    images.push(this._getCssValueForUrl(this._default));
    this._style = { backgroundImage: images.filter((e) => is.string(e)).join(', ') };
  }
 
  _getDefaultAvatar(props) {
    if (props.displayUserInitialsAsDefaultAvatar) {
      return generateUserInitialsAvatarSvgUri(props.userFirstName, props.userLastName);
    }
 
    if (Gender.isMale(props.gender)) {
      return props.defaultMale || props.default;
    }
 
    if (Gender.isFemale(props.gender)) {
      return props.defaultFemale || props.default;
    }
 
    return props.default;
  }
 
  _getCssValueForUrl(url) {
    if (is.not.string(url)) {
      return null;
    }
 
    // don't let http images crash the party
    const secureUrl = url.replace(/^http:/, '');  // //host/path uses current protocol
    return is.not.empty(url) && `url("${secureUrl}")`;
  }
 
  render() {
    const className = classnames(styles.Avatar, {
      [styles.__biggerOnHover]: this.props.biggerOnHover,
    }, this.props.className);
    return <div style={this._style} className={className} />;
  }
}
 
Avatar.propTypes = {
  biggerOnHover: PropTypes.bool,
  className: PropTypes.string,
  src: PropTypes.string,
  default: PropTypes.string,
  defaultMale: PropTypes.string,
  defaultFemale: PropTypes.string,
  gender: PropTypes.string,
  userFirstName: PropTypes.string,
  userLastName: PropTypes.string,
  displayUserInitialsAsDefaultAvatar: PropTypes.bool,
};
 
export default Avatar;