Skip to content

Commit

Permalink
[Avatar] backgroundColor from string
Browse files Browse the repository at this point in the history
  • Loading branch information
Vikram710 committed Apr 16, 2021
1 parent b3c85de commit 4fc1380
Showing 1 changed file with 61 additions and 26 deletions.
87 changes: 61 additions & 26 deletions packages/material-ui/src/Avatar/Avatar.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,34 @@ const useUtilityClasses = (styleProps) => {
return composeClasses(slots, getAvatarUtilityClass, classes);
};

const stringToColor = (styleProps) => {
let hash = 0;
let i;
let color = '';
const string = styleProps.alt;

if (styleProps.sx && styleProps.sx.bgcolor) {
return color;
}
if (!string) {
return color;
}
/* eslint-disable no-bitwise */
for (i = 0; i < string.length; i += 1) {
hash = string.charCodeAt(i) + ((hash << 5) - hash);
}

color = '#';

for (i = 0; i < 3; i += 1) {
const value = (hash >> (i * 8)) & 0xff;
color += `00${value.toString(16)}`.substr(-2);
}
/* eslint-enable no-bitwise */

return color;
};

const AvatarRoot = experimentalStyled(
'div',
{},
Expand All @@ -42,32 +70,39 @@ const AvatarRoot = experimentalStyled(
slot: 'Root',
overridesResolver,
},
)(({ theme, styleProps }) => ({
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
width: 40,
height: 40,
fontFamily: theme.typography.fontFamily,
fontSize: theme.typography.pxToRem(20),
lineHeight: 1,
borderRadius: '50%',
overflow: 'hidden',
userSelect: 'none',
...(styleProps.variant === 'rounded' && {
borderRadius: theme.shape.borderRadius,
}),
...(styleProps.variant === 'square' && {
borderRadius: 0,
}),
...(styleProps.colorDefault && {
color: theme.palette.background.default,
backgroundColor:
theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[600],
}),
}));
)(({ theme, styleProps }) => {
const stringColor = stringToColor(styleProps);
return {
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
width: 40,
height: 40,
fontFamily: theme.typography.fontFamily,
fontSize: theme.typography.pxToRem(20),
lineHeight: 1,
borderRadius: '50%',
overflow: 'hidden',
userSelect: 'none',
...(styleProps.variant === 'rounded' && {
borderRadius: theme.shape.borderRadius,
}),
...(styleProps.variant === 'square' && {
borderRadius: 0,
}),
...(styleProps.colorDefault && {
color: stringColor
? theme.palette.getContrastText(stringColor)
: theme.palette.background.default,

backgroundColor:
stringColor ||
(theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]),
}),
};
});

const AvatarImg = experimentalStyled(
'img',
Expand Down

0 comments on commit 4fc1380

Please sign in to comment.