ant-design/components/avatar/index.tsx

216 lines
5.5 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2017-05-28 14:20:59 +08:00
import classNames from 'classnames';
use ant design icons 4.0 (#18217) * feat: use @ant-design/icons@4.0 * feat: use createFromIconfontCN to make site works * feat: update doc for Icon * feat: use icon in component Alert * feat: use icon in component Avatar * feat: use icon in component Breadcrumb * feat: use icon in component Button * feat: use icon in component Cascader * feat: use icon in component Collapse * feat: use icon in component Datepicker * feat: use icon in component Dropdown * feat: use icon in component Form * feat: use icon in component Input * feat: use icon in component InputNumber * feat: use icon in component Layout * feat: use icon in component Mention * feat: use icon in component Message * feat: use icon in component Modal * feat: use icon in component Notification * feat: use icon in component PageHeader * feat: use icon in component Pagination * feat: use icon in component Popconfirm * feat: use icon in component Progress * feat: use icon in component Rate * feat: use icon in component Result * feat: use icon in component Select * feat: use icon in component Step * feat: use icon in component Switch * feat: use icon in component Table * feat: use icon in component Tab * feat: use icon in component Tag * feat: handle rest component which using Icon * fix: remove unused vars * feat: use latest alpha ant design icons * fix: failed test in uploadlist.test.js * test: update snapshot for icons * doc: add Icon for site * doc: use @ant-design/icons in site * chore: use latest icons * fix: tslint issue * fix: test cases * fix: types for react * fix: lint rules for import orders * fix: use @ant-design/icons@4.0.0-alpha.5 to avoid insert css in server render * fix: eslint error in demo/**.md * inject antd icons * update snapshot * fix site * doc: update docs * fix: code snippets icon in site * feat: use latest @ant-design/icons * fix: icon props in message
2019-08-13 14:07:17 +08:00
import { ConfigContext } from '../config-provider';
import devWarning from '../_util/devWarning';
2017-05-28 14:20:59 +08:00
export interface AvatarProps {
/** Shape of avatar, options:`circle`, `square` */
shape?: 'circle' | 'square';
/*
* Size of avatar, options: `large`, `small`, `default`
* or a custom number size
* */
size?: 'large' | 'small' | 'default' | number;
gap?: number;
2017-05-28 14:20:59 +08:00
/** Src of image avatar */
src?: string;
/** Srcset of image avatar */
srcSet?: string;
draggable?: boolean;
use ant design icons 4.0 (#18217) * feat: use @ant-design/icons@4.0 * feat: use createFromIconfontCN to make site works * feat: update doc for Icon * feat: use icon in component Alert * feat: use icon in component Avatar * feat: use icon in component Breadcrumb * feat: use icon in component Button * feat: use icon in component Cascader * feat: use icon in component Collapse * feat: use icon in component Datepicker * feat: use icon in component Dropdown * feat: use icon in component Form * feat: use icon in component Input * feat: use icon in component InputNumber * feat: use icon in component Layout * feat: use icon in component Mention * feat: use icon in component Message * feat: use icon in component Modal * feat: use icon in component Notification * feat: use icon in component PageHeader * feat: use icon in component Pagination * feat: use icon in component Popconfirm * feat: use icon in component Progress * feat: use icon in component Rate * feat: use icon in component Result * feat: use icon in component Select * feat: use icon in component Step * feat: use icon in component Switch * feat: use icon in component Table * feat: use icon in component Tab * feat: use icon in component Tag * feat: handle rest component which using Icon * fix: remove unused vars * feat: use latest alpha ant design icons * fix: failed test in uploadlist.test.js * test: update snapshot for icons * doc: add Icon for site * doc: use @ant-design/icons in site * chore: use latest icons * fix: tslint issue * fix: test cases * fix: types for react * fix: lint rules for import orders * fix: use @ant-design/icons@4.0.0-alpha.5 to avoid insert css in server render * fix: eslint error in demo/**.md * inject antd icons * update snapshot * fix site * doc: update docs * fix: code snippets icon in site * feat: use latest @ant-design/icons * fix: icon props in message
2019-08-13 14:07:17 +08:00
/** icon to be used in avatar */
icon?: React.ReactNode;
2017-05-28 14:20:59 +08:00
style?: React.CSSProperties;
prefixCls?: string;
className?: string;
children?: React.ReactNode;
2018-06-07 11:36:16 +08:00
alt?: string;
/* callback when img load error */
2019-08-05 18:38:10 +08:00
/* return false to prevent Avatar show default fallback behavior, then you can do fallback by your self */
onError?: () => boolean;
2017-05-28 14:20:59 +08:00
}
const Avatar: React.FC<AvatarProps> = props => {
const [scale, setScale] = React.useState(1);
const [mounted, setMounted] = React.useState(false);
const [isImgExist, setIsImgExist] = React.useState(true);
2019-08-05 18:38:10 +08:00
const avatarNodeRef = React.useRef<HTMLElement>();
const avatarChildrenRef = React.useRef<HTMLElement>();
2019-08-05 18:38:10 +08:00
let lastChildrenWidth: number;
let lastNodeWidth: number;
2019-08-05 18:38:10 +08:00
const { getPrefixCls } = React.useContext(ConfigContext);
2017-06-08 11:44:04 +08:00
const setScaleParam = () => {
if (!avatarChildrenRef.current || !avatarNodeRef.current) {
return;
}
const childrenWidth = avatarChildrenRef.current.offsetWidth; // offsetWidth avoid affecting be transform scale
const nodeWidth = avatarNodeRef.current.offsetWidth;
const { gap = 4 } = props;
// denominator is 0 is no meaning
if (
childrenWidth !== 0 &&
nodeWidth !== 0 &&
(lastChildrenWidth !== childrenWidth || lastNodeWidth !== nodeWidth)
) {
lastChildrenWidth = childrenWidth;
lastNodeWidth = nodeWidth;
}
if (gap * 2 < nodeWidth) {
setScale(nodeWidth - gap * 2 < childrenWidth ? (nodeWidth - gap * 2) / childrenWidth : 1);
2017-06-07 11:18:31 +08:00
}
2018-12-07 20:02:01 +08:00
};
2017-05-28 14:20:59 +08:00
React.useEffect(() => {
setScaleParam();
setMounted(true);
}, []);
React.useEffect(() => {
setIsImgExist(true);
setScale(1);
}, [props.src]);
React.useEffect(() => {
setScaleParam();
}, [props.children, props.gap]);
React.useEffect(() => {
if (props.children) {
setScaleParam();
}
}, [isImgExist]);
const handleImgLoadError = () => {
const { onError } = props;
const errorFlag = onError ? onError() : undefined;
if (errorFlag !== false) {
setIsImgExist(false);
}
2018-12-07 20:02:01 +08:00
};
const {
prefixCls: customizePrefixCls,
shape,
size,
src,
srcSet,
icon,
className,
alt,
draggable,
...others
} = props;
devWarning(
!(typeof icon === 'string' && icon.length > 2),
'Avatar',
`\`icon\` is using ReactNode instead of string naming in v4. Please check \`${icon}\` at https://ant.design/components/icon`,
);
const prefixCls = getPrefixCls('avatar', customizePrefixCls);
const sizeCls = classNames({
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
});
const classString = classNames(prefixCls, className, sizeCls, {
[`${prefixCls}-${shape}`]: shape,
[`${prefixCls}-image`]: src && isImgExist,
[`${prefixCls}-icon`]: icon,
});
const sizeStyle: React.CSSProperties =
typeof size === 'number'
? {
width: size,
height: size,
lineHeight: `${size}px`,
fontSize: icon ? size / 2 : 18,
}
: {};
let { children } = props;
if (src && isImgExist) {
children = (
<img src={src} draggable={draggable} srcSet={srcSet} onError={handleImgLoadError} alt={alt} />
);
} else if (icon) {
children = icon;
} else {
const childrenNode = avatarChildrenRef.current;
if (childrenNode || scale !== 1) {
const transformString = `scale(${scale}) translateX(-50%)`;
const childrenStyle: React.CSSProperties = {
msTransform: transformString,
WebkitTransform: transformString,
transform: transformString,
};
const sizeChildrenStyle: React.CSSProperties =
typeof size === 'number'
? {
lineHeight: `${size}px`,
}
: {};
children = (
<span
className={`${prefixCls}-string`}
ref={(node: HTMLElement) => {
avatarChildrenRef.current = node;
}}
style={{ ...sizeChildrenStyle, ...childrenStyle }}
>
{children}
</span>
);
2017-06-07 11:18:31 +08:00
} else {
const childrenStyle: React.CSSProperties = {};
if (!mounted) {
childrenStyle.opacity = 0;
2017-06-07 11:18:31 +08:00
}
children = (
<span
className={`${prefixCls}-string`}
style={{ opacity: 0 }}
ref={(node: HTMLElement) => {
avatarChildrenRef.current = node;
}}
>
{children}
</span>
);
}
}
// The event is triggered twice from bubbling up the DOM tree.
// see https://codesandbox.io/s/kind-snow-9lidz
delete others.onError;
delete others.gap;
return (
<span
{...others}
style={{ ...sizeStyle, ...others.style }}
className={classString}
ref={(node: HTMLElement) => {
avatarNodeRef.current = node;
}}
>
{children}
</span>
);
};
Avatar.defaultProps = {
shape: 'circle' as AvatarProps['shape'],
size: 'default' as AvatarProps['size'],
};
export default Avatar;