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

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