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 2.1KB

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