All files / avatar avatar.js

100% Statements 13/13
85.71% Branches 6/7
100% Functions 5/5
100% Lines 12/12

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                                        6x 11x 6x                         8x 8x       5x       13x 13x 13x 13x       13x   13x                                                
/*
Copyright (c) 2018-2019 Uber Technologies, Inc.
 
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
 
import * as React from 'react';
 
import {getOverrides} from '../helpers/overrides.js';
 
import {
  Avatar as StyledAvatar,
  Initials as StyledInitials,
  Root as StyledRoot,
} from './styled-components.js';
import type {PropsT, StateT} from './types.js';
 
function getInitials(name) {
  const words = name.split(' ');
  const initials = words.map(word => word[0]);
  return initials
    .slice(0, 2)
    .join('')
    .toUpperCase();
}
 
export default class Avatar extends React.Component<PropsT, StateT> {
  static defaultProps: $Shape<PropsT> = {
    overrides: {},
    size: 'scale1000',
  };
 
  constructor(props: PropsT) {
    super(props);
    this.state = {noImageAvailable: !this.props.src};
  }
 
  handleError = () => {
    this.setState({noImageAvailable: true});
  };
 
  render() {
    const {noImageAvailable} = this.state;
    const {name, overrides = {}, size, src} = this.props;
    const [Avatar, avatarProps] = getOverrides(overrides.Avatar, StyledAvatar);
    const [Initials, initialsProps] = getOverrides(
      overrides.Initials,
      StyledInitials,
    );
    const [Root, rootProps] = getOverrides(overrides.Root, StyledRoot);
 
    return (
      <Root
        aria-label={noImageAvailable ? name : null}
        role={noImageAvailable ? 'img' : null}
        $didImageFailToLoad={noImageAvailable}
        $size={size}
        data-baseweb="avatar"
        {...rootProps}
      >
        {noImageAvailable ? (
          <Initials {...initialsProps}>{getInitials(name)}</Initials>
        ) : (
          <Avatar
            alt={name}
            onError={this.handleError}
            src={src}
            $size={size}
            {...avatarProps}
          />
        )}
      </Root>
    );
  }
}