@yamada-ui/react
Version:
React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion
85 lines (81 loc) • 2.28 kB
JavaScript
"use client";
import { mergeRefs } from "../../utils/ref.js";
import { utils_exports } from "../../utils/index.js";
import { useI18n } from "../../providers/i18n-provider/i18n-provider.js";
import { useCallback, useEffect, useRef, useState } from "react";
//#region src/components/avatar/use-avatar.ts
const defaultFormat = (name) => {
const names = name.trim().split(" ");
const firstName = names[0] ?? "";
const lastName = names.length > 1 ? names[names.length - 1] : "";
return firstName && lastName ? `${firstName.charAt(0)}${lastName.charAt(0)}` : firstName.charAt(0);
};
const useAvatar = ({ name, src, srcSet, alt, crossOrigin, fallback: fallbackMessage, format = defaultFormat, icon, loading, referrerPolicy = "no-referrer",...rest } = {}) => {
const imageRef = useRef(null);
const initials = name ? format(name) : void 0;
const [loaded, setLoaded] = useState(false);
const fallback = !src || !loaded;
const { t } = useI18n("avatar");
useEffect(() => {
if (!imageRef.current) return;
if (!!imageRef.current.src && imageRef.current.complete) setLoaded(true);
}, []);
const getGroupProps = useCallback((props) => ({ ...props }), []);
const getRootProps = useCallback((props) => ({
...rest,
...props,
"data-fallback": (0, utils_exports.dataAttr)(!!fallbackMessage),
"data-loaded": (0, utils_exports.dataAttr)(loaded)
}), [
loaded,
fallbackMessage,
rest
]);
const getImageProps = useCallback(({ ref, onLoad,...props } = {}) => ({
...props,
ref: mergeRefs(ref, imageRef),
src,
srcSet,
alt: name || alt,
crossOrigin,
draggable: false,
hidden: fallback,
loading,
referrerPolicy,
onLoad: (0, utils_exports.handlerAll)(onLoad, () => setLoaded(true))
}), [
src,
srcSet,
alt,
crossOrigin,
loading,
referrerPolicy,
fallback,
name
]);
return {
name,
loaded,
getFallbackProps: useCallback((props) => ({
...props,
"aria-label": !fallbackMessage ? name || alt || t("Avatar Icon") : void 0,
children: fallbackMessage || initials || icon,
hidden: !fallback,
role: "img"
}), [
name,
initials,
fallback,
icon,
fallbackMessage,
alt,
t
]),
getGroupProps,
getImageProps,
getRootProps
};
};
//#endregion
export { useAvatar };
//# sourceMappingURL=use-avatar.js.map