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

Avatar.native.js 9.5KB

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