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.native.js 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import PropTypes from 'prop-types';
  2. import React, { Component } from 'react';
  3. import { View } from 'react-native';
  4. import { CachedImage, ImageCache } from '../../../mobile/image-cache';
  5. import { Platform } from '../../react';
  6. import { ColorPalette } from '../../styles';
  7. /**
  8. * The default image/source to be used in case none is specified or the
  9. * specified one fails to load.
  10. *
  11. * XXX The relative path to the default/stock (image) file is defined by the
  12. * <tt>const</tt> <tt>DEFAULT_AVATAR_RELATIVE_PATH</tt>. Unfortunately, the
  13. * packager of React Native cannot deal with it early enough for the following
  14. * <tt>require</tt> to succeed at runtime. Anyway, be sure to synchronize the
  15. * relative path on Web and mobile for the purposes of consistency.
  16. *
  17. * @private
  18. * @type {string}
  19. */
  20. const _DEFAULT_SOURCE = require('../../../../../images/avatar.png');
  21. /**
  22. * Implements an avatar as a React Native/mobile {@link Component}.
  23. */
  24. export default class Avatar extends Component {
  25. /**
  26. * Avatar component's property types.
  27. *
  28. * @static
  29. */
  30. static propTypes = {
  31. /**
  32. * The optional style to add to the {@link Avatar} in order to customize
  33. * its base look (and feel).
  34. */
  35. style: PropTypes.object,
  36. /**
  37. * The URI of the {@link Avatar}.
  38. *
  39. * @type {string}
  40. */
  41. uri: PropTypes.string
  42. };
  43. /**
  44. * Initializes a new Avatar instance.
  45. *
  46. * @param {Object} props - The read-only React Component props with which
  47. * the new instance is to be initialized.
  48. */
  49. constructor(props) {
  50. super(props);
  51. // Fork (in Facebook/React speak) the prop uri because Image will
  52. // receive it through a source object. Additionally, other props may be
  53. // forked as well.
  54. this.componentWillReceiveProps(props);
  55. }
  56. /**
  57. * Notifies this mounted React Component that it will receive new props.
  58. * Forks (in Facebook/React speak) the prop {@code uri} because
  59. * {@link Image} will receive it through a {@code source} object.
  60. * Additionally, other props may be forked as well.
  61. *
  62. * @inheritdoc
  63. * @param {Object} nextProps - The read-only React Component props that this
  64. * instance will receive.
  65. * @returns {void}
  66. */
  67. componentWillReceiveProps(nextProps) {
  68. // uri
  69. const prevURI = this.props && this.props.uri;
  70. const nextURI = nextProps && nextProps.uri;
  71. const assignState = !this.state;
  72. if (prevURI !== nextURI || assignState) {
  73. const nextState = {
  74. backgroundColor: this._getBackgroundColor(nextProps),
  75. /**
  76. * The source of the {@link Image} which is the actual
  77. * representation of this {@link Avatar}. The state
  78. * {@code source} was explicitly introduced in order to reduce
  79. * unnecessary renders.
  80. *
  81. * @type {{
  82. * uri: string
  83. * }}
  84. */
  85. source: _DEFAULT_SOURCE
  86. };
  87. if (assignState) {
  88. this.state = nextState;
  89. } else {
  90. this.setState(nextState);
  91. }
  92. // XXX @lyubomir: My logic for the character # bellow is as follows:
  93. // - Technically, URI is supposed to start with a scheme and scheme
  94. // cannot contain the character #.
  95. // - Technically, the character # in URI signals the start of the
  96. // fragment/hash.
  97. // - Technically, the fragment/hash does not imply a retrieval
  98. // action.
  99. // - Practically, the fragment/hash does not always mandate a
  100. // retrieval action. For example, an HTML anchor with an href that
  101. // starts with the character # does not cause a Web browser to
  102. // initiate a retrieval action.
  103. // So I'll use the character # at the start of URI to not initiate
  104. // an image retrieval action.
  105. if (nextURI && !nextURI.startsWith('#')) {
  106. const nextSource = { uri: nextURI };
  107. const observer = () => {
  108. this._unmounted || this.setState((prevState, props) => {
  109. if (props.uri === nextURI
  110. && (!prevState.source
  111. || prevState.source.uri !== nextURI)) {
  112. return { source: nextSource };
  113. }
  114. return {};
  115. });
  116. };
  117. // Wait for the source/URI to load.
  118. if (ImageCache) {
  119. ImageCache.get().on(
  120. nextSource,
  121. observer,
  122. /* immutable */ true);
  123. } else if (assignState) {
  124. this.state = {
  125. ...this.state,
  126. source: nextSource
  127. };
  128. } else {
  129. observer();
  130. }
  131. }
  132. }
  133. }
  134. /**
  135. * Notifies this <tt>Component</tt> that it will be unmounted and destroyed
  136. * and, most importantly, that it should no longer call
  137. * {@link #setState(Object)}. <tt>Avatar</tt> needs it because it downloads
  138. * images via {@link ImageCache} which will asynchronously notify about
  139. * success.
  140. *
  141. * @inheritdoc
  142. * @returns {void}
  143. */
  144. componentWillUnmount() {
  145. this._unmounted = true;
  146. }
  147. /**
  148. * Computes a hash over the URI and returns a HSL background color. We use
  149. * 75% as lightness, for nice pastel style colors.
  150. *
  151. * @param {Object} props - The read-only React <tt>Component</tt> props from
  152. * which the background color is to be generated.
  153. * @private
  154. * @returns {string} - The HSL CSS property.
  155. */
  156. _getBackgroundColor({ uri }) {
  157. if (!uri) {
  158. // @lyubomir: I'm leaving @saghul's implementation which picks up a
  159. // random color bellow so that we have it in the source code in
  160. // case we decide to use it in the future. However, I think at the
  161. // time of this writing that the randomness reduces the
  162. // predictability which React is supposed to bring to our app.
  163. return ColorPalette.white;
  164. }
  165. let hash = 0;
  166. if (typeof uri === 'string') {
  167. /* eslint-disable no-bitwise */
  168. for (let i = 0; i < uri.length; i++) {
  169. hash = uri.charCodeAt(i) + ((hash << 5) - hash);
  170. hash |= 0; // Convert to 32-bit integer
  171. }
  172. /* eslint-enable no-bitwise */
  173. } else {
  174. // @saghul: If we have no URI yet, we have no data to hash from. So
  175. // use a random value.
  176. hash = Math.floor(Math.random() * 360);
  177. }
  178. return `hsl(${hash % 360}, 100%, 75%)`;
  179. }
  180. /**
  181. * Implements React's {@link Component#render()}.
  182. *
  183. * @inheritdoc
  184. */
  185. render() {
  186. // Propagate all props of this Avatar but the ones consumed by this
  187. // Avatar to the Image it renders.
  188. const {
  189. /* eslint-disable no-unused-vars */
  190. // The following are forked in state:
  191. uri: forked0,
  192. /* eslint-enable no-unused-vars */
  193. style,
  194. ...props
  195. } = this.props;
  196. const {
  197. backgroundColor,
  198. source
  199. } = this.state;
  200. // If we're rendering the _DEFAULT_SOURCE, then we want to do some
  201. // additional fu like having automagical colors generated per
  202. // participant, transparency to make the intermediate state while
  203. // downloading the remote image a little less "in your face", etc.
  204. let styleWithBackgroundColor;
  205. if (source === _DEFAULT_SOURCE && backgroundColor) {
  206. styleWithBackgroundColor = {
  207. ...style,
  208. backgroundColor,
  209. // FIXME @lyubomir: Without the opacity bellow I feel like the
  210. // avatar colors are too strong. Besides, we use opacity for the
  211. // ToolbarButtons. That's where I copied the value from and we
  212. // may want to think about "standardizing" the opacity in the
  213. // app in a way similar to ColorPalette.
  214. opacity: 0.1,
  215. overflow: 'hidden'
  216. };
  217. }
  218. // If we're styling with backgroundColor, we need to wrap the Image in a
  219. // View because of a bug in React Native for Android:
  220. // https://github.com/facebook/react-native/issues/3198
  221. let imageStyle;
  222. let viewStyle;
  223. if (styleWithBackgroundColor) {
  224. if (Platform.OS === 'android') {
  225. imageStyle = style;
  226. viewStyle = styleWithBackgroundColor;
  227. } else {
  228. imageStyle = styleWithBackgroundColor;
  229. }
  230. } else {
  231. imageStyle = style;
  232. }
  233. let element = React.createElement(CachedImage, {
  234. ...props,
  235. resizeMode: 'contain',
  236. source,
  237. style: imageStyle
  238. });
  239. if (viewStyle) {
  240. element = React.createElement(View, { style: viewStyle }, element);
  241. }
  242. return element;
  243. }
  244. }