Skip to content

Commit cac78fa

Browse files
authored
Add user Avatar color based on name (#569)
* feat(): Add user Avatar color based on name Signed-off-by: sBouzols <[email protected]>
1 parent d8b1c91 commit cac78fa

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/components/utils/renderers/user-cell-renderer.tsx

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,25 @@
44
* License, v. 2.0. If a copy of the MPL was not distributed with this
55
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
66
*/
7+
import { mergeSx } from '@gridsuite/commons-ui';
78
import { Avatar, Box, Theme, Tooltip } from '@mui/material';
89

10+
const FERMAT_PRIME = 65537;
11+
// This function is a copy/paste of the MUI demo sample here :
12+
// https://mui.com/material-ui/react-avatar/#letter-avatars
13+
// hash function improved to generate more distinct values for similar strings using FERMAT_PRIME
14+
// Use hsl to manage saturation and softer colors
15+
function stringToColor(string: string) {
16+
let hash = 0;
17+
/* eslint-disable no-bitwise */
18+
const stringUniqueHash = [...string].reduce((acc, char) => {
19+
hash = char.charCodeAt(0) + ((acc << 5) - acc) * FERMAT_PRIME;
20+
return hash & hash;
21+
}, 0);
22+
/* eslint-enable no-bitwise */
23+
return `hsl(${stringUniqueHash % 360}, 50%, 50%)`;
24+
}
25+
926
function getAbbreviationFromUserName(name: string) {
1027
// notice : == null means null or undefined
1128
if (name == null || name.trim() === '') {
@@ -24,6 +41,7 @@ const styles = {
2441
height: '32px',
2542
width: '32px',
2643
fontSize: theme.typography.fontSize,
44+
backgroundColor: theme.row.hover as string,
2745
}),
2846
};
2947

@@ -33,7 +51,9 @@ export function UserCellRenderer({ value }: Readonly<UserCellRendererProps>) {
3351
return (
3452
<Box sx={{ display: 'inline-flex', verticalAlign: 'middle' }}>
3553
<Tooltip title={value} placement="right">
36-
<Avatar sx={styles.avatar}>{getAbbreviationFromUserName(value)}</Avatar>
54+
<Avatar sx={mergeSx(styles.avatar, value ? { backgroundColor: stringToColor(value) } : null)}>
55+
{getAbbreviationFromUserName(value)}
56+
</Avatar>
3757
</Tooltip>
3858
</Box>
3959
);

0 commit comments

Comments
 (0)