|
3 | 3 | * SPDX-License-Identifier: AGPL-3.0-or-later |
4 | 4 | */ |
5 | 5 |
|
6 | | -export { default } from './usernameToColor.js' |
| 6 | +import { GenColors } from '../../utils/GenColors.js' |
| 7 | + |
| 8 | +import md5 from 'md5' |
| 9 | + |
| 10 | +/** |
| 11 | + * Generate a color from a username |
| 12 | + * Originally taken from https://github.com/nextcloud/server/blob/master/core/js/placeholder.js |
| 13 | + * |
| 14 | + * @param {string} username Display name or user id to generate from |
| 15 | + * @return {{ r: number, g: number, b: number }} the RGB color |
| 16 | + */ |
| 17 | +export function usernameToColor(username) { |
| 18 | + // Normalize hash |
| 19 | + let hash = username.toLowerCase() |
| 20 | + |
| 21 | + // Already a md5 hash? |
| 22 | + if (hash.match(/^([0-9a-f]{4}-?){8}$/) === null) { |
| 23 | + hash = md5(hash) |
| 24 | + } |
| 25 | + |
| 26 | + hash = hash.replace(/[^0-9a-f]/g, '') |
| 27 | + |
| 28 | + const steps = 6 |
| 29 | + const finalPalette = GenColors(steps) |
| 30 | + |
| 31 | + /** |
| 32 | + * Convert a string to an integer evenly |
| 33 | + * |
| 34 | + * @param {string} hash The hash to convert |
| 35 | + * @param {number} maximum Largest number allowed |
| 36 | + */ |
| 37 | + function hashToInt(hash, maximum) { |
| 38 | + let finalInt = 0 |
| 39 | + const result = [] |
| 40 | + |
| 41 | + // Splitting evenly the string |
| 42 | + for (let i = 0; i < hash.length; i++) { |
| 43 | + // chars in md5 goes up to f, hex:16 |
| 44 | + result.push(parseInt(hash.charAt(i), 16) % 16) |
| 45 | + } |
| 46 | + |
| 47 | + // Adds up all results |
| 48 | + for (const j in result) { |
| 49 | + finalInt += result[j] |
| 50 | + } |
| 51 | + |
| 52 | + // chars in md5 goes up to f, hex:16 |
| 53 | + // make sure we're always using int in our operation |
| 54 | + return parseInt(parseInt(finalInt, 10) % maximum, 10) |
| 55 | + } |
| 56 | + return finalPalette[hashToInt(hash, steps * 3)] |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * @deprecated use the named export of `usernameToColor` instead |
| 61 | + */ |
| 62 | +export default usernameToColor |
0 commit comments