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.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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<string>} 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).filter(Boolean);
  59. return getFirstGraphemeUpper(firstWord) + getFirstGraphemeUpper(secondWord);
  60. }
  61. /**
  62. * Checks if the passed URL should be loaded with CORS.
  63. *
  64. * @param {string} url - The URL.
  65. * @param {Array<string>} corsURLs - The URL pattern that matches a URL that needs to be handled with CORS.
  66. * @returns {void}
  67. */
  68. export function isCORSAvatarURL(url: string | any = '', corsURLs: Array<string> = []) {
  69. return corsURLs.some(pattern => url.startsWith(pattern));
  70. }