BookmarkButtons.tsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import React, { FC, useState } from 'react';
  2. import { Types } from 'mongoose';
  3. import { UncontrolledTooltip, Popover, PopoverBody } from 'reactstrap';
  4. import { useTranslation } from 'react-i18next';
  5. import UserPictureList from './User/UserPictureList';
  6. import { toastError } from '~/client/util/apiNotification';
  7. import { useIsGuestUser } from '~/stores/context';
  8. import { useSWRxBookmarksInfo } from '~/stores/bookmarks';
  9. import { apiv3Put } from '~/client/util/apiv3-client';
  10. interface Props {
  11. pageId: Types.ObjectId
  12. }
  13. const BookmarkButton: FC<Props> = (props: Props) => {
  14. const { t } = useTranslation();
  15. const { pageId } = props;
  16. const [isPopoverOpen, setIsPopoverOpen] = useState(false);
  17. const { data: isGuestUser } = useIsGuestUser();
  18. const { data: bookmarksInfo, mutate } = useSWRxBookmarksInfo(pageId);
  19. const isBookmarked = bookmarksInfo?.isBookmarked != null ? bookmarksInfo.isBookmarked : false;
  20. const sumOfBookmarks = bookmarksInfo?.sumOfBookmarks != null ? bookmarksInfo.sumOfBookmarks : 0;
  21. const bookmarkedUsers = bookmarksInfo?.bookmarkedUsers != null ? bookmarksInfo.bookmarkedUsers : [];
  22. const togglePopover = () => {
  23. setIsPopoverOpen(!isPopoverOpen);
  24. };
  25. const handleClick = async() => {
  26. if (isGuestUser) {
  27. return;
  28. }
  29. try {
  30. const res = await apiv3Put('/bookmarks', { pageId, bool: !isBookmarked });
  31. if (res) {
  32. mutate();
  33. }
  34. }
  35. catch (err) {
  36. toastError(err);
  37. }
  38. };
  39. return (
  40. <div className="btn-group" role="group" aria-label="Bookmark buttons">
  41. <button
  42. type="button"
  43. id="bookmark-button"
  44. onClick={handleClick}
  45. className={`btn btn-bookmark border-0
  46. ${isBookmarked ? 'active' : ''} ${isGuestUser ? 'disabled' : ''}`}
  47. >
  48. <i className="icon-star"></i>
  49. </button>
  50. {isGuestUser && (
  51. <UncontrolledTooltip placement="top" target="bookmark-button" fade={false}>
  52. {t('Not available for guest')}
  53. </UncontrolledTooltip>
  54. )}
  55. <button type="button" id="po-total-bookmarks" className={`btn btn-bookmark border-0 total-bookmarks ${isBookmarked ? 'active' : ''}`}>
  56. {sumOfBookmarks}
  57. </button>
  58. <Popover placement="bottom" isOpen={isPopoverOpen} target="po-total-bookmarks" toggle={togglePopover} trigger="legacy">
  59. <PopoverBody className="seen-user-popover">
  60. <div className="px-2 text-right user-list-content text-truncate text-muted">
  61. {bookmarkedUsers.length ? <UserPictureList users={bookmarkedUsers} /> : t('No users have bookmarked yet')}
  62. </div>
  63. </PopoverBody>
  64. </Popover>
  65. </div>
  66. );
  67. };
  68. export default BookmarkButton;