2021-12-08 01:59:55 +00:00
|
|
|
import React, { useMemo } from "react";
|
|
|
|
import classNames from "classnames";
|
2022-05-06 10:32:09 +00:00
|
|
|
|
2021-12-08 01:59:55 +00:00
|
|
|
import styles from "./Avatar.module.css";
|
|
|
|
|
|
|
|
const backgroundColors = [
|
|
|
|
"#5C56F5",
|
|
|
|
"#03B381",
|
|
|
|
"#368BD6",
|
|
|
|
"#AC3BA8",
|
|
|
|
"#E64F7A",
|
|
|
|
"#FF812D",
|
|
|
|
"#2DC2C5",
|
|
|
|
"#74D12C",
|
|
|
|
];
|
|
|
|
|
2022-05-06 10:32:09 +00:00
|
|
|
function hashStringToArrIndex(str: string, arrLength: number) {
|
2021-12-08 01:59:55 +00:00
|
|
|
let sum = 0;
|
|
|
|
|
|
|
|
for (let i = 0; i < str.length; i++) {
|
|
|
|
sum += str.charCodeAt(i);
|
|
|
|
}
|
|
|
|
|
|
|
|
return sum % arrLength;
|
|
|
|
}
|
|
|
|
|
2022-05-06 10:32:09 +00:00
|
|
|
interface Props extends React.HTMLAttributes<HTMLDivElement> {
|
|
|
|
bgKey?: string;
|
|
|
|
src: string;
|
|
|
|
fallback: string;
|
|
|
|
size?: number;
|
|
|
|
className: string;
|
|
|
|
style: React.CSSProperties;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const Avatar: React.FC<Props> = ({
|
2021-12-08 01:59:55 +00:00
|
|
|
bgKey,
|
|
|
|
src,
|
|
|
|
fallback,
|
|
|
|
size,
|
|
|
|
className,
|
|
|
|
style,
|
|
|
|
...rest
|
2022-05-06 10:32:09 +00:00
|
|
|
}) => {
|
2021-12-08 01:59:55 +00:00
|
|
|
const backgroundColor = useMemo(() => {
|
|
|
|
const index = hashStringToArrIndex(
|
2022-03-01 19:37:45 +00:00
|
|
|
bgKey || fallback || src || "",
|
2021-12-08 01:59:55 +00:00
|
|
|
backgroundColors.length
|
|
|
|
);
|
|
|
|
return backgroundColors[index];
|
|
|
|
}, [bgKey, src, fallback]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div
|
|
|
|
className={classNames(styles.avatar, styles[size || "md"], className)}
|
|
|
|
style={{ backgroundColor, ...style }}
|
|
|
|
{...rest}
|
|
|
|
>
|
|
|
|
{src ? (
|
|
|
|
<img src={src} />
|
|
|
|
) : typeof fallback === "string" ? (
|
|
|
|
<span>{fallback}</span>
|
|
|
|
) : (
|
|
|
|
fallback
|
|
|
|
)}
|
|
|
|
</div>
|
|
|
|
);
|
2022-05-06 10:32:09 +00:00
|
|
|
};
|