ant-design/components/avatar/avatar.tsx

258 lines
7.2 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2020-07-13 12:45:37 +08:00
import classNames from 'classnames';
import ResizeObserver from 'rc-resize-observer';
import { composeRef } from 'rc-util/lib/ref';
import type { Breakpoint } from '../_util/responsiveObserver';
import { responsiveArray } from '../_util/responsiveObserver';
import { devUseWarning } from '../_util/warning';
import { ConfigContext } from '../config-provider';
import useSize from '../config-provider/hooks/useSize';
import useBreakpoint from '../grid/hooks/useBreakpoint';
import type { AvatarContextType, AvatarSize } from './AvatarContext';
import AvatarContext from './AvatarContext';
2022-06-21 19:40:22 +08:00
import useStyle from './style';
import useCSSVar from './style/cssVar';
2020-07-13 12:45:37 +08:00
export interface AvatarProps {
2021-04-02 22:37:36 +08:00
/** Shape of avatar, options: `circle`, `square` */
2020-07-13 12:45:37 +08:00
shape?: 'circle' | 'square';
/*
* Size of avatar, options: `large`, `small`, `default`
* or a custom number size
* */
size?: AvatarSize;
2020-07-13 12:45:37 +08:00
gap?: number;
/** Src of image avatar */
src?: React.ReactNode;
2020-07-13 12:45:37 +08:00
/** Srcset of image avatar */
srcSet?: string;
2023-03-09 17:37:22 +08:00
draggable?: boolean | 'true' | 'false';
/** Icon to be used in avatar */
2020-07-13 12:45:37 +08:00
icon?: React.ReactNode;
style?: React.CSSProperties;
prefixCls?: string;
className?: string;
rootClassName?: string;
2020-07-13 12:45:37 +08:00
children?: React.ReactNode;
alt?: string;
crossOrigin?: '' | 'anonymous' | 'use-credentials';
onClick?: (e?: React.MouseEvent<HTMLElement>) => void;
2020-07-13 12:45:37 +08:00
/* callback when img load error */
/* return false to prevent Avatar show default fallback behavior, then you can do fallback by yourself */
2020-07-13 12:45:37 +08:00
onError?: () => boolean;
}
2022-09-29 21:38:14 +08:00
const InternalAvatar: React.ForwardRefRenderFunction<HTMLSpanElement, AvatarProps> = (
props,
ref,
) => {
2020-07-13 12:45:37 +08:00
const [scale, setScale] = React.useState(1);
const [mounted, setMounted] = React.useState(false);
const [isImgExist, setIsImgExist] = React.useState(true);
2022-09-29 21:38:14 +08:00
const avatarNodeRef = React.useRef<HTMLSpanElement>(null);
const avatarChildrenRef = React.useRef<HTMLSpanElement>(null);
const avatarNodeMergeRef = composeRef<HTMLSpanElement>(ref, avatarNodeRef);
2020-07-13 12:45:37 +08:00
const { getPrefixCls, avatar } = React.useContext(ConfigContext);
2020-07-13 12:45:37 +08:00
const avatarCtx = React.useContext<AvatarContextType>(AvatarContext);
2020-07-13 12:45:37 +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;
// denominator is 0 is no meaning
if (childrenWidth !== 0 && nodeWidth !== 0) {
const { gap = 4 } = props;
if (gap * 2 < nodeWidth) {
setScale(nodeWidth - gap * 2 < childrenWidth ? (nodeWidth - gap * 2) / childrenWidth : 1);
}
2020-07-13 12:45:37 +08:00
}
};
React.useEffect(() => {
setMounted(true);
}, []);
React.useEffect(() => {
setIsImgExist(true);
setScale(1);
}, [props.src]);
React.useEffect(setScaleParam, [props.gap]);
2020-07-13 12:45:37 +08:00
const handleImgLoadError = () => {
const { onError } = props;
const errorFlag = onError?.();
2020-07-13 12:45:37 +08:00
if (errorFlag !== false) {
setIsImgExist(false);
}
};
const {
prefixCls: customizePrefixCls,
shape,
size: customSize,
2020-07-13 12:45:37 +08:00
src,
srcSet,
icon,
className,
rootClassName,
2020-07-13 12:45:37 +08:00
alt,
draggable,
2020-07-26 20:30:56 +08:00
children,
crossOrigin,
2020-07-13 12:45:37 +08:00
...others
} = props;
const size = useSize((ctxSize) => customSize ?? avatarCtx?.size ?? ctxSize ?? 'default');
const needResponsive = Object.keys(typeof size === 'object' ? size || {} : {}).some((key) =>
['xs', 'sm', 'md', 'lg', 'xl', 'xxl'].includes(key),
);
const screens = useBreakpoint(needResponsive);
const responsiveSizeStyle = React.useMemo<React.CSSProperties>(() => {
if (typeof size !== 'object') {
return {};
}
const currentBreakpoint: Breakpoint = responsiveArray.find((screen) => screens[screen])!;
const currentSize = size[currentBreakpoint];
return currentSize
? {
width: currentSize,
height: currentSize,
lineHeight: `${currentSize}px`,
fontSize: currentSize && (icon || children) ? currentSize / 2 : 18,
}
: {};
}, [screens, size]);
if (process.env.NODE_ENV !== 'production') {
const warning = devUseWarning('Avatar');
warning(
!(typeof icon === 'string' && icon.length > 2),
'breaking',
`\`icon\` is using ReactNode instead of string naming in v4. Please check \`${icon}\` at https://ant.design/components/icon`,
);
}
2020-07-13 12:45:37 +08:00
const prefixCls = getPrefixCls('avatar', customizePrefixCls);
const [, hashId] = useStyle(prefixCls);
const wrapCSSVar = useCSSVar(prefixCls);
2020-07-13 12:45:37 +08:00
const sizeCls = classNames({
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
});
const hasImageElement = React.isValidElement(src);
const mergedShape = shape || avatarCtx?.shape || 'circle';
const classString = classNames(
prefixCls,
sizeCls,
avatar?.className,
`${prefixCls}-${mergedShape}`,
{
[`${prefixCls}-image`]: hasImageElement || (src && isImgExist),
2021-04-02 22:37:36 +08:00
[`${prefixCls}-icon`]: !!icon,
},
className,
rootClassName,
hashId,
);
2020-07-13 12:45:37 +08:00
const sizeStyle: React.CSSProperties =
typeof size === 'number'
? {
width: size,
height: size,
lineHeight: `${size}px`,
fontSize: icon ? size / 2 : 18,
}
: {};
2022-09-29 21:38:14 +08:00
let childrenToRender: React.ReactNode;
if (typeof src === 'string' && isImgExist) {
2020-07-26 20:30:56 +08:00
childrenToRender = (
<img
src={src}
draggable={draggable}
srcSet={srcSet}
onError={handleImgLoadError}
alt={alt}
crossOrigin={crossOrigin}
/>
2020-07-13 12:45:37 +08:00
);
} else if (hasImageElement) {
childrenToRender = src;
2020-07-13 12:45:37 +08:00
} else if (icon) {
2020-07-26 20:30:56 +08:00
childrenToRender = icon;
} else if (mounted || 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`,
}
: {};
childrenToRender = (
<ResizeObserver onResize={setScaleParam}>
<span
className={`${prefixCls}-string`}
2022-09-29 21:38:14 +08:00
ref={avatarChildrenRef}
style={{ ...sizeChildrenStyle, ...childrenStyle }}
>
{children}
</span>
</ResizeObserver>
2020-07-26 20:30:56 +08:00
);
2020-07-13 12:45:37 +08:00
} else {
2020-07-26 20:30:56 +08:00
childrenToRender = (
2022-09-29 21:38:14 +08:00
<span className={`${prefixCls}-string`} style={{ opacity: 0 }} ref={avatarChildrenRef}>
2020-07-26 20:30:56 +08:00
{children}
</span>
);
2020-07-13 12:45:37 +08:00
}
// 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;
2020-07-26 20:30:56 +08:00
return wrapCSSVar(
2020-07-13 12:45:37 +08:00
<span
{...others}
style={{ ...sizeStyle, ...responsiveSizeStyle, ...avatar?.style, ...others.style }}
2020-07-13 12:45:37 +08:00
className={classString}
2022-09-29 21:38:14 +08:00
ref={avatarNodeMergeRef}
2020-07-13 12:45:37 +08:00
>
2020-07-26 20:30:56 +08:00
{childrenToRender}
</span>,
2020-07-13 12:45:37 +08:00
);
};
2022-09-29 21:38:14 +08:00
const Avatar = React.forwardRef<HTMLSpanElement, AvatarProps>(InternalAvatar);
if (process.env.NODE_ENV !== 'production') {
Avatar.displayName = 'Avatar';
}
2020-07-13 12:45:37 +08:00
export default Avatar;