import { Avatar, Spin, Tooltip } from 'antd'; import _ from 'lodash'; import React, { useMemo } from 'react'; import { qiniuImageView } from '../../utils/utils'; import styles from './index.module.css'; type PropType = { name?: string; src?: string; size?: string | number; loading?: boolean; alt?: string; icon?: any; width?: number; className?: string; onClick?: (e: any) => void; online?: boolean; group?: boolean; }; const calSize = (size: string | undefined | number, width: number | undefined) => { let sizeNumber = 32; if (typeof size === 'number') { sizeNumber = size; } else if (size !== 'auto') { switch (size) { case 'small': sizeNumber = 24; break; case 'large': sizeNumber = 40; break; default: } } else if (width) { sizeNumber = Math.floor(width * 0.8); } return sizeNumber; }; const formatURL = (src: string | undefined, size: number) => { let formatedURL = src; if (src) { formatedURL = qiniuImageView(src, 5, size * 2); } return formatedURL; }; const CustomizedAvatar: React.FC = ({ name, src, size, loading, alt, icon, width, online, group, ...props }) => { const sizeNumber = useMemo(() => calSize(size, width), [size, width]); const formatedURL = src?.startsWith('http') ? formatURL(src, sizeNumber) : src; const getImageAvatar = () => { return ( {group ? ( ) : ( {loading && (
)}
)} ); }; const getColorTextAvatar = (color: string, text: string, otherProps?: any) => (
{text}
); const getColorAvatar = (color: string, text: string) => { return ( {group ? ( getColorTextAvatar(color, text, size === 'auto' ? {} : { 'line-height': sizeNumber - 2 }) ) : (
{getColorTextAvatar(color, text)}
)} ); }; const split = (s: string | undefined) => _.filter(s?.split(/(#)(?!.*\1)/), (l: string) => l !== '#'); const getAvatarView = () => { if (size === 'auto') { if (formatedURL?.startsWith('http') || !formatedURL) { return group ? getImageAvatar() :
{getImageAvatar()}
; } const data = split(formatedURL); if (data && data.length === 2) { return group ? ( getColorAvatar(data[0], ` ${data[1]} `) ) : (
{getColorAvatar(data[0], ` ${data[1]} `)}
); } return ( // eslint-disable-next-line react/jsx-no-useless-fragment <> {group ? ( ) : (
)} ); } if (formatedURL?.startsWith('http') || !formatedURL) { return getImageAvatar(); } const data = split(formatedURL); if (data && data.length === 2) { return getColorAvatar(data[0], data[1]); } return ( // eslint-disable-next-line react/jsx-no-useless-fragment <> {group ? ( ) : (
)} ); }; return getAvatarView(); }; export default CustomizedAvatar;