Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Avatar.tsx 8.2KB

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