UserPicture.jsx 1.7 KB

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