UserPicture.jsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import React from 'react';
  2. import md5 from 'md5';
  3. import PropTypes from 'prop-types';
  4. const DEFAULT_IMAGE = '/images/icons/user.svg';
  5. // TODO UserComponent?
  6. export default class UserPicture extends React.Component {
  7. getUserPicture(user) {
  8. // gravatar
  9. if (user.isGravatarEnabled === true) {
  10. return this.generateGravatarSrc(user);
  11. }
  12. // uploaded image
  13. if (user.image != null) {
  14. return user.image;
  15. }
  16. if (user.imageAttachment != null) {
  17. return user.imageAttachment.filePathProxied;
  18. }
  19. return DEFAULT_IMAGE;
  20. }
  21. generateGravatarSrc(user) {
  22. const email = user.email || '';
  23. const hash = md5(email.trim().toLowerCase());
  24. return `https://gravatar.com/avatar/${hash}`;
  25. }
  26. getClassName() {
  27. const className = ['img-circle', 'picture'];
  28. // size
  29. if (this.props.size) {
  30. className.push(`picture-${this.props.size}`);
  31. }
  32. return className.join(' ');
  33. }
  34. renderForNull() {
  35. return (
  36. <img
  37. src={DEFAULT_IMAGE}
  38. alt="someone"
  39. className={this.getClassName()}
  40. />
  41. );
  42. }
  43. render() {
  44. const user = this.props.user;
  45. if (user == null) {
  46. return this.renderForNull();
  47. }
  48. const imgElem = (
  49. <img
  50. src={this.getUserPicture(user)}
  51. alt={user.username}
  52. className={this.getClassName()}
  53. />
  54. );
  55. return (
  56. (this.props.withoutLink)
  57. ? <span>{imgElem}</span>
  58. : <a href={`/user/${user.username}`}>{imgElem}</a>
  59. );
  60. }
  61. }
  62. UserPicture.propTypes = {
  63. user: PropTypes.object,
  64. size: PropTypes.string,
  65. withoutLink: PropTypes.bool,
  66. };
  67. UserPicture.defaultProps = {
  68. size: null,
  69. };