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

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