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.

Avatar.tsx 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import React, { PureComponent } from 'react';
  2. import { connect } from 'react-redux';
  3. import { IReduxState } from '../../../app/types';
  4. import { IconUser } from '../../icons/svg';
  5. import { getParticipantById } from '../../participants/functions';
  6. import { IParticipant } from '../../participants/types';
  7. import { getAvatarColor, getInitials, isCORSAvatarURL } from '../functions';
  8. import { IAvatarProps as AbstractProps } from '../types';
  9. import { StatelessAvatar } from './';
  10. export interface IProps {
  11. /**
  12. * The URL patterns for URLs that needs to be handled with CORS.
  13. */
  14. _corsAvatarURLs?: Array<string>;
  15. /**
  16. * Custom avatar backgrounds from branding.
  17. */
  18. _customAvatarBackgrounds?: Array<string>;
  19. /**
  20. * The string we base the initials on (this is generated from a list of precedences).
  21. */
  22. _initialsBase?: string;
  23. /**
  24. * An URL that we validated that it can be loaded.
  25. */
  26. _loadableAvatarUrl?: string;
  27. /**
  28. * Indicates whether _loadableAvatarUrl should use CORS or not.
  29. */
  30. _loadableAvatarUrlUseCORS?: boolean;
  31. /**
  32. * A prop to maintain compatibility with web.
  33. */
  34. className?: string;
  35. /**
  36. * A string to override the initials to generate a color of. This is handy if you don't want to make
  37. * the background color match the string that the initials are generated from.
  38. */
  39. colorBase?: string;
  40. /**
  41. * Display name of the entity to render an avatar for (if any). This is handy when we need
  42. * an avatar for a non-participant entity (e.g. A recent list item).
  43. */
  44. displayName?: string;
  45. /**
  46. * Whether or not to update the background color of the avatar.
  47. */
  48. dynamicColor?: boolean;
  49. /**
  50. * ID of the element, if any.
  51. */
  52. id?: string;
  53. /**
  54. * The ID of the participant to render an avatar for (if it's a participant avatar).
  55. */
  56. participantId?: string;
  57. /**
  58. * The size of the avatar.
  59. */
  60. size?: number;
  61. /**
  62. * One of the expected status strings (e.g. 'available') to render a badge on the avatar, if necessary.
  63. */
  64. status?: string;
  65. /**
  66. * TestId of the element, if any.
  67. */
  68. testId?: string;
  69. /**
  70. * URL of the avatar, if any.
  71. */
  72. url?: string;
  73. /**
  74. * Indicates whether to load the avatar using CORS or not.
  75. */
  76. useCORS?: boolean;
  77. }
  78. interface IState {
  79. avatarFailed: boolean;
  80. isUsingCORS: boolean;
  81. }
  82. export const DEFAULT_SIZE = 65;
  83. /**
  84. * Implements a class to render avatars in the app.
  85. */
  86. class Avatar<P extends IProps> extends PureComponent<P, IState> {
  87. /**
  88. * Default values for {@code Avatar} component's properties.
  89. *
  90. * @static
  91. */
  92. static defaultProps = {
  93. dynamicColor: true
  94. };
  95. /**
  96. * Instantiates a new {@code Component}.
  97. *
  98. * @inheritdoc
  99. */
  100. constructor(props: P) {
  101. super(props);
  102. const {
  103. _corsAvatarURLs,
  104. url,
  105. useCORS
  106. } = props;
  107. this.state = {
  108. avatarFailed: false,
  109. isUsingCORS: Boolean(useCORS) || Boolean(url && isCORSAvatarURL(url, _corsAvatarURLs))
  110. };
  111. this._onAvatarLoadError = this._onAvatarLoadError.bind(this);
  112. }
  113. /**
  114. * Implements {@code Component#componentDidUpdate}.
  115. *
  116. * @inheritdoc
  117. */
  118. componentDidUpdate(prevProps: P) {
  119. const { _corsAvatarURLs, url } = this.props;
  120. if (prevProps.url !== url) {
  121. // URI changed, so we need to try to fetch it again.
  122. // Eslint doesn't like this statement, but based on the React doc, it's safe if it's
  123. // wrapped in a condition: https://reactjs.org/docs/react-component.html#componentdidupdate
  124. // eslint-disable-next-line react/no-did-update-set-state
  125. this.setState({
  126. avatarFailed: false,
  127. isUsingCORS: Boolean(this.props.useCORS) || Boolean(url && isCORSAvatarURL(url, _corsAvatarURLs))
  128. });
  129. }
  130. }
  131. /**
  132. * Implements {@code Componenr#render}.
  133. *
  134. * @inheritdoc
  135. */
  136. render() {
  137. const {
  138. _customAvatarBackgrounds,
  139. _initialsBase,
  140. _loadableAvatarUrl,
  141. _loadableAvatarUrlUseCORS,
  142. className,
  143. colorBase,
  144. dynamicColor,
  145. id,
  146. size,
  147. status,
  148. testId,
  149. url
  150. } = this.props;
  151. const { avatarFailed, isUsingCORS } = this.state;
  152. const avatarProps: AbstractProps & {
  153. className?: string;
  154. iconUser?: any;
  155. id?: string;
  156. status?: string;
  157. testId?: string;
  158. url?: string;
  159. useCORS?: boolean;
  160. } = {
  161. className,
  162. color: undefined,
  163. id,
  164. initials: undefined,
  165. onAvatarLoadError: undefined,
  166. onAvatarLoadErrorParams: undefined,
  167. size,
  168. status,
  169. testId,
  170. url: undefined,
  171. useCORS: isUsingCORS
  172. };
  173. // _loadableAvatarUrl is validated that it can be loaded, but uri (if present) is not, so
  174. // we still need to do a check for that. And an explicitly provided URI is higher priority than
  175. // an avatar URL anyhow.
  176. const useReduxLoadableAvatarURL = avatarFailed || !url;
  177. const effectiveURL = useReduxLoadableAvatarURL ? _loadableAvatarUrl : url;
  178. if (effectiveURL) {
  179. avatarProps.onAvatarLoadError = this._onAvatarLoadError;
  180. if (useReduxLoadableAvatarURL) {
  181. avatarProps.onAvatarLoadErrorParams = { dontRetry: true };
  182. avatarProps.useCORS = _loadableAvatarUrlUseCORS;
  183. }
  184. avatarProps.url = effectiveURL;
  185. }
  186. const initials = getInitials(_initialsBase);
  187. if (initials) {
  188. if (dynamicColor) {
  189. avatarProps.color = getAvatarColor(colorBase || _initialsBase, _customAvatarBackgrounds ?? []);
  190. }
  191. avatarProps.initials = initials;
  192. }
  193. if (navigator.product !== 'ReactNative') {
  194. avatarProps.iconUser = IconUser;
  195. }
  196. return (
  197. <StatelessAvatar
  198. { ...avatarProps } />
  199. );
  200. }
  201. /**
  202. * Callback to handle the error while loading of the avatar URI.
  203. *
  204. * @param {Object} params - An object with parameters.
  205. * @param {boolean} params.dontRetry - If false we will retry to load the Avatar with different CORS mode.
  206. * @returns {void}
  207. */
  208. _onAvatarLoadError(params: { dontRetry?: boolean; } = {}) {
  209. const { dontRetry = false } = params;
  210. if (Boolean(this.props.useCORS) === this.state.isUsingCORS && !dontRetry) {
  211. // try different mode of loading the avatar.
  212. this.setState({
  213. isUsingCORS: !this.state.isUsingCORS
  214. });
  215. } else {
  216. // we already have tried loading the avatar with and without CORS and it failed.
  217. this.setState({
  218. avatarFailed: true
  219. });
  220. }
  221. }
  222. }
  223. /**
  224. * Maps part of the Redux state to the props of this component.
  225. *
  226. * @param {Object} state - The Redux state.
  227. * @param {IProps} ownProps - The own props of the component.
  228. * @returns {IProps}
  229. */
  230. export function _mapStateToProps(state: IReduxState, ownProps: IProps) {
  231. const { colorBase, displayName, participantId } = ownProps;
  232. const _participant: IParticipant | undefined = participantId ? getParticipantById(state, participantId) : undefined;
  233. const _initialsBase = _participant?.name ?? displayName;
  234. const { corsAvatarURLs } = state['features/base/config'];
  235. return {
  236. _customAvatarBackgrounds: state['features/dynamic-branding'].avatarBackgrounds,
  237. _corsAvatarURLs: corsAvatarURLs,
  238. _initialsBase,
  239. _loadableAvatarUrl: _participant?.loadableAvatarUrl,
  240. _loadableAvatarUrlUseCORS: _participant?.loadableAvatarUrlUseCORS,
  241. colorBase
  242. };
  243. }
  244. export default connect(_mapStateToProps)(Avatar);