jiti-meet/react/features/base/avatar/functions.js

84 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-06-26 14:08:23 +00:00
// @flow
import GraphemeSplitter from 'grapheme-splitter';
2019-06-26 14:08:23 +00:00
import _ from 'lodash';
const AVATAR_COLORS = [
'#6A50D3',
'#FF9B42',
'#DF486F',
'#73348C',
'#B23683',
'#F96E57',
'#4380E2',
'#2AA076',
'#00A8B3'
2019-06-26 14:08:23 +00:00
];
const wordSplitRegex = (/\s+|\.+|_+|;+|-+|,+|\|+|\/+|\\+|"+|'+|\(+|\)+|#+|&+/);
const splitter = new GraphemeSplitter();
2019-06-26 14:08:23 +00:00
/**
* Generates the background color of an initials based avatar.
*
* @param {string?} initials - The initials of the avatar.
* @param {Array<string>} customAvatarBackgrounds - Custom avatar background values.
2019-06-26 14:08:23 +00:00
* @returns {string}
*/
export function getAvatarColor(initials: ?string, customAvatarBackgrounds: Array<string>) {
const hasCustomAvatarBackgronds = customAvatarBackgrounds && customAvatarBackgrounds.length;
const colorsBase = hasCustomAvatarBackgronds ? customAvatarBackgrounds : AVATAR_COLORS;
2019-06-26 14:08:23 +00:00
let colorIndex = 0;
if (initials) {
let nameHash = 0;
for (const s of initials) {
nameHash += s.codePointAt(0);
}
colorIndex = nameHash % colorsBase.length;
2019-06-26 14:08:23 +00:00
}
return colorsBase[colorIndex];
2019-06-26 14:08:23 +00:00
}
/**
* Returns the first grapheme from a word, uppercased.
*
* @param {string} word - The string to get grapheme from.
* @returns {string}
*/
function getFirstGraphemeUpper(word) {
if (!word?.length) {
return '';
}
return splitter.splitGraphemes(word)[0].toUpperCase();
}
2019-06-26 14:08:23 +00:00
/**
* Generates initials for a simple string.
*
* @param {string?} s - The string to generate initials for.
* @returns {string?}
*/
export function getInitials(s: ?string) {
// We don't want to use the domain part of an email address, if it is one
const initialsBasis = _.split(s, '@')[0];
const [ firstWord, secondWord ] = initialsBasis.split(wordSplitRegex).filter(Boolean);
2019-06-26 14:08:23 +00:00
return getFirstGraphemeUpper(firstWord) + getFirstGraphemeUpper(secondWord);
2019-06-26 14:08:23 +00:00
}
/**
2021-12-17 00:16:24 +00:00
* Checks if the passed URL should be loaded with CORS.
*
* @param {string} url - The URL.
2021-12-17 00:16:24 +00:00
* @param {Array<string>} corsURLs - The URL pattern that matches a URL that needs to be handled with CORS.
* @returns {void}
*/
2021-12-17 00:16:24 +00:00
export function isCORSAvatarURL(url: string | any = '', corsURLs: Array<string> = []) {
return corsURLs.some(pattern => url.startsWith(pattern));
}