UserPicture.jsx 1.4 KB

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