You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

functions.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // @flow
  2. import GraphemeSplitter from 'grapheme-splitter';
  3. import _ from 'lodash';
  4. const AVATAR_COLORS = [
  5. '#6A50D3',
  6. '#FF9B42',
  7. '#DF486F',
  8. '#73348C',
  9. '#B23683',
  10. '#F96E57',
  11. '#4380E2',
  12. '#2AA076',
  13. '#00A8B3'
  14. ];
  15. const wordSplitRegex = (/\s+|\.+|_+|;+|-+|,+|\|+|\/+|\\+/);
  16. const splitter = new GraphemeSplitter();
  17. /**
  18. * Generates the background color of an initials based avatar.
  19. *
  20. * @param {string?} initials - The initials of the avatar.
  21. * @param {Array<strig>} customAvatarBackgrounds - Custom avatar background values.
  22. * @returns {string}
  23. */
  24. export function getAvatarColor(initials: ?string, customAvatarBackgrounds: Array<string>) {
  25. const hasCustomAvatarBackgronds = customAvatarBackgrounds && customAvatarBackgrounds.length;
  26. const colorsBase = hasCustomAvatarBackgronds ? customAvatarBackgrounds : AVATAR_COLORS;
  27. let colorIndex = 0;
  28. if (initials) {
  29. let nameHash = 0;
  30. for (const s of initials) {
  31. nameHash += s.codePointAt(0);
  32. }
  33. colorIndex = nameHash % colorsBase.length;
  34. }
  35. return colorsBase[colorIndex];
  36. }
  37. /**
  38. * Returns the first grapheme from a word, uppercased.
  39. *
  40. * @param {string} word - The string to get grapheme from.
  41. * @returns {string}
  42. */
  43. function getFirstGraphemeUpper(word) {
  44. if (!word?.length) {
  45. return '';
  46. }
  47. return splitter.splitGraphemes(word)[0].toUpperCase();
  48. }
  49. /**
  50. * Generates initials for a simple string.
  51. *
  52. * @param {string?} s - The string to generate initials for.
  53. * @returns {string?}
  54. */
  55. export function getInitials(s: ?string) {
  56. // We don't want to use the domain part of an email address, if it is one
  57. const initialsBasis = _.split(s, '@')[0];
  58. const [ firstWord, secondWord ] = initialsBasis.split(wordSplitRegex);
  59. return getFirstGraphemeUpper(firstWord) + getFirstGraphemeUpper(secondWord);
  60. }