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

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