UserPicture.jsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { userPageRoot } from '@commons/util/path-utils';
  4. import { UncontrolledTooltip } from 'reactstrap';
  5. const DEFAULT_IMAGE = '/images/icons/user.svg';
  6. // TODO UserComponent?
  7. export default class UserPicture extends React.Component {
  8. getClassName() {
  9. const className = ['rounded-circle', 'picture'];
  10. // size
  11. if (this.props.size) {
  12. className.push(`picture-${this.props.size}`);
  13. }
  14. return className.join(' ');
  15. }
  16. renderForNull() {
  17. return (
  18. <img
  19. src={DEFAULT_IMAGE}
  20. alt="someone"
  21. className={this.getClassName()}
  22. />
  23. );
  24. }
  25. RootElmWithoutLink = (props) => {
  26. return <span {...props}>{props.children}</span>;
  27. }
  28. RootElmWithLink = (props) => {
  29. const { user } = this.props;
  30. const href = userPageRoot(user);
  31. return <a href={href} {...props}>{props.children}</a>;
  32. }
  33. withTooltip = (RootElm) => {
  34. const { user } = this.props;
  35. const id = `user-picture-${Math.random().toString(32).substring(2)}`;
  36. return props => (
  37. <>
  38. <RootElm id={id}>{props.children}</RootElm>
  39. <UncontrolledTooltip placement="bottom" target={id} delay={0} fade={false}>
  40. @{user.username}<br />
  41. {user.name}
  42. </UncontrolledTooltip>
  43. </>
  44. );
  45. }
  46. render() {
  47. const user = this.props.user;
  48. if (user == null) {
  49. return this.renderForNull();
  50. }
  51. const { noLink, noTooltip } = this.props;
  52. // determine RootElm
  53. let RootElm = noLink ? this.RootElmWithoutLink : this.RootElmWithLink;
  54. if (!noTooltip) {
  55. RootElm = this.withTooltip(RootElm);
  56. }
  57. const userPictureSrc = user.imageUrlCached || DEFAULT_IMAGE;
  58. return (
  59. <RootElm>
  60. <img
  61. src={userPictureSrc}
  62. alt={user.username}
  63. className={this.getClassName()}
  64. />
  65. </RootElm>
  66. );
  67. }
  68. }
  69. UserPicture.propTypes = {
  70. user: PropTypes.object,
  71. size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
  72. noLink: PropTypes.bool,
  73. noTooltip: PropTypes.bool,
  74. };
  75. UserPicture.defaultProps = {
  76. size: null,
  77. noLink: false,
  78. noTooltip: false,
  79. };