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.0KB

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