Skip to content

Commit

Permalink
fixed an issue where the initial color in avatar was not right
Browse files Browse the repository at this point in the history
  • Loading branch information
fraincs committed Apr 23, 2024
1 parent 803577e commit 9ddb577
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
5 changes: 5 additions & 0 deletions .changeset/young-colts-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@orbit-ui/transition-components": patch
---

Avatar Initials color is now the right one
40 changes: 17 additions & 23 deletions packages/components/src/avatar/src/Avatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,18 @@ function AvatarImage({
);
}

const O365InitialsColorsForName = [
"#95B1FF",
"#A3D6CB",
"#FFBF92",
"#AAD89D",
"#9FD2F7",
"#EAC96D",
"#E5DED6",
"#FFBCB7"
];
function getColorIndexForInitial(name: string, maxNumberOfColor: number) {
let hashCode = 0;

for (let i = name.length - 1; i >= 0; i--) {
const character = name.charCodeAt(i);
const shift = i % 8;

hashCode ^= (character << shift) + (character >> (8 - shift));
}

return hashCode % maxNumberOfColor;
}

function AvatarInitials({ "aria-label": ariaLabel, name, size }: Partial<InnerAvatarProps>) {
const initials = useMemo(() => {
Expand All @@ -92,28 +94,20 @@ function AvatarInitials({ "aria-label": ariaLabel, name, size }: Partial<InnerAv
return size === "xs" && letters.length > 1 ? letters.charAt(0) : letters;
}, [name, size]);

const color = useMemo(() => {
let hashCode = 0;

for (let i = name.length - 1; i >= 0; i--) {
const character = name.charCodeAt(i);
const shift = i % 8;

hashCode ^= (character << shift) + (character >> (8 - shift));
}

return O365InitialsColorsForName[hashCode % O365InitialsColorsForName.length];
}, [name]);
const variantToUse = useMemo(() => `option${getColorIndexForInitial(name, 8) + 1}`, [name]);

const initialValue = size === "xs" ? initials.at(0) : initials;
const tokenBackgroundColor = `var(--hop-decorative-${variantToUse}-surface-strong)`;
const tokenTextColor = `var(--hop-decorative-${variantToUse}-text)`;

return (
<AvatarText
aria-label={ariaLabel ?? name}
role="img"
size={size}
style={{
backgroundColor: color
backgroundColor: tokenBackgroundColor,
color: tokenTextColor
}}
>
{initialValue}
Expand Down

0 comments on commit 9ddb577

Please sign in to comment.