All files / src/Avatar Avatar.tsx

100% Statements 12/12
71.43% Branches 5/7
100% Functions 2/2
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                                    1x   21x   21x                 21x 1x       21x                   1x   21x   21x 21x 1x     21x                        
import { Box as ReakitBox } from 'reakit';
 
import { Omit, Size } from '../types';
import { useClassName, createComponent, createElement, createHook } from '../utils';
import { Box } from '../Box';
import { Image, ImageProps } from '../Image';
 
import * as styles from './styles';
 
export type LocalAvatarProps = {
  kind?: 'circle';
  src?: string;
  size?: Size | string;
  initials?: string;
  palette?: string;
};
export type AvatarProps = Omit<ImageProps, 'src'> & LocalAvatarProps;
 
const useProps = createHook<AvatarProps>(
  (props = {}, { themeKey, themeKeyOverride }) => {
    const imageProps = Image.useProps({ ...props }, { themeKey: 'Avatar' });
 
    const className = useClassName({
      style: styles.Avatar,
      styleProps: props,
      themeKey,
      themeKeyOverride,
      prevClassName: imageProps.className
    });
 
    let children;
    if (props.initials) {
      children =
        props.initials.split(' ').length === 2 ? props.initials.match(/\b\w/g) : props.initials.substring(0, 2);
    }
 
    return { ...imageProps, className, children };
  },
  {
    defaultProps: {
      size: 'default'
    },
    themeKey: 'Avatar'
  }
);
 
export const Avatar = createComponent<AvatarProps>(
  props => {
    const imageProps = useProps(props);
 
    let use = props.use;
    if (props.initials) {
      use = Box;
    }
 
    return createElement({ component: ReakitBox, use, htmlProps: imageProps });
  },
  {
    attach: {
      useProps
    },
    defaultProps: {
      use: 'img'
    },
    themeKey: 'Avatar'
  }
);