UNPKG

@engie-group/fluid-design-system-react

Version:

Fluid Design System React

63 lines (60 loc) 3.12 kB
import { jsxs, jsx, Fragment } from 'react/jsx-runtime'; import React__default, { useContext } from 'react'; import { Utils } from '../../../utils/util.js'; import { NJTooltip } from '../../tooltip/NJTooltip.js'; import { NJAvatarContext } from '../NJAvatar.context.js'; const rootComponentClassName = 'nj-avatar'; const Component = React__default.forwardRef(({ initials, children, label, scale, href, target, rel, isClickable, isRemainingCount, onClick, onMouseEnter, onMouseLeave, tooltipText, tooltipPosition = 'bottom', className, asChild = false }, ref) => { const context = useContext(NJAvatarContext); let CustomTag = 'div'; if (href) { CustomTag = 'a'; } else if (isClickable) { CustomTag = 'button'; } const localSize = scale; const avatarClass = Utils.classNames(rootComponentClassName, { [`${rootComponentClassName}--${localSize}`]: !!localSize, [`${rootComponentClassName}--default-icon`]: !initials && !context?.hasContent && !isRemainingCount, [`${rootComponentClassName}--clickable`]: isClickable || isRemainingCount, [`${rootComponentClassName}--remaining-count`]: isRemainingCount, [`${rootComponentClassName}--initials`]: initials || isRemainingCount, [`${rootComponentClassName}--picture`]: context?.hasContent }, className); const avatarTooltipClass = Utils.classNames(`${rootComponentClassName}__tooltip`, { [`${rootComponentClassName}__tooltip--${localSize}`]: !!localSize }); // Initials cannot exceed 3 characters if (initials) { if (initials.length >= 4) { initials = initials.slice(0, 3); } } const avatarContent = (child) => (jsxs(Fragment, { children: [initials && (jsx("span", { className: `${rootComponentClassName}__initials`, "aria-hidden": "true", children: initials })), !context?.hasContent && label && jsx("p", { className: "nj-sr-only", children: label }), child] })); let content; if (asChild) { const onlyChild = React__default.Children.only(children); content = React__default.cloneElement(onlyChild, { children: avatarContent(onlyChild.props.children), className: avatarClass, ref }); } else { content = (jsx(CustomTag, { href: href, target: target, rel: rel, className: avatarClass, ref: ref, onClick: onClick, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, children: avatarContent(children) })); } if (tooltipText) { return (jsx(NJTooltip, { text: tooltipText, placement: tooltipPosition, className: avatarTooltipClass, children: content })); } else { return content; } }); Component.displayName = ''; const NJAvatarRoot = React__default.forwardRef((props, forwardedRef) => { const [hasContent, setHasContent] = React__default.useState(false); return (jsx(NJAvatarContext.Provider, { value: { hasContent, setHasContent, label: props.label }, children: jsx(Component, { ...props, ref: forwardedRef }) })); }); NJAvatarRoot.displayName = 'NJAvatarRoot'; export { NJAvatarRoot };