您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Avatar.native.js 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. const assignState = !this.state;
  71. if (prevURI !== nextURI || assignState) {
  72. const nextState = {
  73. backgroundColor: this._getBackgroundColor(nextProps),
  74. /**
  75. * The source of the {@link Image} which is the actual
  76. * representation of this {@link Avatar}. The state
  77. * {@code source} was explicitly introduced in order to reduce
  78. * unnecessary renders.
  79. *
  80. * @type {{
  81. * uri: string
  82. * }}
  83. */
  84. source: _DEFAULT_SOURCE
  85. };
  86. if (assignState) {
  87. this.state = nextState;
  88. } else {
  89. this.setState(nextState);
  90. }
  91. // XXX @lyubomir: My logic for the character # bellow is as follows:
  92. // - Technically, URI is supposed to start with a scheme and scheme
  93. // cannot contain the character #.
  94. // - Technically, the character # in URI signals the start of the
  95. // fragment/hash.
  96. // - Technically, the fragment/hash does not imply a retrieval
  97. // action.
  98. // - Practically, the fragment/hash does not always mandate a
  99. // retrieval action. For example, an HTML anchor with an href that
  100. // starts with the character # does not cause a Web browser to
  101. // initiate a retrieval action.
  102. // So I'll use the character # at the start of URI to not initiate
  103. // an image retrieval action.
  104. if (nextURI && !nextURI.startsWith('#')) {
  105. const nextSource = { uri: nextURI };
  106. const 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. // Wait for the source/URI to load.
  117. if (ImageCache) {
  118. ImageCache.get().on(
  119. nextSource,
  120. observer,
  121. /* immutable */ true);
  122. } else if (assignState) {
  123. this.state = {
  124. ...this.state,
  125. source: nextSource
  126. };
  127. } else {
  128. observer();
  129. }
  130. }
  131. }
  132. }
  133. /**
  134. * Notifies this <tt>Component</tt> that it will be unmounted and destroyed
  135. * and, most importantly, that it should no longer call
  136. * {@link #setState(Object)}. <tt>Avatar</tt> needs it because it downloads
  137. * images via {@link ImageCache} which will asynchronously notify about
  138. * success.
  139. *
  140. * @inheritdoc
  141. * @returns {void}
  142. */
  143. componentWillUnmount() {
  144. this._unmounted = true;
  145. }
  146. /**
  147. * Computes a hash over the URI and returns a HSL background color. We use
  148. * 75% as lightness, for nice pastel style colors.
  149. *
  150. * @param {Object} props - The read-only React <tt>Component</tt> props from
  151. * which the background color is to be generated.
  152. * @private
  153. * @returns {string} - The HSL CSS property.
  154. */
  155. _getBackgroundColor({ uri }) {
  156. if (!uri) {
  157. // @lyubomir: I'm leaving @saghul's implementation which picks up a
  158. // random color bellow so that we have it in the source code in
  159. // case we decide to use it in the future. However, I think at the
  160. // time of this writing that the randomness reduces the
  161. // predictability which React is supposed to bring to our app.
  162. return ColorPalette.white;
  163. }
  164. let hash = 0;
  165. if (typeof uri === 'string') {
  166. /* eslint-disable no-bitwise */
  167. for (let i = 0; i < uri.length; i++) {
  168. hash = uri.charCodeAt(i) + ((hash << 5) - hash);
  169. hash |= 0; // Convert to 32-bit integer
  170. }
  171. /* eslint-enable no-bitwise */
  172. } else {
  173. // @saghul: If we have no URI yet, we have no data to hash from. So
  174. // use a random value.
  175. hash = Math.floor(Math.random() * 360);
  176. }
  177. return `hsl(${hash % 360}, 100%, 75%)`;
  178. }
  179. /**
  180. * Implements React's {@link Component#render()}.
  181. *
  182. * @inheritdoc
  183. */
  184. render() {
  185. // Propagate all props of this Avatar but the ones consumed by this
  186. // Avatar to the Image it renders.
  187. const {
  188. /* eslint-disable no-unused-vars */
  189. // The following are forked in state:
  190. uri: forked0,
  191. /* eslint-enable no-unused-vars */
  192. style,
  193. ...props
  194. } = this.props;
  195. const {
  196. backgroundColor,
  197. source
  198. } = this.state;
  199. // If we're rendering the _DEFAULT_SOURCE, then we want to do some
  200. // additional fu like having automagical colors generated per
  201. // participant, transparency to make the intermediate state while
  202. // downloading the remote image a little less "in your face", etc.
  203. let styleWithBackgroundColor;
  204. if (source === _DEFAULT_SOURCE && backgroundColor) {
  205. styleWithBackgroundColor = {
  206. ...style,
  207. backgroundColor,
  208. // FIXME @lyubomir: Without the opacity bellow I feel like the
  209. // avatar colors are too strong. Besides, we use opacity for the
  210. // ToolbarButtons. That's where I copied the value from and we
  211. // may want to think about "standardizing" the opacity in the
  212. // app in a way similar to ColorPalette.
  213. opacity: 0.1,
  214. overflow: 'hidden'
  215. };
  216. }
  217. // If we're styling with backgroundColor, we need to wrap the Image in a
  218. // View because of a bug in React Native for Android:
  219. // https://github.com/facebook/react-native/issues/3198
  220. let imageStyle;
  221. let viewStyle;
  222. if (styleWithBackgroundColor) {
  223. if (Platform.OS === 'android') {
  224. imageStyle = style;
  225. viewStyle = styleWithBackgroundColor;
  226. } else {
  227. imageStyle = styleWithBackgroundColor;
  228. }
  229. } else {
  230. imageStyle = style;
  231. }
  232. let element = React.createElement(CachedImage, {
  233. ...props,
  234. resizeMode: 'contain',
  235. source,
  236. style: imageStyle
  237. });
  238. if (viewStyle) {
  239. element = React.createElement(View, { style: viewStyle }, element);
  240. }
  241. return element;
  242. }
  243. }