From 9e490990034cab5e954b561d80697baffafd4da5 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 11:20:57 -0300 Subject: [PATCH 01/16] refactor: create useBookmark() hook, used for bookmark and undo a bookmark --- src/api/hooks/index.ts | 1 + src/api/hooks/statuses/useBookmark.ts | 80 +++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 src/api/hooks/statuses/useBookmark.ts diff --git a/src/api/hooks/index.ts b/src/api/hooks/index.ts index 990dda57b..001eb6322 100644 --- a/src/api/hooks/index.ts +++ b/src/api/hooks/index.ts @@ -45,6 +45,7 @@ export { useUpdateGroupTag } from './groups/useUpdateGroupTag.ts'; // Statuses export { useBookmarks } from './statuses/useBookmarks.ts'; +export { useBookmark } from './statuses/useBookmark.ts'; // Streaming export { useUserStream } from './streaming/useUserStream.ts'; diff --git a/src/api/hooks/statuses/useBookmark.ts b/src/api/hooks/statuses/useBookmark.ts new file mode 100644 index 000000000..f0263a905 --- /dev/null +++ b/src/api/hooks/statuses/useBookmark.ts @@ -0,0 +1,80 @@ +import { importEntities } from 'soapbox/entity-store/actions.ts'; +import { Entities } from 'soapbox/entity-store/entities.ts'; +import { useTransaction } from 'soapbox/entity-store/hooks/index.ts'; +import { useApi } from 'soapbox/hooks/useApi.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useLoggedIn } from 'soapbox/hooks/useLoggedIn.ts'; +import { statusSchema } from 'soapbox/schemas/index.ts'; + +/** + * Bookmark and undo a bookmark, with optimistic update. + * + * https://docs.joinmastodon.org/methods/statuses/#bookmark + * POST /api/v1/statuses/:id/bookmark + * + * https://docs.joinmastodon.org/methods/statuses/#unbookmark + * POST /api/v1/statuses/:id/unbookmark + */ +function useBookmark() { + const api = useApi(); + const dispatch = useAppDispatch(); + const { isLoggedIn } = useLoggedIn(); + const { transaction } = useTransaction(); + + function bookmarkEffect(statusId: string) { + transaction({ + Statuses: { + [statusId]: (status) => ({ + ...status, + bookmarked: true, + }), + }, + }); + } + + function unbookmarkEffect(statusId: string) { + transaction({ + Statuses: { + [statusId]: (status) => ({ + ...status, + bookmarked: false, + }), + }, + }); + } + + async function bookmark(statusId: string) { + if (!isLoggedIn) return; + bookmarkEffect(statusId); + + try { + const response = await api.post(`/api/v1/statuses/${statusId}/bookmark`); + const result = statusSchema.safeParse(await response.json()); + if (result.success) { + dispatch(importEntities([result.data], Entities.STATUSES, 'bookmarks')); + } + } catch (e) { + unbookmarkEffect(statusId); + } + } + + async function unbookmark(statusId: string) { + if (!isLoggedIn) return; + unbookmarkEffect(statusId); + + try { + await api.post(`/api/v1/statuses/${statusId}/unbookmark`); + } catch (e) { + bookmarkEffect(statusId); + } + } + + return { + bookmark, + unbookmark, + bookmarkEffect, + unbookmarkEffect, + }; +} + +export { useBookmark }; \ No newline at end of file From a339bb93ea4cab2bb3f15b5decca7e82a7bc2b42 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 11:23:36 -0300 Subject: [PATCH 02/16] fix(legacy bookmark): add actionLabel in toast.success --- src/actions/interactions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/actions/interactions.ts b/src/actions/interactions.ts index 4c06276d7..e4faf11a6 100644 --- a/src/actions/interactions.ts +++ b/src/actions/interactions.ts @@ -368,7 +368,7 @@ const bookmark = (status: StatusEntity) => dispatch(bookmarkSuccess(status, response.data)); toast.success(messages.bookmarkAdded, { - actionLink: '/bookmarks', + actionLink: '/bookmarks/all', actionLabel: messages.view, }); }).catch(function(error) { dispatch(bookmarkFail(status, error)); From cfce081063960ac0b0087b4cb56c94758a82043d Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 18:27:08 -0300 Subject: [PATCH 03/16] fix: use useDismissEntity when undoing a bookmark --- src/api/hooks/statuses/useBookmark.ts | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/api/hooks/statuses/useBookmark.ts b/src/api/hooks/statuses/useBookmark.ts index f0263a905..23ffbcf5b 100644 --- a/src/api/hooks/statuses/useBookmark.ts +++ b/src/api/hooks/statuses/useBookmark.ts @@ -1,6 +1,7 @@ import { importEntities } from 'soapbox/entity-store/actions.ts'; import { Entities } from 'soapbox/entity-store/entities.ts'; -import { useTransaction } from 'soapbox/entity-store/hooks/index.ts'; +import { useDismissEntity, useTransaction } from 'soapbox/entity-store/hooks/index.ts'; +import { ExpandedEntitiesPath } from 'soapbox/entity-store/hooks/types.ts'; import { useApi } from 'soapbox/hooks/useApi.ts'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useLoggedIn } from 'soapbox/hooks/useLoggedIn.ts'; @@ -21,6 +22,15 @@ function useBookmark() { const { isLoggedIn } = useLoggedIn(); const { transaction } = useTransaction(); + type Success = { success: boolean } + + const path: ExpandedEntitiesPath = [Entities.STATUSES, 'bookmarks']; + + const { dismissEntity } = useDismissEntity(path, async (statusId: string) => { + const response = await api.post(`/api/v1/statuses/${statusId}/unbookmark`); + return response; + }); + function bookmarkEffect(statusId: string) { transaction({ Statuses: { @@ -43,8 +53,8 @@ function useBookmark() { }); } - async function bookmark(statusId: string) { - if (!isLoggedIn) return; + async function bookmark(statusId: string): Promise { + if (!isLoggedIn) return { success: false }; bookmarkEffect(statusId); try { @@ -53,19 +63,23 @@ function useBookmark() { if (result.success) { dispatch(importEntities([result.data], Entities.STATUSES, 'bookmarks')); } + return { success: true }; } catch (e) { unbookmarkEffect(statusId); + return { success: false }; } } - async function unbookmark(statusId: string) { - if (!isLoggedIn) return; + async function unbookmark(statusId: string): Promise { + if (!isLoggedIn) return { success: false }; unbookmarkEffect(statusId); try { - await api.post(`/api/v1/statuses/${statusId}/unbookmark`); + await dismissEntity(statusId); + return { success: true }; } catch (e) { bookmarkEffect(statusId); + return { success: false }; } } From 3aa6582b0902471f10588c9183d6240141bdbd34 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 19:27:27 -0300 Subject: [PATCH 04/16] refactor: toggleMuteStatus accepts pure Status rather than Legacy Immutable Status --- src/actions/statuses.ts | 3 ++- src/components/status-action-bar.tsx | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/actions/statuses.ts b/src/actions/statuses.ts index 8d00cf00b..3277e6402 100644 --- a/src/actions/statuses.ts +++ b/src/actions/statuses.ts @@ -1,3 +1,4 @@ +import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; import { isLoggedIn } from 'soapbox/utils/auth.ts'; import { getFeatures } from 'soapbox/utils/features.ts'; import { shouldHaveCard } from 'soapbox/utils/status.ts'; @@ -277,7 +278,7 @@ const unmuteStatus = (id: string) => }); }; -const toggleMuteStatus = (status: Status) => +const toggleMuteStatus = (status: StatusEntity) => (dispatch: AppDispatch, getState: () => RootState) => { if (status.muted) { dispatch(unmuteStatus(status.id)); diff --git a/src/components/status-action-bar.tsx b/src/components/status-action-bar.tsx index c269b3a36..28fd2f5ed 100644 --- a/src/components/status-action-bar.tsx +++ b/src/components/status-action-bar.tsx @@ -363,7 +363,7 @@ const StatusActionBar: React.FC = ({ }; const handleConversationMuteClick: React.EventHandler = (e) => { - dispatch(toggleMuteStatus(status)); + dispatch(toggleMuteStatus(status.toJS() as StatusEntity)); }; const handleCopy: React.EventHandler = (e) => { From 2f5781b0468b844b48a5c20537a1a49b6fda7c02 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 22:03:14 -0300 Subject: [PATCH 05/16] refactor: make BoostModal pure, and openModal 'BOOST' pure --- src/components/status-action-bar.tsx | 9 ++++++--- src/components/status.tsx | 9 ++++++--- src/features/event/components/event-header.tsx | 13 ++++++++----- .../notifications/components/notification.tsx | 14 ++++++++------ src/features/status/components/thread.tsx | 9 ++++++--- src/features/ui/components/modals/boost-modal.tsx | 8 +++----- 6 files changed, 37 insertions(+), 25 deletions(-) diff --git a/src/components/status-action-bar.tsx b/src/components/status-action-bar.tsx index 28fd2f5ed..03a41cd47 100644 --- a/src/components/status-action-bar.tsx +++ b/src/components/status-action-bar.tsx @@ -36,7 +36,7 @@ import { blockAccount } from 'soapbox/actions/accounts.ts'; import { launchChat } from 'soapbox/actions/chats.ts'; import { directCompose, mentionCompose, quoteCompose, replyCompose } from 'soapbox/actions/compose.ts'; import { editEvent } from 'soapbox/actions/events.ts'; -import { pinToGroup, toggleBookmark, toggleDislike, toggleFavourite, togglePin, toggleReblog, unpinFromGroup } from 'soapbox/actions/interactions.ts'; +import { pinToGroup, toggleBookmark, toggleDislike, toggleFavourite, togglePin, unpinFromGroup } from 'soapbox/actions/interactions.ts'; import { openModal } from 'soapbox/actions/modals.ts'; import { deleteStatusModal, toggleStatusSensitivityModal } from 'soapbox/actions/moderation.tsx'; import { initMuteModal } from 'soapbox/actions/mutes.ts'; @@ -53,6 +53,7 @@ import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useAppSelector } from 'soapbox/hooks/useAppSelector.ts'; import { useFeatures } from 'soapbox/hooks/useFeatures.ts'; import { useOwnAccount } from 'soapbox/hooks/useOwnAccount.ts'; +import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { useSettings } from 'soapbox/hooks/useSettings.ts'; import { GroupRoles } from 'soapbox/schemas/group-member.ts'; import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; @@ -174,6 +175,8 @@ const StatusActionBar: React.FC = ({ const isStaff = account ? account.staff : false; const isAdmin = account ? account.admin : false; + const { toggleReblog } = useReblog(); + if (!status) { return null; } @@ -232,11 +235,11 @@ const StatusActionBar: React.FC = ({ const handleReblogClick: React.EventHandler = e => { if (me) { - const modalReblog = () => dispatch(toggleReblog(status)); + const modalReblog = () => toggleReblog(status.id); if ((e && e.shiftKey) || !boostModal) { modalReblog(); } else { - dispatch(openModal('BOOST', { status, onReblog: modalReblog })); + dispatch(openModal('BOOST', { status: status.toJS(), onReblog: modalReblog })); } } else { onOpenUnauthorizedModal('REBLOG'); diff --git a/src/components/status.tsx b/src/components/status.tsx index ccde634b8..317a7295e 100644 --- a/src/components/status.tsx +++ b/src/components/status.tsx @@ -7,7 +7,7 @@ import { useIntl, FormattedMessage, defineMessages } from 'react-intl'; import { Link, useHistory } from 'react-router-dom'; import { mentionCompose, replyCompose } from 'soapbox/actions/compose.ts'; -import { toggleFavourite, toggleReblog } from 'soapbox/actions/interactions.ts'; +import { toggleFavourite } from 'soapbox/actions/interactions.ts'; import { openModal } from 'soapbox/actions/modals.ts'; import { toggleStatusHidden, unfilterStatus } from 'soapbox/actions/statuses.ts'; import TranslateButton from 'soapbox/components/translate-button.tsx'; @@ -19,6 +19,7 @@ import AccountContainer from 'soapbox/containers/account-container.tsx'; import QuotedStatus from 'soapbox/features/status/containers/quoted-status-container.tsx'; import { HotKeys } from 'soapbox/features/ui/components/hotkeys.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { useSettings } from 'soapbox/hooks/useSettings.ts'; import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; import { emojifyText } from 'soapbox/utils/emojify.tsx'; @@ -103,6 +104,8 @@ const Status: React.FC = (props) => { const filtered = (status.filtered.size || actualStatus.filtered.size) > 0; + const { toggleReblog } = useReblog(); + // Track height changes we know about to compensate scrolling. useEffect(() => { didShowCard.current = Boolean(!muted && !hidden && status?.card); @@ -166,11 +169,11 @@ const Status: React.FC = (props) => { }; const handleHotkeyBoost = (e?: KeyboardEvent): void => { - const modalReblog = () => dispatch(toggleReblog(actualStatus)); + const modalReblog = () => toggleReblog(actualStatus.id); if ((e && e.shiftKey) || !boostModal) { modalReblog(); } else { - dispatch(openModal('BOOST', { status: actualStatus, onReblog: modalReblog })); + dispatch(openModal('BOOST', { status: actualStatus.toJS(), onReblog: modalReblog })); } }; diff --git a/src/features/event/components/event-header.tsx b/src/features/event/components/event-header.tsx index 1a3d382d2..57aeff30e 100644 --- a/src/features/event/components/event-header.tsx +++ b/src/features/event/components/event-header.tsx @@ -29,7 +29,7 @@ import { blockAccount } from 'soapbox/actions/accounts.ts'; import { launchChat } from 'soapbox/actions/chats.ts'; import { directCompose, mentionCompose, quoteCompose } from 'soapbox/actions/compose.ts'; import { editEvent, fetchEventIcs } from 'soapbox/actions/events.ts'; -import { toggleBookmark, togglePin, toggleReblog } from 'soapbox/actions/interactions.ts'; +import { toggleBookmark, togglePin } from 'soapbox/actions/interactions.ts'; import { openModal } from 'soapbox/actions/modals.ts'; import { deleteStatusModal, toggleStatusSensitivityModal } from 'soapbox/actions/moderation.tsx'; import { initMuteModal } from 'soapbox/actions/mutes.ts'; @@ -47,6 +47,7 @@ import VerificationBadge from 'soapbox/components/verification-badge.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useFeatures } from 'soapbox/hooks/useFeatures.ts'; import { useOwnAccount } from 'soapbox/hooks/useOwnAccount.ts'; +import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { useSettings } from 'soapbox/hooks/useSettings.ts'; import copy from 'soapbox/utils/copy.ts'; import { download } from 'soapbox/utils/download.ts'; @@ -58,7 +59,7 @@ import EventActionButton from '../components/event-action-button.tsx'; import EventDate from '../components/event-date.tsx'; import type { Menu as MenuType } from 'soapbox/components/dropdown-menu/index.ts'; -import type { Status as StatusEntity } from 'soapbox/types/entities.ts'; +import type { Status as LegacyStatus } from 'soapbox/types/entities.ts'; const messages = defineMessages({ bannerHeader: { id: 'event.banner', defaultMessage: 'Event banner' }, @@ -92,7 +93,7 @@ const messages = defineMessages({ }); interface IEventHeader { - status?: StatusEntity; + status?: LegacyStatus; } const EventHeader: React.FC = ({ status }) => { @@ -106,6 +107,8 @@ const EventHeader: React.FC = ({ status }) => { const isStaff = ownAccount ? ownAccount.staff : false; const isAdmin = ownAccount ? ownAccount.admin : false; + const { toggleReblog } = useReblog(); + if (!status || !status.event) { return ( <> @@ -148,11 +151,11 @@ const EventHeader: React.FC = ({ status }) => { }; const handleReblogClick = () => { - const modalReblog = () => dispatch(toggleReblog(status)); + const modalReblog = () => toggleReblog(status.id); if (!boostModal) { modalReblog(); } else { - dispatch(openModal('BOOST', { status, onReblog: modalReblog })); + dispatch(openModal('BOOST', { status: status.toJS(), onReblog: modalReblog })); } }; diff --git a/src/features/notifications/components/notification.tsx b/src/features/notifications/components/notification.tsx index c912c3ba4..e245710bd 100644 --- a/src/features/notifications/components/notification.tsx +++ b/src/features/notifications/components/notification.tsx @@ -17,7 +17,7 @@ import { defineMessages, useIntl, IntlShape, MessageDescriptor, defineMessage, F import { Link, useHistory } from 'react-router-dom'; import { mentionCompose } from 'soapbox/actions/compose.ts'; -import { reblog, favourite, unreblog, unfavourite } from 'soapbox/actions/interactions.ts'; +import { favourite, unreblog, unfavourite } from 'soapbox/actions/interactions.ts'; import { patchMe } from 'soapbox/actions/me.ts'; import { openModal } from 'soapbox/actions/modals.ts'; import { getSettings } from 'soapbox/actions/settings.ts'; @@ -35,13 +35,14 @@ import { HotKeys } from 'soapbox/features/ui/components/hotkeys.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useAppSelector } from 'soapbox/hooks/useAppSelector.ts'; import { useInstance } from 'soapbox/hooks/useInstance.ts'; +import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { makeGetNotification } from 'soapbox/selectors/index.ts'; import toast from 'soapbox/toast.tsx'; import { emojifyText } from 'soapbox/utils/emojify.tsx'; import { NotificationType, validType } from 'soapbox/utils/notification.ts'; import type { ScrollPosition } from 'soapbox/components/status.tsx'; -import type { Account as AccountEntity, Status as StatusEntity, Notification as NotificationEntity } from 'soapbox/types/entities.ts'; +import type { Account as AccountEntity, Status as StatusLegacy, Notification as NotificationEntity } from 'soapbox/types/entities.ts'; const notificationForScreenReader = (intl: IntlShape, message: string, timestamp: Date) => { const output = [message]; @@ -204,7 +205,7 @@ interface INotification { notification: NotificationEntity; onMoveUp?: (notificationId: string) => void; onMoveDown?: (notificationId: string) => void; - onReblog?: (status: StatusEntity, e?: KeyboardEvent) => void; + onReblog?: (status: StatusLegacy, e?: KeyboardEvent) => void; getScrollPosition?: () => ScrollPosition | undefined; updateScrollBottom?: (bottom: number) => void; } @@ -221,6 +222,7 @@ const Notification: React.FC = (props) => { const history = useHistory(); const intl = useIntl(); const { instance } = useInstance(); + const { reblog } = useReblog(); const type = notification.type; const { account, status } = notification; @@ -277,10 +279,10 @@ const Notification: React.FC = (props) => { dispatch(unreblog(status)); } else { if (e?.shiftKey || !boostModal) { - dispatch(reblog(status)); + reblog(status.id); } else { - dispatch(openModal('BOOST', { status, onReblog: (status: StatusEntity) => { - dispatch(reblog(status)); + dispatch(openModal('BOOST', { status: status.toJS(), onReblog: (status: StatusLegacy) => { + reblog(status.id); } })); } } diff --git a/src/features/status/components/thread.tsx b/src/features/status/components/thread.tsx index bd0734098..16abb5430 100644 --- a/src/features/status/components/thread.tsx +++ b/src/features/status/components/thread.tsx @@ -7,7 +7,7 @@ import { useHistory } from 'react-router-dom'; import { type VirtuosoHandle } from 'react-virtuoso'; import { mentionCompose, replyCompose } from 'soapbox/actions/compose.ts'; -import { favourite, reblog, unfavourite, unreblog } from 'soapbox/actions/interactions.ts'; +import { favourite, unfavourite, unreblog } from 'soapbox/actions/interactions.ts'; import { openModal } from 'soapbox/actions/modals.ts'; import { getSettings } from 'soapbox/actions/settings.ts'; import { hideStatus, revealStatus } from 'soapbox/actions/statuses.ts'; @@ -20,6 +20,7 @@ import { HotKeys } from 'soapbox/features/ui/components/hotkeys.tsx'; import PendingStatus from 'soapbox/features/ui/components/pending-status.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useAppSelector } from 'soapbox/hooks/useAppSelector.ts'; +import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { useSettings } from 'soapbox/hooks/useSettings.ts'; import { RootState } from 'soapbox/store.ts'; import { type Account, type Status } from 'soapbox/types/entities.ts'; @@ -100,6 +101,8 @@ const Thread = (props: IThread) => { const isUnderReview = status?.visibility === 'self'; + const { reblog } = useReblog(); + const { ancestorsIds, descendantsIds } = useAppSelector((state) => { let ancestorsIds = ImmutableOrderedSet(); let descendantsIds = ImmutableOrderedSet(); @@ -149,7 +152,7 @@ const Thread = (props: IThread) => { const handleReplyClick = (status: Status) => dispatch(replyCompose(status)); - const handleModalReblog = (status: Status) => dispatch(reblog(status)); + const handleModalReblog = (status: Status) => reblog(status.id); const handleReblogClick = (status: Status, e?: React.MouseEvent) => { dispatch((_, getState) => { @@ -160,7 +163,7 @@ const Thread = (props: IThread) => { if ((e && e.shiftKey) || !boostModal) { handleModalReblog(status); } else { - dispatch(openModal('BOOST', { status, onReblog: handleModalReblog })); + dispatch(openModal('BOOST', { status: status.toJS(), onReblog: handleModalReblog })); } } }); diff --git a/src/features/ui/components/modals/boost-modal.tsx b/src/features/ui/components/modals/boost-modal.tsx index 730586dcd..1258bc65b 100644 --- a/src/features/ui/components/modals/boost-modal.tsx +++ b/src/features/ui/components/modals/boost-modal.tsx @@ -8,16 +8,14 @@ import Text from 'soapbox/components/ui/text.tsx'; import ReplyIndicator from 'soapbox/features/compose/components/reply-indicator.tsx'; import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; -import type { Status as LegacyStatus } from 'soapbox/types/entities.ts'; - const messages = defineMessages({ cancel_reblog: { id: 'status.cancel_reblog_private', defaultMessage: 'Un-repost' }, reblog: { id: 'status.reblog', defaultMessage: 'Repost' }, }); interface IBoostModal { - status: LegacyStatus; - onReblog: (status: LegacyStatus) => void; + status: StatusEntity; + onReblog: (status: StatusEntity) => void; onClose: () => void; } @@ -38,7 +36,7 @@ const BoostModal: React.FC = ({ status, onReblog, onClose }) => { confirmationText={intl.formatMessage(buttonText)} > - + {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */} From b2c22df02c1a74d4a68b89f4c2eb8b21db228597 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 22:25:44 -0300 Subject: [PATCH 06/16] refactor: finish PureStatus component by creating the remaining PureStatusActionBar component --- src/components/pure-status-action-bar.tsx | 880 ++++++++++++++++++++++ src/components/pure-status.tsx | 8 +- src/hooks/useDislike.ts | 31 + src/hooks/useInitReport.ts | 27 + src/hooks/usePin.ts | 31 + src/hooks/usePinGroup.ts | 24 + src/hooks/useQuoteCompose.ts | 17 + 7 files changed, 1012 insertions(+), 6 deletions(-) create mode 100644 src/components/pure-status-action-bar.tsx create mode 100644 src/hooks/useDislike.ts create mode 100644 src/hooks/useInitReport.ts create mode 100644 src/hooks/usePin.ts create mode 100644 src/hooks/usePinGroup.ts create mode 100644 src/hooks/useQuoteCompose.ts diff --git a/src/components/pure-status-action-bar.tsx b/src/components/pure-status-action-bar.tsx new file mode 100644 index 000000000..4f1312692 --- /dev/null +++ b/src/components/pure-status-action-bar.tsx @@ -0,0 +1,880 @@ +import alertTriangleIcon from '@tabler/icons/outline/alert-triangle.svg'; +import arrowsVerticalIcon from '@tabler/icons/outline/arrows-vertical.svg'; +import atIcon from '@tabler/icons/outline/at.svg'; +import banIcon from '@tabler/icons/outline/ban.svg'; +import bellOffIcon from '@tabler/icons/outline/bell-off.svg'; +import bellIcon from '@tabler/icons/outline/bell.svg'; +import boltIcon from '@tabler/icons/outline/bolt.svg'; +import bookmarkOffIcon from '@tabler/icons/outline/bookmark-off.svg'; +import bookmarkIcon from '@tabler/icons/outline/bookmark.svg'; +import clipboardCopyIcon from '@tabler/icons/outline/clipboard-copy.svg'; +import dotsIcon from '@tabler/icons/outline/dots.svg'; +import editIcon from '@tabler/icons/outline/edit.svg'; +import externalLinkIcon from '@tabler/icons/outline/external-link.svg'; +import flagIcon from '@tabler/icons/outline/flag.svg'; +import gavelIcon from '@tabler/icons/outline/gavel.svg'; +import heartIcon from '@tabler/icons/outline/heart.svg'; +import lockIcon from '@tabler/icons/outline/lock.svg'; +import mailIcon from '@tabler/icons/outline/mail.svg'; +import messageCircleIcon from '@tabler/icons/outline/message-circle.svg'; +import messagesIcon from '@tabler/icons/outline/messages.svg'; +import pencilIcon from '@tabler/icons/outline/pencil.svg'; +import pinIcon from '@tabler/icons/outline/pin.svg'; +import pinnedOffIcon from '@tabler/icons/outline/pinned-off.svg'; +import quoteIcon from '@tabler/icons/outline/quote.svg'; +import repeatIcon from '@tabler/icons/outline/repeat.svg'; +import shareIcon from '@tabler/icons/outline/share.svg'; +import thumbDownIcon from '@tabler/icons/outline/thumb-down.svg'; +import thumbUpIcon from '@tabler/icons/outline/thumb-up.svg'; +import trashIcon from '@tabler/icons/outline/trash.svg'; +import uploadIcon from '@tabler/icons/outline/upload.svg'; +import volume3Icon from '@tabler/icons/outline/volume-3.svg'; +import { defineMessages, FormattedMessage, useIntl } from 'react-intl'; +import { useHistory, useRouteMatch } from 'react-router-dom'; + +import { blockAccount } from 'soapbox/actions/accounts.ts'; +import { launchChat } from 'soapbox/actions/chats.ts'; +import { directCompose, mentionCompose } from 'soapbox/actions/compose.ts'; +import { editEvent } from 'soapbox/actions/events.ts'; +import { openModal } from 'soapbox/actions/modals.ts'; +import { deleteStatusModal, toggleStatusSensitivityModal } from 'soapbox/actions/moderation.tsx'; +import { initMuteModal } from 'soapbox/actions/mutes.ts'; +import { ReportableEntities } from 'soapbox/actions/reports.ts'; +import { deleteStatus, editStatus, toggleMuteStatus } from 'soapbox/actions/statuses.ts'; +import { deleteFromTimelines } from 'soapbox/actions/timelines.ts'; +import { useDeleteGroupStatus } from 'soapbox/api/hooks/groups/useDeleteGroupStatus.ts'; +import { useBlockGroupMember, useBookmark, useGroup, useGroupRelationship, useMuteGroup, useUnmuteGroup } from 'soapbox/api/hooks/index.ts'; +import DropdownMenu from 'soapbox/components/dropdown-menu/index.ts'; +import StatusActionButton from 'soapbox/components/status-action-button.tsx'; +import StatusReactionWrapper from 'soapbox/components/status-reaction-wrapper.tsx'; +import HStack from 'soapbox/components/ui/hstack.tsx'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useAppSelector } from 'soapbox/hooks/useAppSelector.ts'; +import { useDislike } from 'soapbox/hooks/useDislike.ts'; +import { useFavourite } from 'soapbox/hooks/useFavourite.ts'; +import { useFeatures } from 'soapbox/hooks/useFeatures.ts'; +import { useInitReport } from 'soapbox/hooks/useInitReport.ts'; +import { useOwnAccount } from 'soapbox/hooks/useOwnAccount.ts'; +import { usePin } from 'soapbox/hooks/usePin.ts'; +import { usePinGroup } from 'soapbox/hooks/usePinGroup.ts'; +import { useQuoteCompose } from 'soapbox/hooks/useQuoteCompose.ts'; +import { useReblog } from 'soapbox/hooks/useReblog.ts'; +import { useReplyCompose } from 'soapbox/hooks/useReplyCompose.ts'; +import { useSettings } from 'soapbox/hooks/useSettings.ts'; +import { GroupRoles } from 'soapbox/schemas/group-member.ts'; +import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; +import toast from 'soapbox/toast.tsx'; +import copy from 'soapbox/utils/copy.ts'; + +import GroupPopover from './groups/popover/group-popover.tsx'; + +import type { Menu } from 'soapbox/components/dropdown-menu/index.ts'; +import type { Group } from 'soapbox/types/entities.ts'; + +const messages = defineMessages({ + adminAccount: { id: 'status.admin_account', defaultMessage: 'Moderate @{name}' }, + admin_status: { id: 'status.admin_status', defaultMessage: 'Open this post in the moderation interface' }, + block: { id: 'account.block', defaultMessage: 'Block @{name}' }, + blocked: { id: 'group.group_mod_block.success', defaultMessage: '@{name} is banned' }, + blockAndReport: { id: 'confirmations.block.block_and_report', defaultMessage: 'Block & Report' }, + blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' }, + bookmark: { id: 'status.bookmark', defaultMessage: 'Bookmark' }, + bookmarkAdded: { id: 'status.bookmarked', defaultMessage: 'Bookmark added.' }, + bookmarkRemoved: { id: 'status.unbookmarked', defaultMessage: 'Bookmark removed.' }, + cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Un-repost' }, + cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be reposted' }, + chat: { id: 'status.chat', defaultMessage: 'Chat with @{name}' }, + copy: { id: 'status.copy', defaultMessage: 'Copy Link to Post' }, + deactivateUser: { id: 'admin.users.actions.deactivate_user', defaultMessage: 'Deactivate @{name}' }, + delete: { id: 'status.delete', defaultMessage: 'Delete' }, + deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' }, + deleteFromGroupMessage: { id: 'confirmations.delete_from_group.message', defaultMessage: 'Are you sure you want to delete @{name}\'s post?' }, + deleteHeading: { id: 'confirmations.delete.heading', defaultMessage: 'Delete post' }, + deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this post?' }, + deleteStatus: { id: 'admin.statuses.actions.delete_status', defaultMessage: 'Delete post' }, + deleteUser: { id: 'admin.users.actions.delete_user', defaultMessage: 'Delete @{name}' }, + direct: { id: 'status.direct', defaultMessage: 'Direct message @{name}' }, + disfavourite: { id: 'status.disfavourite', defaultMessage: 'Disike' }, + edit: { id: 'status.edit', defaultMessage: 'Edit' }, + embed: { id: 'status.embed', defaultMessage: 'Embed post' }, + external: { id: 'status.external', defaultMessage: 'View post on {domain}' }, + favourite: { id: 'status.favourite', defaultMessage: 'Like' }, + groupBlockConfirm: { id: 'confirmations.block_from_group.confirm', defaultMessage: 'Ban User' }, + groupBlockFromGroupHeading: { id: 'confirmations.block_from_group.heading', defaultMessage: 'Ban From Group' }, + groupBlockFromGroupMessage: { id: 'confirmations.block_from_group.message', defaultMessage: 'Are you sure you want to ban @{name} from the group?' }, + groupModDelete: { id: 'status.group_mod_delete', defaultMessage: 'Delete post from group' }, + group_remove_account: { id: 'status.remove_account_from_group', defaultMessage: 'Remove account from group' }, + group_remove_post: { id: 'status.remove_post_from_group', defaultMessage: 'Remove post from group' }, + markStatusNotSensitive: { id: 'admin.statuses.actions.mark_status_not_sensitive', defaultMessage: 'Mark post not sensitive' }, + markStatusSensitive: { id: 'admin.statuses.actions.mark_status_sensitive', defaultMessage: 'Mark post sensitive' }, + mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, + more: { id: 'status.more', defaultMessage: 'More' }, + mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, + muteConfirm: { id: 'confirmations.mute_group.confirm', defaultMessage: 'Mute' }, + muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute Conversation' }, + muteGroup: { id: 'group.mute.long_label', defaultMessage: 'Mute Group' }, + muteHeading: { id: 'confirmations.mute_group.heading', defaultMessage: 'Mute Group' }, + muteMessage: { id: 'confirmations.mute_group.message', defaultMessage: 'You are about to mute the group. Do you want to continue?' }, + muteSuccess: { id: 'group.mute.success', defaultMessage: 'Muted the group' }, + open: { id: 'status.open', defaultMessage: 'Show Post Details' }, + pin: { id: 'status.pin', defaultMessage: 'Pin on profile' }, + pinToGroup: { id: 'status.pin_to_group', defaultMessage: 'Pin to Group' }, + pinToGroupSuccess: { id: 'status.pin_to_group.success', defaultMessage: 'Pinned to Group!' }, + quotePost: { id: 'status.quote', defaultMessage: 'Quote post' }, + reactionCry: { id: 'status.reactions.cry', defaultMessage: 'Sad' }, + reactionHeart: { id: 'status.reactions.heart', defaultMessage: 'Love' }, + reactionLaughing: { id: 'status.reactions.laughing', defaultMessage: 'Haha' }, + reactionLike: { id: 'status.reactions.like', defaultMessage: 'Like' }, + reactionOpenMouth: { id: 'status.reactions.open_mouth', defaultMessage: 'Wow' }, + reactionWeary: { id: 'status.reactions.weary', defaultMessage: 'Weary' }, + reblog: { id: 'status.reblog', defaultMessage: 'Repost' }, + reblog_private: { id: 'status.reblog_private', defaultMessage: 'Repost to original audience' }, + redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' }, + redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' }, + redraftHeading: { id: 'confirmations.redraft.heading', defaultMessage: 'Delete & redraft' }, + redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this post and re-draft it? Favorites and reposts will be lost, and replies to the original post will be orphaned.' }, + replies_disabled_group: { id: 'status.disabled_replies.group_membership', defaultMessage: 'Only group members can reply' }, + reply: { id: 'status.reply', defaultMessage: 'Reply' }, + replyAll: { id: 'status.reply_all', defaultMessage: 'Reply to thread' }, + replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' }, + replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' }, + report: { id: 'status.report', defaultMessage: 'Report @{name}' }, + share: { id: 'status.share', defaultMessage: 'Share' }, + unbookmark: { id: 'status.unbookmark', defaultMessage: 'Remove bookmark' }, + unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute Conversation' }, + unmuteGroup: { id: 'group.unmute.long_label', defaultMessage: 'Unmute Group' }, + unmuteSuccess: { id: 'group.unmute.success', defaultMessage: 'Unmuted the group' }, + unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, + unpinFromGroup: { id: 'status.unpin_to_group', defaultMessage: 'Unpin from Group' }, + view: { id: 'toast.view', defaultMessage: 'View' }, + zap: { id: 'status.zap', defaultMessage: 'Zap' }, +}); + +interface IPureStatusActionBar { + status: StatusEntity; + expandable?: boolean; + space?: 'sm' | 'md' | 'lg'; + statusActionButtonTheme?: 'default' | 'inverse'; +} + +const PureStatusActionBar: React.FC = ({ + status, + expandable = true, + space = 'sm', + statusActionButtonTheme = 'default', +}) => { + const intl = useIntl(); + const history = useHistory(); + const dispatch = useAppDispatch(); + const match = useRouteMatch<{ groupSlug: string }>('/group/:groupSlug'); + + const { group } = useGroup((status.group as Group)?.id as string); + const muteGroup = useMuteGroup(group as Group); + const unmuteGroup = useUnmuteGroup(group as Group); + const isMutingGroup = !!group?.relationship?.muting; + const deleteGroupStatus = useDeleteGroupStatus(group as Group, status.id); + const blockGroupMember = useBlockGroupMember(group as Group, status.account); + + const me = useAppSelector(state => state.me); + const { groupRelationship } = useGroupRelationship(status.group?.id); + const features = useFeatures(); + const { boostModal, deleteModal } = useSettings(); + + const { account } = useOwnAccount(); + const isStaff = account ? account.staff : false; + const isAdmin = account ? account.admin : false; + + const { replyCompose } = useReplyCompose(); + const { toggleFavourite } = useFavourite(); + const { toggleDislike } = useDislike(); + const { bookmark, unbookmark } = useBookmark(); + const { toggleReblog } = useReblog(); + const { quoteCompose } = useQuoteCompose(); + const { togglePin } = usePin(); + const { unpinFromGroup, pinToGroup } = usePinGroup(); + const { initReport } = useInitReport(); + + if (!status) { + return null; + } + + const onOpenUnauthorizedModal = (action?: string) => { + dispatch(openModal('UNAUTHORIZED', { + action, + ap_id: status.url, + })); + }; + + const handleReplyClick: React.MouseEventHandler = (e) => { + if (me) { + replyCompose(status.id); + } else { + onOpenUnauthorizedModal('REPLY'); + } + }; + + const handleShareClick = () => { + navigator.share({ + text: status.search_index, + url: status.uri, + }).catch((e) => { + if (e.name !== 'AbortError') console.error(e); + }); + }; + + const handleFavouriteClick: React.EventHandler = (e) => { + if (me) { + toggleFavourite(status.id); + } else { + onOpenUnauthorizedModal('FAVOURITE'); + } + }; + + const handleDislikeClick: React.EventHandler = (e) => { + if (me) { + toggleDislike(status.id); + } else { + onOpenUnauthorizedModal('DISLIKE'); + } + }; + + const handleZapClick: React.EventHandler = (e) => { + if (me) { + dispatch(openModal('ZAP_PAY_REQUEST', { status, account: status.account })); + } else { + onOpenUnauthorizedModal('ZAP_PAY_REQUEST'); + } + }; + + const handleBookmarkClick: React.EventHandler = (e) => { + if (status.bookmarked) { + unbookmark(status.id).then(({ success }) => { + if (success) { + toast.success(messages.bookmarkRemoved); + } + }).catch(null); + } else { + bookmark(status.id).then(({ success }) => { + if (success) { + toast.success(messages.bookmarkAdded, { + actionLink: '/bookmarks/all', actionLabel: messages.view, + }); + } + }).catch(null); + } + }; + + const handleReblogClick: React.EventHandler = e => { + if (me) { + const modalReblog = () => toggleReblog(status.id); + if ((e && e.shiftKey) || !boostModal) { + modalReblog(); + } else { + dispatch(openModal('BOOST', { status, onReblog: modalReblog })); + } + } else { + onOpenUnauthorizedModal('REBLOG'); + } + }; + + const handleQuoteClick: React.EventHandler = (e) => { + if (me) { + quoteCompose(status.id); + } else { + onOpenUnauthorizedModal('REBLOG'); + } + }; + + const doDeleteStatus = (withRedraft = false) => { + dispatch((_, getState) => { + if (!deleteModal) { + dispatch(deleteStatus(status.id, withRedraft)); + } else { + dispatch(openModal('CONFIRM', { + icon: withRedraft ? editIcon : trashIcon, + heading: intl.formatMessage(withRedraft ? messages.redraftHeading : messages.deleteHeading), + message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage), + confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm), + onConfirm: () => dispatch(deleteStatus(status.id, withRedraft)), + })); + } + }); + }; + + const handleDeleteClick: React.EventHandler = (e) => { + doDeleteStatus(); + }; + + const handleRedraftClick: React.EventHandler = (e) => { + doDeleteStatus(true); + }; + + const handleEditClick: React.EventHandler = () => { + if (status.event) dispatch(editEvent(status.id)); + else dispatch(editStatus(status.id)); + }; + + const handlePinClick: React.EventHandler = (e) => { + togglePin(status.id); + }; + + const handleGroupPinClick: React.EventHandler = () => { + if (status.pinned) { + unpinFromGroup(status.id); + } else { + pinToGroup(status.id) + ?.then(() => toast.success(intl.formatMessage(messages.pinToGroupSuccess))) + .catch(() => null); + } + }; + + const handleMentionClick: React.EventHandler = (e) => { + dispatch(mentionCompose(status.account)); + }; + + const handleDirectClick: React.EventHandler = (e) => { + dispatch(directCompose(status.account)); + }; + + const handleChatClick: React.EventHandler = (e) => { + const account = status.account; + dispatch(launchChat(account.id, history)); + }; + + const handleMuteClick: React.EventHandler = (e) => { + dispatch(initMuteModal(status.account)); + }; + + const handleMuteGroupClick: React.EventHandler = () => + dispatch(openModal('CONFIRM', { + heading: intl.formatMessage(messages.muteHeading), + message: intl.formatMessage(messages.muteMessage), + confirm: intl.formatMessage(messages.muteConfirm), + confirmationTheme: 'primary', + onConfirm: () => muteGroup.mutate(undefined, { + onSuccess() { + toast.success(intl.formatMessage(messages.muteSuccess)); + }, + }), + })); + + const handleUnmuteGroupClick: React.EventHandler = () => { + unmuteGroup.mutate(undefined, { + onSuccess() { + toast.success(intl.formatMessage(messages.unmuteSuccess)); + }, + }); + }; + + const handleBlockClick: React.EventHandler = (e) => { + const account = status.account; + + dispatch(openModal('CONFIRM', { + icon: banIcon, + heading: , + message: @{account.acct} }} />, // eslint-disable-line formatjs/no-literal-string-in-jsx + confirm: intl.formatMessage(messages.blockConfirm), + onConfirm: () => dispatch(blockAccount(account.id)), + secondary: intl.formatMessage(messages.blockAndReport), + onSecondary: () => { + dispatch(blockAccount(account.id)); + initReport(ReportableEntities.STATUS, account, { statusId: status.id }); + }, + })); + }; + + const handleEmbed = () => { + dispatch(openModal('EMBED', { + url: status.url, + onError: (error: any) => toast.showAlertForError(error), + })); + }; + + const handleReport: React.EventHandler = (e) => { + initReport(ReportableEntities.STATUS, status.account, { statusId: status.id }); + }; + + const handleConversationMuteClick: React.EventHandler = (e) => { + dispatch(toggleMuteStatus(status)); + }; + + const handleCopy: React.EventHandler = (e) => { + const { uri } = status; + + copy(uri); + }; + + const onModerate: React.MouseEventHandler = (e) => { + const account = status.account; + dispatch(openModal('ACCOUNT_MODERATION', { accountId: account.id })); + }; + + const handleDeleteStatus: React.EventHandler = (e) => { + dispatch(deleteStatusModal(intl, status.id)); + }; + + const handleToggleStatusSensitivity: React.EventHandler = (e) => { + dispatch(toggleStatusSensitivityModal(intl, status.id, status.sensitive)); + }; + + const handleDeleteFromGroup: React.EventHandler = () => { + const account = status.account; + + dispatch(openModal('CONFIRM', { + heading: intl.formatMessage(messages.deleteHeading), + message: intl.formatMessage(messages.deleteFromGroupMessage, { name: {account.username} }), + confirm: intl.formatMessage(messages.deleteConfirm), + onConfirm: () => { + deleteGroupStatus.mutate(status.id, { + onSuccess() { + dispatch(deleteFromTimelines(status.id)); + }, + }); + }, + })); + }; + + const handleBlockFromGroup = () => { + dispatch(openModal('CONFIRM', { + heading: intl.formatMessage(messages.groupBlockFromGroupHeading), + message: intl.formatMessage(messages.groupBlockFromGroupMessage, { name: status.account.username }), + confirm: intl.formatMessage(messages.groupBlockConfirm), + onConfirm: () => { + blockGroupMember({ account_ids: [status.account.id] }, { + onSuccess() { + toast.success(intl.formatMessage(messages.blocked, { name: account?.acct })); + }, + }); + }, + })); + }; + + const _makeMenu = (publicStatus: boolean) => { + const mutingConversation = status.muted; + const ownAccount = status.account.id === me; + const username = status.account.username; + const account = status.account; + + const menu: Menu = []; + + if (expandable) { + menu.push({ + text: intl.formatMessage(messages.open), + icon: arrowsVerticalIcon, + to: `/@${status.account.acct}/posts/${status.id}`, + }); + } + + if (publicStatus) { + menu.push({ + text: intl.formatMessage(messages.copy), + action: handleCopy, + icon: clipboardCopyIcon, + }); + + if (features.embeds && account.local) { + menu.push({ + text: intl.formatMessage(messages.embed), + action: handleEmbed, + icon: shareIcon, + }); + } + } + + if (features.federating && (status.ditto?.external_url || !account.local)) { + const externalNostrUrl: string | undefined = status.ditto?.external_url; + const { hostname: domain } = new URL(externalNostrUrl || status.uri); + + menu.push({ + text: intl.formatMessage(messages.external, { domain }), + icon: externalLinkIcon, + href: externalNostrUrl || status.uri, + target: '_blank', + }); + } + + if (!me) { + return menu; + } + + const isGroupStatus = typeof status.group === 'object'; + if (isGroupStatus && !!status.group) { + const isGroupOwner = groupRelationship?.role === GroupRoles.OWNER; + + if (isGroupOwner) { + menu.push({ + text: intl.formatMessage(status.pinned ? messages.unpinFromGroup : messages.pinToGroup), + action: handleGroupPinClick, + icon: status.pinned ? pinnedOffIcon : pinIcon, + }); + } + } + + if (features.bookmarks) { + menu.push({ + text: intl.formatMessage(status.bookmarked ? messages.unbookmark : messages.bookmark), + action: handleBookmarkClick, + icon: status.bookmarked ? bookmarkOffIcon : bookmarkIcon, + }); + } + + menu.push(null); + + menu.push({ + text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), + action: handleConversationMuteClick, + icon: mutingConversation ? bellIcon : bellOffIcon, + }); + + menu.push(null); + + if (ownAccount) { + if (publicStatus) { + menu.push({ + text: intl.formatMessage(status.pinned ? messages.unpin : messages.pin), + action: handlePinClick, + icon: status.pinned ? pinnedOffIcon : pinIcon, + }); + } else { + if (status.visibility === 'private') { + menu.push({ + text: intl.formatMessage(status.reblogged ? messages.cancel_reblog_private : messages.reblog_private), + action: handleReblogClick, + icon: repeatIcon, + }); + } + } + + menu.push({ + text: intl.formatMessage(messages.delete), + action: handleDeleteClick, + icon: trashIcon, + destructive: true, + }); + if (features.editStatuses) { + menu.push({ + text: intl.formatMessage(messages.edit), + action: handleEditClick, + icon: editIcon, + }); + } else { + menu.push({ + text: intl.formatMessage(messages.redraft), + action: handleRedraftClick, + icon: editIcon, + destructive: true, + }); + } + } else { + menu.push({ + text: intl.formatMessage(messages.mention, { name: username }), + action: handleMentionClick, + icon: atIcon, + }); + + if (status.account.pleroma?.accepts_chat_messages === true) { + menu.push({ + text: intl.formatMessage(messages.chat, { name: username }), + action: handleChatClick, + icon: messagesIcon, + }); + } else if (features.privacyScopes) { + menu.push({ + text: intl.formatMessage(messages.direct, { name: username }), + action: handleDirectClick, + icon: mailIcon, + }); + } + + menu.push(null); + if (features.groupsMuting && status.group) { + menu.push({ + text: isMutingGroup ? intl.formatMessage(messages.unmuteGroup) : intl.formatMessage(messages.muteGroup), + icon: volume3Icon, + action: isMutingGroup ? handleUnmuteGroupClick : handleMuteGroupClick, + }); + menu.push(null); + } + + menu.push({ + text: intl.formatMessage(messages.mute, { name: username }), + action: handleMuteClick, + icon: volume3Icon, + }); + if (features.blocks) { + menu.push({ + text: intl.formatMessage(messages.block, { name: username }), + action: handleBlockClick, + icon: banIcon, + }); + } + menu.push({ + text: intl.formatMessage(messages.report, { name: username }), + action: handleReport, + icon: flagIcon, + }); + } + + if (isGroupStatus && !!status.group) { + const group = status.group as Group; + const account = status.account; + const isGroupOwner = groupRelationship?.role === GroupRoles.OWNER; + const isGroupAdmin = groupRelationship?.role === GroupRoles.ADMIN; + const isStatusFromOwner = group.owner.id === account.id; + + const canBanUser = match?.isExact && (isGroupOwner || isGroupAdmin) && !isStatusFromOwner && !ownAccount; + const canDeleteStatus = !ownAccount && (isGroupOwner || (isGroupAdmin && !isStatusFromOwner)); + + if (canBanUser || canDeleteStatus) { + menu.push(null); + } + + if (canBanUser) { + menu.push({ + text: 'Ban from Group', + action: handleBlockFromGroup, + icon: banIcon, + destructive: true, + }); + } + + if (canDeleteStatus) { + menu.push({ + text: intl.formatMessage(messages.groupModDelete), + action: handleDeleteFromGroup, + icon: trashIcon, + destructive: true, + }); + } + } + + if (isStaff) { + menu.push(null); + + menu.push({ + text: intl.formatMessage(messages.adminAccount, { name: username }), + action: onModerate, + icon: gavelIcon, + }); + + if (isAdmin) { + menu.push({ + text: intl.formatMessage(messages.admin_status), + href: `/pleroma/admin/#/statuses/${status.id}/`, + icon: pencilIcon, + }); + } + + menu.push({ + text: intl.formatMessage(status.sensitive === false ? messages.markStatusSensitive : messages.markStatusNotSensitive), + action: handleToggleStatusSensitivity, + icon: alertTriangleIcon, + }); + + if (!ownAccount) { + menu.push({ + text: intl.formatMessage(messages.deleteStatus), + action: handleDeleteStatus, + icon: trashIcon, + destructive: true, + }); + } + } + + return menu; + }; + + const publicStatus = ['public', 'unlisted', 'group'].includes(status.visibility); + + const replyCount = status.replies_count; + const reblogCount = status.reblogs_count; + const favouriteCount = status.favourites_count; + + const emojiReactCount = status.reactions?.reduce((acc, reaction) => acc + (reaction.count ?? 0), 0) ?? 0; // allow all emojis + + const meEmojiReact = status.reactions?.find((emojiReact) => emojiReact.me) // allow all emojis + ?? ( + status.favourited && account + ? { count: 1, me: status.account.id === account.id, name: '👍' } + : undefined + ); + + const meEmojiName = meEmojiReact?.name as keyof typeof reactMessages | undefined; + + const reactMessages = { + '👍': messages.reactionLike, + '❤️': messages.reactionHeart, + '😆': messages.reactionLaughing, + '😮': messages.reactionOpenMouth, + '😢': messages.reactionCry, + '😩': messages.reactionWeary, + '': messages.favourite, + }; + + const meEmojiTitle = intl.formatMessage(reactMessages[meEmojiName || ''] || messages.favourite); + + const menu = _makeMenu(publicStatus); + let reblogIcon = repeatIcon; + let replyTitle; + let replyDisabled = false; + + if (status.visibility === 'direct') { + reblogIcon = mailIcon; + } else if (status.visibility === 'private') { + reblogIcon = lockIcon; + } + + if ((status.group as Group)?.membership_required && !groupRelationship?.member) { + replyDisabled = true; + replyTitle = intl.formatMessage(messages.replies_disabled_group); + } + + const reblogMenu = [{ + text: intl.formatMessage(status.reblogged ? messages.cancel_reblog_private : messages.reblog), + action: handleReblogClick, + icon: repeatIcon, + }, { + text: intl.formatMessage(messages.quotePost), + action: handleQuoteClick, + icon: quoteIcon, + }]; + + const reblogButton = ( + + ); + + if (!status.in_reply_to_id) { + replyTitle = intl.formatMessage(messages.reply); + } else { + replyTitle = intl.formatMessage(messages.replyAll); + } + + const canShare = ('share' in navigator) && (status.visibility === 'public' || status.visibility === 'group'); + const acceptsZaps = status.account.ditto.accepts_zaps === true; + + const spacing: { + [key: string]: React.ComponentProps['space']; + } = { + 'sm': 2, + 'md': 8, + 'lg': 0, // using justifyContent instead on the HStack + }; + + return ( + + e.stopPropagation()} + alignItems='center' + > + + + + + {(features.quotePosts && me) ? ( + + {reblogButton} + + ) : ( + reblogButton + )} + + {features.emojiReacts ? ( + + + + ) : ( + + )} + + {features.dislikes && ( + + )} + + {(acceptsZaps) && ( + + )} + + {canShare && ( + + )} + + + + + + + ); +}; + +export default PureStatusActionBar; diff --git a/src/components/pure-status.tsx b/src/components/pure-status.tsx index ff7c15805..93a1e0fa2 100644 --- a/src/components/pure-status.tsx +++ b/src/components/pure-status.tsx @@ -9,6 +9,7 @@ import { Link, useHistory } from 'react-router-dom'; import { openModal } from 'soapbox/actions/modals.ts'; import { unfilterStatus } from 'soapbox/actions/statuses.ts'; import PureEventPreview from 'soapbox/components/pure-event-preview.tsx'; +import PureStatusActionBar from 'soapbox/components/pure-status-action-bar.tsx'; import PureStatusContent from 'soapbox/components/pure-status-content.tsx'; import PureStatusReplyMentions from 'soapbox/components/pure-status-reply-mentions.tsx'; import PureTranslateButton from 'soapbox/components/pure-translate-button.tsx'; @@ -27,13 +28,10 @@ import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { useReplyCompose } from 'soapbox/hooks/useReplyCompose.ts'; import { useSettings } from 'soapbox/hooks/useSettings.ts'; import { useStatusHidden } from 'soapbox/hooks/useStatusHidden.ts'; -import { normalizeStatus } from 'soapbox/normalizers/index.ts'; import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; -import { Status as LegacyStatus } from 'soapbox/types/entities.ts'; import { emojifyText } from 'soapbox/utils/emojify.tsx'; import { defaultMediaVisibility, textForScreenReader, getActualStatus } from 'soapbox/utils/status.ts'; -import StatusActionBar from './status-action-bar.tsx'; import StatusMedia from './status-media.tsx'; import StatusInfo from './statuses/status-info.tsx'; import Tombstone from './tombstone.tsx'; @@ -126,8 +124,6 @@ const PureStatus: React.FC = (props) => { } }, [overlay.current]); - const statusImmutable = normalizeStatus(status) as LegacyStatus; // TODO: remove this line, it will be removed once all components in this file are pure. - const handleToggleMediaVisibility = (): void => { setShowMedia(!showMedia); }; @@ -492,7 +488,7 @@ const PureStatus: React.FC = (props) => { {(!hideActionBar && !isUnderReview) && (
- {/* FIXME: stop using 'statusImmutable' and use 'status' variable directly, for that create a new component called 'PureStatusActionBar' */} +
)} diff --git a/src/hooks/useDislike.ts b/src/hooks/useDislike.ts new file mode 100644 index 000000000..ca56b5033 --- /dev/null +++ b/src/hooks/useDislike.ts @@ -0,0 +1,31 @@ +import { dislike as dislikeAction, undislike as undislikeAction, toggleDislike as toggleDislikeAction } from 'soapbox/actions/interactions.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; + +export function useDislike() { + const getState = useGetState(); + const dispatch = useAppDispatch(); + + const dislike = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(dislikeAction(status)); + } + }; + + const undislike = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(undislikeAction(status)); + } + }; + + const toggleDislike = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(toggleDislikeAction(status)); + } + }; + + return { dislike, undislike, toggleDislike }; +} diff --git a/src/hooks/useInitReport.ts b/src/hooks/useInitReport.ts new file mode 100644 index 000000000..e23ecc6b2 --- /dev/null +++ b/src/hooks/useInitReport.ts @@ -0,0 +1,27 @@ +import { initReport as initReportAction, ReportableEntities } from 'soapbox/actions/reports.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; +import { Account } from 'soapbox/schemas/index.ts'; + +type SemiReportedEntity = { + statusId?: string; +} + +/** TODO: support fully the 'ReportedEntity' type, for now only status is suported. */ +export function useInitReport() { + const getState = useGetState(); + const dispatch = useAppDispatch(); + + const initReport = (entityType: ReportableEntities, account: Account, entities?: SemiReportedEntity) => { + const { statusId } = entities || {}; + + if (!statusId) return; + + const status = getState().statuses.get(statusId); + if (status) { + dispatch(initReportAction(entityType, account, { status })); + } + }; + + return { initReport }; +} diff --git a/src/hooks/usePin.ts b/src/hooks/usePin.ts new file mode 100644 index 000000000..0c1e3ed3a --- /dev/null +++ b/src/hooks/usePin.ts @@ -0,0 +1,31 @@ +import { pin as pinAction, unpin as unpinAction, togglePin as togglePinAction } from 'soapbox/actions/interactions.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; + +export function usePin() { + const getState = useGetState(); + const dispatch = useAppDispatch(); + + const pin = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(pinAction(status)); + } + }; + + const unpin = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(unpinAction(status)); + } + }; + + const togglePin = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(togglePinAction(status)); + } + }; + + return { pin, unpin, togglePin }; +} diff --git a/src/hooks/usePinGroup.ts b/src/hooks/usePinGroup.ts new file mode 100644 index 000000000..12df3772a --- /dev/null +++ b/src/hooks/usePinGroup.ts @@ -0,0 +1,24 @@ +import { pinToGroup as pinToGroupAction, unpinFromGroup as unpinFromGroupAction } from 'soapbox/actions/interactions.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; + +export function usePinGroup() { + const getState = useGetState(); + const dispatch = useAppDispatch(); + + const pinToGroup = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status && status.group) { + return dispatch(pinToGroupAction(status, status.group)); + } + }; + + const unpinFromGroup = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status && status.group) { + return dispatch(unpinFromGroupAction(status, status.group)); + } + }; + + return { pinToGroup, unpinFromGroup }; +} diff --git a/src/hooks/useQuoteCompose.ts b/src/hooks/useQuoteCompose.ts new file mode 100644 index 000000000..5df9e2857 --- /dev/null +++ b/src/hooks/useQuoteCompose.ts @@ -0,0 +1,17 @@ +import { quoteCompose as quoteComposeAction } from 'soapbox/actions/compose.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; + +export function useQuoteCompose() { + const getState = useGetState(); + const dispatch = useAppDispatch(); + + const quoteCompose = (statusId: string) => { + const status = getState().statuses.get(statusId); + if (status) { + dispatch(quoteComposeAction(status)); + } + }; + + return { quoteCompose }; +} \ No newline at end of file From e3aff3bdc6ce7a420c17c8b0587abaf6046fe73a Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 22:49:01 -0300 Subject: [PATCH 07/16] refactor: StatusActionBar component uses the useBookmark() hook to bookmark and unbookmark a status --- src/components/status-action-bar.tsx | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/components/status-action-bar.tsx b/src/components/status-action-bar.tsx index 03a41cd47..5b6924ee2 100644 --- a/src/components/status-action-bar.tsx +++ b/src/components/status-action-bar.tsx @@ -36,7 +36,7 @@ import { blockAccount } from 'soapbox/actions/accounts.ts'; import { launchChat } from 'soapbox/actions/chats.ts'; import { directCompose, mentionCompose, quoteCompose, replyCompose } from 'soapbox/actions/compose.ts'; import { editEvent } from 'soapbox/actions/events.ts'; -import { pinToGroup, toggleBookmark, toggleDislike, toggleFavourite, togglePin, unpinFromGroup } from 'soapbox/actions/interactions.ts'; +import { pinToGroup, toggleDislike, toggleFavourite, togglePin, unpinFromGroup } from 'soapbox/actions/interactions.ts'; import { openModal } from 'soapbox/actions/modals.ts'; import { deleteStatusModal, toggleStatusSensitivityModal } from 'soapbox/actions/moderation.tsx'; import { initMuteModal } from 'soapbox/actions/mutes.ts'; @@ -44,7 +44,7 @@ import { initReport, ReportableEntities } from 'soapbox/actions/reports.ts'; import { deleteStatus, editStatus, toggleMuteStatus } from 'soapbox/actions/statuses.ts'; import { deleteFromTimelines } from 'soapbox/actions/timelines.ts'; import { useDeleteGroupStatus } from 'soapbox/api/hooks/groups/useDeleteGroupStatus.ts'; -import { useBlockGroupMember, useGroup, useGroupRelationship, useMuteGroup, useUnmuteGroup } from 'soapbox/api/hooks/index.ts'; +import { useBlockGroupMember, useBookmark, useGroup, useGroupRelationship, useMuteGroup, useUnmuteGroup } from 'soapbox/api/hooks/index.ts'; import DropdownMenu from 'soapbox/components/dropdown-menu/index.ts'; import StatusActionButton from 'soapbox/components/status-action-button.tsx'; import StatusReactionWrapper from 'soapbox/components/status-reaction-wrapper.tsx'; @@ -73,6 +73,8 @@ const messages = defineMessages({ blockAndReport: { id: 'confirmations.block.block_and_report', defaultMessage: 'Block & Report' }, blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' }, bookmark: { id: 'status.bookmark', defaultMessage: 'Bookmark' }, + bookmarkAdded: { id: 'status.bookmarked', defaultMessage: 'Bookmark added.' }, + bookmarkRemoved: { id: 'status.unbookmarked', defaultMessage: 'Bookmark removed.' }, cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Un-repost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be reposted' }, chat: { id: 'status.chat', defaultMessage: 'Chat with @{name}' }, @@ -138,6 +140,7 @@ const messages = defineMessages({ unmuteSuccess: { id: 'group.unmute.success', defaultMessage: 'Unmuted the group' }, unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, unpinFromGroup: { id: 'status.unpin_to_group', defaultMessage: 'Unpin from Group' }, + view: { id: 'toast.view', defaultMessage: 'View' }, zap: { id: 'status.zap', defaultMessage: 'Zap' }, }); @@ -176,6 +179,7 @@ const StatusActionBar: React.FC = ({ const isAdmin = account ? account.admin : false; const { toggleReblog } = useReblog(); + const { bookmark, unbookmark } = useBookmark(); if (!status) { return null; @@ -230,7 +234,21 @@ const StatusActionBar: React.FC = ({ }; const handleBookmarkClick: React.EventHandler = (e) => { - dispatch(toggleBookmark(status)); + if (status.bookmarked) { + unbookmark(status.id).then(({ success }) => { + if (success) { + toast.success(messages.bookmarkRemoved); + } + }).catch(null); + } else { + bookmark(status.id).then(({ success }) => { + if (success) { + toast.success(messages.bookmarkAdded, { + actionLink: '/bookmarks/all', actionLabel: messages.view, + }); + } + }).catch(null); + } }; const handleReblogClick: React.EventHandler = e => { From beed9fa6c37959f7356fe744cf71f50e3f6ad2b3 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 22:49:39 -0300 Subject: [PATCH 08/16] fix: import the bookmarked status to the start of the cache array --- src/api/hooks/statuses/useBookmark.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/hooks/statuses/useBookmark.ts b/src/api/hooks/statuses/useBookmark.ts index 23ffbcf5b..4bb45f2a5 100644 --- a/src/api/hooks/statuses/useBookmark.ts +++ b/src/api/hooks/statuses/useBookmark.ts @@ -61,7 +61,7 @@ function useBookmark() { const response = await api.post(`/api/v1/statuses/${statusId}/bookmark`); const result = statusSchema.safeParse(await response.json()); if (result.success) { - dispatch(importEntities([result.data], Entities.STATUSES, 'bookmarks')); + dispatch(importEntities([result.data], Entities.STATUSES, 'bookmarks', 'start')); } return { success: true }; } catch (e) { From 4c2ed157a0cfbf335db84e7bf25d160ecf4ed08e Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 13 Dec 2024 23:41:34 -0300 Subject: [PATCH 09/16] feat: create reblogEffect and unreblogEffect functions, and use it in legacy actions in such a way that everything is compatible --- src/actions/interactions.ts | 19 ++++++++--- src/hooks/useReblog.ts | 68 +++++++++++++++++++++++++++++++++---- 2 files changed, 76 insertions(+), 11 deletions(-) diff --git a/src/actions/interactions.ts b/src/actions/interactions.ts index e4faf11a6..0383d6b49 100644 --- a/src/actions/interactions.ts +++ b/src/actions/interactions.ts @@ -95,11 +95,17 @@ const messages = defineMessages({ view: { id: 'toast.view', defaultMessage: 'View' }, }); -const reblog = (status: StatusEntity) => +type ReblogEffects = { + reblogEffect: (statusId: string) => void; + unreblogEffect: (statusId: string) => void; +} + +const reblog = (status: StatusEntity, effects?: ReblogEffects) => function(dispatch: AppDispatch, getState: () => RootState) { if (!isLoggedIn(getState)) return; dispatch(reblogRequest(status)); + effects?.reblogEffect(status.id); api(getState).post(`/api/v1/statuses/${status.id}/reblog`).then(function(response) { // The reblog API method returns a new status wrapped around the original. In this case we are only @@ -108,28 +114,31 @@ const reblog = (status: StatusEntity) => dispatch(reblogSuccess(status)); }).catch(error => { dispatch(reblogFail(status, error)); + effects?.unreblogEffect(status.id); }); }; -const unreblog = (status: StatusEntity) => +const unreblog = (status: StatusEntity, effects?: ReblogEffects) => (dispatch: AppDispatch, getState: () => RootState) => { if (!isLoggedIn(getState)) return; dispatch(unreblogRequest(status)); + effects?.unreblogEffect(status.id); api(getState).post(`/api/v1/statuses/${status.id}/unreblog`).then(() => { dispatch(unreblogSuccess(status)); }).catch(error => { dispatch(unreblogFail(status, error)); + effects?.reblogEffect(status.id); }); }; -const toggleReblog = (status: StatusEntity) => +const toggleReblog = (status: StatusEntity, effects?: ReblogEffects) => (dispatch: AppDispatch) => { if (status.reblogged) { - dispatch(unreblog(status)); + dispatch(unreblog(status, effects)); } else { - dispatch(reblog(status)); + dispatch(reblog(status, effects)); } }; diff --git a/src/hooks/useReblog.ts b/src/hooks/useReblog.ts index d0028dbae..15d5004d6 100644 --- a/src/hooks/useReblog.ts +++ b/src/hooks/useReblog.ts @@ -1,29 +1,85 @@ import { reblog as reblogAction, unreblog as unreblogAction, toggleReblog as toggleReblogAction } from 'soapbox/actions/interactions.ts'; +import { Entities } from 'soapbox/entity-store/entities.ts'; +import { useTransaction } from 'soapbox/entity-store/hooks/index.ts'; +import { selectEntity } from 'soapbox/entity-store/selectors.ts'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useGetState } from 'soapbox/hooks/useGetState.ts'; +import { normalizeStatus } from 'soapbox/normalizers/index.ts'; +import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; + +import type { Status as LegacyStatus } from 'soapbox/types/entities.ts'; export function useReblog() { const getState = useGetState(); const dispatch = useAppDispatch(); + const { transaction } = useTransaction(); + + function reblogEffect(statusId: string) { + transaction({ + Statuses: { + [statusId]: (status) => ({ + ...status, + reblogged: true, + reblogs_count: status.reblogs_count + 1, + }), + }, + }); + } + + function unreblogEffect(statusId: string) { + transaction({ + Statuses: { + [statusId]: (status) => ({ + ...status, + reblogged: false, + reblogs_count: status.reblogs_count - 1, + }), + }, + }); + } const reblog = (statusId: string) => { - const status = getState().statuses.get(statusId); + let status: undefined|LegacyStatus|StatusEntity = getState().statuses.get(statusId); + if (status) { - dispatch(reblogAction(status)); + dispatch(reblogAction(status, { reblogEffect, unreblogEffect })); + return; + } + + status = selectEntity(getState(), Entities.STATUSES, statusId); + if (status) { + dispatch(reblogAction(normalizeStatus(status) as LegacyStatus, { reblogEffect, unreblogEffect })); + return; } }; const unreblog = (statusId: string) => { - const status = getState().statuses.get(statusId); + let status: undefined|LegacyStatus|StatusEntity = getState().statuses.get(statusId); + if (status) { - dispatch(unreblogAction(status)); + dispatch(unreblogAction(status, { reblogEffect, unreblogEffect })); + return; + } + + status = selectEntity(getState(), Entities.STATUSES, statusId); + if (status) { + dispatch(unreblogAction(normalizeStatus(status) as LegacyStatus, { reblogEffect, unreblogEffect })); + return; } }; const toggleReblog = (statusId: string) => { - const status = getState().statuses.get(statusId); + let status: undefined|LegacyStatus|StatusEntity = getState().statuses.get(statusId); + if (status) { - dispatch(toggleReblogAction(status)); + dispatch(toggleReblogAction(status, { reblogEffect, unreblogEffect })); + return; + } + + status = selectEntity(getState(), Entities.STATUSES, statusId); + if (status) { + dispatch(toggleReblogAction(normalizeStatus(status) as LegacyStatus, { reblogEffect, unreblogEffect })); + return; } }; From ede079a0ebc2a3df60c2a4c91f1f3629e1725f59 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Mon, 16 Dec 2024 21:06:46 -0300 Subject: [PATCH 10/16] refactor/checkpoint: create PureStatusReactionWrapper component to make it work 100%, a reaction hook must be created and used, rather than dispatching the simpleEmojiReact() function from actions (src/actions/emoji-reacts.ts) --- .../pure-status-reaction-wrapper.tsx | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 src/components/pure-status-reaction-wrapper.tsx diff --git a/src/components/pure-status-reaction-wrapper.tsx b/src/components/pure-status-reaction-wrapper.tsx new file mode 100644 index 000000000..63c66ec73 --- /dev/null +++ b/src/components/pure-status-reaction-wrapper.tsx @@ -0,0 +1,132 @@ +import { useState, useEffect, useRef, cloneElement } from 'react'; + +import { simpleEmojiReact } from 'soapbox/actions/emoji-reacts.ts'; +import { openModal } from 'soapbox/actions/modals.ts'; +import EmojiSelector from 'soapbox/components/ui/emoji-selector.tsx'; +import Portal from 'soapbox/components/ui/portal.tsx'; +import { Entities } from 'soapbox/entity-store/entities.ts'; +import { selectEntity } from 'soapbox/entity-store/selectors.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; +import { useOwnAccount } from 'soapbox/hooks/useOwnAccount.ts'; +import { userTouching } from 'soapbox/is-mobile.ts'; +import { normalizeStatus } from 'soapbox/normalizers/index.ts'; +import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; + +import type { Status as LegacyStatus } from 'soapbox/types/entities.ts'; + +interface IPureStatusReactionWrapper { + statusId: string; + children: JSX.Element; +} + +/** Provides emoji reaction functionality to the underlying button component */ +const PureStatusReactionWrapper: React.FC = ({ statusId, children }): JSX.Element | null => { + const dispatch = useAppDispatch(); + const { account: ownAccount } = useOwnAccount(); + const getState = useGetState(); + + const status = selectEntity(getState(), Entities.STATUSES, statusId); + + const timeout = useRef(); + const [visible, setVisible] = useState(false); + + const [referenceElement, setReferenceElement] = useState(null); + + useEffect(() => { + return () => { + if (timeout.current) { + clearTimeout(timeout.current); + } + }; + }, []); + + if (!status) return null; + + const handleMouseEnter = () => { + if (timeout.current) { + clearTimeout(timeout.current); + } + + if (!userTouching.matches) { + setVisible(true); + } + }; + + const handleMouseLeave = () => { + if (timeout.current) { + clearTimeout(timeout.current); + } + + // Unless the user is touching, delay closing the emoji selector briefly + // so the user can move the mouse diagonally to make a selection. + if (userTouching.matches) { + setVisible(false); + } else { + timeout.current = setTimeout(() => { + setVisible(false); + }, 500); + } + }; + + const handleReact = (emoji: string, custom?: string): void => { + if (ownAccount) { + dispatch(simpleEmojiReact(normalizeStatus(status) as LegacyStatus, emoji, custom)); + } else { + handleUnauthorized(); + } + + setVisible(false); + }; + + const handleClick: React.EventHandler = e => { + const meEmojiReact = status.reactions?.find((emojiReact) => emojiReact.me)?.name ?? '👍' ; // allow all emojis + + if (userTouching.matches) { + if (ownAccount) { + if (visible) { + handleReact(meEmojiReact); + } else { + setVisible(true); + } + } else { + handleUnauthorized(); + } + } else { + handleReact(meEmojiReact); + } + + e.preventDefault(); + e.stopPropagation(); + }; + + const handleUnauthorized = () => { + dispatch(openModal('UNAUTHORIZED', { + action: 'FAVOURITE', + ap_id: status.url, + })); + }; + + return ( +
+ {cloneElement(children, { + onClick: handleClick, + ref: setReferenceElement, + })} + + {visible && ( + + setVisible(false)} + /> + + )} +
+ ); +}; + +export default PureStatusReactionWrapper; From f6cc3382dd15b5af951de2db3999e87a371636df Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Tue, 17 Dec 2024 19:59:04 -0300 Subject: [PATCH 11/16] refactor: use /PureStatusReactionWrapper component in PureStatusActionBar component --- src/components/pure-status-action-bar.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/pure-status-action-bar.tsx b/src/components/pure-status-action-bar.tsx index 4f1312692..aee22adbd 100644 --- a/src/components/pure-status-action-bar.tsx +++ b/src/components/pure-status-action-bar.tsx @@ -45,8 +45,8 @@ import { deleteFromTimelines } from 'soapbox/actions/timelines.ts'; import { useDeleteGroupStatus } from 'soapbox/api/hooks/groups/useDeleteGroupStatus.ts'; import { useBlockGroupMember, useBookmark, useGroup, useGroupRelationship, useMuteGroup, useUnmuteGroup } from 'soapbox/api/hooks/index.ts'; import DropdownMenu from 'soapbox/components/dropdown-menu/index.ts'; +import PureStatusReactionWrapper from 'soapbox/components/pure-status-reaction-wrapper.tsx'; import StatusActionButton from 'soapbox/components/status-action-button.tsx'; -import StatusReactionWrapper from 'soapbox/components/status-reaction-wrapper.tsx'; import HStack from 'soapbox/components/ui/hstack.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useAppSelector } from 'soapbox/hooks/useAppSelector.ts'; @@ -805,7 +805,7 @@ const PureStatusActionBar: React.FC = ({ )} {features.emojiReacts ? ( - + = ({ emoji={meEmojiReact} theme={statusActionButtonTheme} /> - + ) : ( Date: Wed, 18 Dec 2024 10:54:27 -0300 Subject: [PATCH 12/16] refactor: move useFavourite to 'src/api/hooks' --- src/api/hooks/index.ts | 1 + src/{hooks => api/hooks/statuses}/useFavourite.ts | 0 src/components/pure-status-action-bar.tsx | 3 +-- src/components/pure-status.tsx | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename src/{hooks => api/hooks/statuses}/useFavourite.ts (100%) diff --git a/src/api/hooks/index.ts b/src/api/hooks/index.ts index 001eb6322..8ae1a44ff 100644 --- a/src/api/hooks/index.ts +++ b/src/api/hooks/index.ts @@ -46,6 +46,7 @@ export { useUpdateGroupTag } from './groups/useUpdateGroupTag.ts'; // Statuses export { useBookmarks } from './statuses/useBookmarks.ts'; export { useBookmark } from './statuses/useBookmark.ts'; +export { useFavourite } from './statuses/useFavourite.ts'; // Streaming export { useUserStream } from './streaming/useUserStream.ts'; diff --git a/src/hooks/useFavourite.ts b/src/api/hooks/statuses/useFavourite.ts similarity index 100% rename from src/hooks/useFavourite.ts rename to src/api/hooks/statuses/useFavourite.ts diff --git a/src/components/pure-status-action-bar.tsx b/src/components/pure-status-action-bar.tsx index aee22adbd..d3aa21401 100644 --- a/src/components/pure-status-action-bar.tsx +++ b/src/components/pure-status-action-bar.tsx @@ -43,7 +43,7 @@ import { ReportableEntities } from 'soapbox/actions/reports.ts'; import { deleteStatus, editStatus, toggleMuteStatus } from 'soapbox/actions/statuses.ts'; import { deleteFromTimelines } from 'soapbox/actions/timelines.ts'; import { useDeleteGroupStatus } from 'soapbox/api/hooks/groups/useDeleteGroupStatus.ts'; -import { useBlockGroupMember, useBookmark, useGroup, useGroupRelationship, useMuteGroup, useUnmuteGroup } from 'soapbox/api/hooks/index.ts'; +import { useBlockGroupMember, useBookmark, useGroup, useGroupRelationship, useMuteGroup, useUnmuteGroup, useFavourite } from 'soapbox/api/hooks/index.ts'; import DropdownMenu from 'soapbox/components/dropdown-menu/index.ts'; import PureStatusReactionWrapper from 'soapbox/components/pure-status-reaction-wrapper.tsx'; import StatusActionButton from 'soapbox/components/status-action-button.tsx'; @@ -51,7 +51,6 @@ import HStack from 'soapbox/components/ui/hstack.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useAppSelector } from 'soapbox/hooks/useAppSelector.ts'; import { useDislike } from 'soapbox/hooks/useDislike.ts'; -import { useFavourite } from 'soapbox/hooks/useFavourite.ts'; import { useFeatures } from 'soapbox/hooks/useFeatures.ts'; import { useInitReport } from 'soapbox/hooks/useInitReport.ts'; import { useOwnAccount } from 'soapbox/hooks/useOwnAccount.ts'; diff --git a/src/components/pure-status.tsx b/src/components/pure-status.tsx index 93a1e0fa2..31e9e5ded 100644 --- a/src/components/pure-status.tsx +++ b/src/components/pure-status.tsx @@ -8,6 +8,7 @@ import { Link, useHistory } from 'react-router-dom'; import { openModal } from 'soapbox/actions/modals.ts'; import { unfilterStatus } from 'soapbox/actions/statuses.ts'; +import { useFavourite } from 'soapbox/api/hooks/index.ts'; import PureEventPreview from 'soapbox/components/pure-event-preview.tsx'; import PureStatusActionBar from 'soapbox/components/pure-status-action-bar.tsx'; import PureStatusContent from 'soapbox/components/pure-status-content.tsx'; @@ -22,7 +23,6 @@ import AccountContainer from 'soapbox/containers/account-container.tsx'; import QuotedStatus from 'soapbox/features/status/containers/quoted-status-container.tsx'; import { HotKeys } from 'soapbox/features/ui/components/hotkeys.tsx'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; -import { useFavourite } from 'soapbox/hooks/useFavourite.ts'; import { useMentionCompose } from 'soapbox/hooks/useMentionCompose.ts'; import { useReblog } from 'soapbox/hooks/useReblog.ts'; import { useReplyCompose } from 'soapbox/hooks/useReplyCompose.ts'; From d2126f60f22927e32da040ad9310ee84f7c6c8c6 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Wed, 18 Dec 2024 21:16:08 -0300 Subject: [PATCH 13/16] refactor: use statusSchema.parse rather than statusSchema.safeParse we want to throw any errors so they are catched --- src/api/hooks/statuses/useBookmark.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/hooks/statuses/useBookmark.ts b/src/api/hooks/statuses/useBookmark.ts index 4bb45f2a5..a64da3d28 100644 --- a/src/api/hooks/statuses/useBookmark.ts +++ b/src/api/hooks/statuses/useBookmark.ts @@ -59,9 +59,9 @@ function useBookmark() { try { const response = await api.post(`/api/v1/statuses/${statusId}/bookmark`); - const result = statusSchema.safeParse(await response.json()); - if (result.success) { - dispatch(importEntities([result.data], Entities.STATUSES, 'bookmarks', 'start')); + const result = statusSchema.parse(await response.json()); + if (result) { + dispatch(importEntities([result], Entities.STATUSES, 'bookmarks', 'start')); } return { success: true }; } catch (e) { From afd1f49e593fd7c2541a2c3f976777fafe304877 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Thu, 19 Dec 2024 18:51:10 -0300 Subject: [PATCH 14/16] refactor: create useReaction hook, used in PureStatusReactionWrapper componet --- src/api/hooks/index.ts | 1 + src/api/hooks/statuses/useReaction.ts | 125 ++++++++++++++++++ .../pure-status-reaction-wrapper.tsx | 8 +- 3 files changed, 129 insertions(+), 5 deletions(-) create mode 100644 src/api/hooks/statuses/useReaction.ts diff --git a/src/api/hooks/index.ts b/src/api/hooks/index.ts index 8ae1a44ff..8a958fd3c 100644 --- a/src/api/hooks/index.ts +++ b/src/api/hooks/index.ts @@ -47,6 +47,7 @@ export { useUpdateGroupTag } from './groups/useUpdateGroupTag.ts'; export { useBookmarks } from './statuses/useBookmarks.ts'; export { useBookmark } from './statuses/useBookmark.ts'; export { useFavourite } from './statuses/useFavourite.ts'; +export { useReaction } from './statuses/useReaction.ts'; // Streaming export { useUserStream } from './streaming/useUserStream.ts'; diff --git a/src/api/hooks/statuses/useReaction.ts b/src/api/hooks/statuses/useReaction.ts new file mode 100644 index 000000000..139ea977d --- /dev/null +++ b/src/api/hooks/statuses/useReaction.ts @@ -0,0 +1,125 @@ +import { useFavourite } from 'soapbox/api/hooks/index.ts'; +import { importEntities } from 'soapbox/entity-store/actions.ts'; +import { Entities } from 'soapbox/entity-store/entities.ts'; +import { useTransaction } from 'soapbox/entity-store/hooks/index.ts'; +import { useApi } from 'soapbox/hooks/useApi.ts'; +import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; +import { useGetState } from 'soapbox/hooks/useGetState.ts'; +import { EmojiReaction, Status as StatusEntity, statusSchema } from 'soapbox/schemas/index.ts'; +import { isLoggedIn } from 'soapbox/utils/auth.ts'; + +export function useReaction() { + const api = useApi(); + const getState = useGetState(); + const dispatch = useAppDispatch(); + const { transaction } = useTransaction(); + const { favourite, unfavourite } = useFavourite(); + + function emojiReactEffect(statusId: string, emoji: string) { + transaction({ + Statuses: { + [statusId]: (status) => { + // Get the emoji already present in the status reactions, if it exists. + const currentEmoji = status.reactions.find((value) => value.name === emoji); + // If the emoji doesn't exist, append it to the array and return. + if (!currentEmoji) { + return ({ + ...status, + reactions: [...status.reactions, { me: true, name: emoji, count: 1 }], + }); + } + // if the emoji exists in the status reactions, then just update the array and return. + return ({ + ...status, + reactions: status.reactions.map((val) => { + if (val.name === emoji) { + return { ...val, me: true, count: (val.count ?? 0) + 1 }; + } + return val; + }), + }); + }, + }, + }); + } + + function unemojiReactEffect(statusId: string, emoji: string) { + transaction({ + Statuses: { + [statusId]: (status) => { + return ({ + ...status, + reactions: status.reactions.map((val) => { + if (val.name === emoji && val.me === true) { + return { ...val, me: false, count: (val.count ?? 1) - 1 }; + } + return val; + }), + }); + }, + }, + }); + } + + const emojiReact = async (status: StatusEntity, emoji: string) => { // TODO: add custom emoji support + if (!isLoggedIn(getState)) return; + emojiReactEffect(status.id, emoji); + + try { + const response = await api.put(`/api/v1/pleroma/statuses/${status.id}/reactions/${emoji}`); + const result = statusSchema.parse(await response.json()); + if (result) { + dispatch(importEntities([result], Entities.STATUSES)); + } + } catch (e) { + unemojiReactEffect(status.id, emoji); + } + }; + + const unEmojiReact = async (status: StatusEntity, emoji: string) => { + if (!isLoggedIn(getState)) return; + unemojiReactEffect(status.id, emoji); + + try { + const response = await api.delete(`/api/v1/pleroma/statuses/${status.id}/reactions/${emoji}`); + const result = statusSchema.parse(await response.json()); + if (result) { + dispatch(importEntities([result], Entities.STATUSES)); + } + } catch (e) { + emojiReactEffect(status.id, emoji); + } + }; + + const simpleEmojiReact = async (status: StatusEntity, emoji: string) => { + const emojiReacts: readonly EmojiReaction[] = status.reactions; + + // Undo a standard favourite + if (emoji === '👍' && status.favourited) return unfavourite(status.id); + + // Undo an emoji reaction + const undo = emojiReacts.filter(e => e.me === true && e.name === emoji).length > 0; + if (undo) return unEmojiReact(status, emoji); + + try { + await Promise.all([ + ...emojiReacts + .filter((emojiReact) => emojiReact.me === true) + // Remove all existing emoji reactions by the user before adding a new one. If 'emoji' is an 'apple' and the status already has 'banana' as an emoji, then remove 'banana' + .map(emojiReact => unEmojiReact(status, emojiReact.name)), + // Remove existing standard like, if it exists + status.favourited && unfavourite(status.id), + ]); + + if (emoji === '👍') { + favourite(status.id); + } else { + emojiReact(status, emoji); + } + } catch (err) { + console.error(err); + } + }; + + return { emojiReact, unEmojiReact, simpleEmojiReact }; +} diff --git a/src/components/pure-status-reaction-wrapper.tsx b/src/components/pure-status-reaction-wrapper.tsx index 63c66ec73..c242d57b6 100644 --- a/src/components/pure-status-reaction-wrapper.tsx +++ b/src/components/pure-status-reaction-wrapper.tsx @@ -1,7 +1,7 @@ import { useState, useEffect, useRef, cloneElement } from 'react'; -import { simpleEmojiReact } from 'soapbox/actions/emoji-reacts.ts'; import { openModal } from 'soapbox/actions/modals.ts'; +import { useReaction } from 'soapbox/api/hooks/index.ts'; import EmojiSelector from 'soapbox/components/ui/emoji-selector.tsx'; import Portal from 'soapbox/components/ui/portal.tsx'; import { Entities } from 'soapbox/entity-store/entities.ts'; @@ -10,11 +10,8 @@ import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useGetState } from 'soapbox/hooks/useGetState.ts'; import { useOwnAccount } from 'soapbox/hooks/useOwnAccount.ts'; import { userTouching } from 'soapbox/is-mobile.ts'; -import { normalizeStatus } from 'soapbox/normalizers/index.ts'; import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; -import type { Status as LegacyStatus } from 'soapbox/types/entities.ts'; - interface IPureStatusReactionWrapper { statusId: string; children: JSX.Element; @@ -27,6 +24,7 @@ const PureStatusReactionWrapper: React.FC = ({ statu const getState = useGetState(); const status = selectEntity(getState(), Entities.STATUSES, statusId); + const { simpleEmojiReact } = useReaction(); const timeout = useRef(); const [visible, setVisible] = useState(false); @@ -71,7 +69,7 @@ const PureStatusReactionWrapper: React.FC = ({ statu const handleReact = (emoji: string, custom?: string): void => { if (ownAccount) { - dispatch(simpleEmojiReact(normalizeStatus(status) as LegacyStatus, emoji, custom)); + simpleEmojiReact(status, emoji); } else { handleUnauthorized(); } From b8da3e4f0c1bb7118ff516936ef38eaef13a77d0 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Thu, 19 Dec 2024 20:23:54 -0300 Subject: [PATCH 15/16] refactor: get status in new entity store as a fallback --- src/api/hooks/statuses/useFavourite.ts | 36 +++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/api/hooks/statuses/useFavourite.ts b/src/api/hooks/statuses/useFavourite.ts index 54158e9b6..f406ad78f 100644 --- a/src/api/hooks/statuses/useFavourite.ts +++ b/src/api/hooks/statuses/useFavourite.ts @@ -1,29 +1,59 @@ import { favourite as favouriteAction, unfavourite as unfavouriteAction, toggleFavourite as toggleFavouriteAction } from 'soapbox/actions/interactions.ts'; +import { Entities } from 'soapbox/entity-store/entities.ts'; +import { selectEntity } from 'soapbox/entity-store/selectors.ts'; import { useAppDispatch } from 'soapbox/hooks/useAppDispatch.ts'; import { useGetState } from 'soapbox/hooks/useGetState.ts'; +import { normalizeStatus } from 'soapbox/normalizers/index.ts'; +import { Status as StatusEntity } from 'soapbox/schemas/index.ts'; + +import type { Status as LegacyStatus } from 'soapbox/types/entities.ts'; export function useFavourite() { const getState = useGetState(); const dispatch = useAppDispatch(); const favourite = (statusId: string) => { - const status = getState().statuses.get(statusId); + let status: undefined|LegacyStatus|StatusEntity = getState().statuses.get(statusId); + if (status) { dispatch(favouriteAction(status)); + return; + } + + status = selectEntity(getState(), Entities.STATUSES, statusId); + if (status) { + dispatch(favouriteAction(normalizeStatus(status) as LegacyStatus)); + return; } }; const unfavourite = (statusId: string) => { - const status = getState().statuses.get(statusId); + let status: undefined|LegacyStatus|StatusEntity = getState().statuses.get(statusId); + if (status) { dispatch(unfavouriteAction(status)); + return; + } + + status = selectEntity(getState(), Entities.STATUSES, statusId); + if (status) { + dispatch(unfavouriteAction(normalizeStatus(status) as LegacyStatus)); + return; } }; const toggleFavourite = (statusId: string) => { - const status = getState().statuses.get(statusId); + let status: undefined|LegacyStatus|StatusEntity = getState().statuses.get(statusId); + if (status) { dispatch(toggleFavouriteAction(status)); + return; + } + + status = selectEntity(getState(), Entities.STATUSES, statusId); + if (status) { + dispatch(toggleFavouriteAction(normalizeStatus(status) as LegacyStatus)); + return; } }; From b344de842596cffe8a85cbe1587a7ed583028c1a Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 20 Dec 2024 14:00:08 -0300 Subject: [PATCH 16/16] refactor: remove bookmarks actions --- src/actions/bookmarks.ts | 102 ----------------------------------- src/reducers/status-lists.ts | 18 ------- 2 files changed, 120 deletions(-) delete mode 100644 src/actions/bookmarks.ts diff --git a/src/actions/bookmarks.ts b/src/actions/bookmarks.ts deleted file mode 100644 index fdf6c9237..000000000 --- a/src/actions/bookmarks.ts +++ /dev/null @@ -1,102 +0,0 @@ -import api from '../api/index.ts'; - -import { importFetchedStatuses } from './importer/index.ts'; - -import type { AppDispatch, RootState } from 'soapbox/store.ts'; -import type { APIEntity } from 'soapbox/types/entities.ts'; - -const BOOKMARKED_STATUSES_FETCH_REQUEST = 'BOOKMARKED_STATUSES_FETCH_REQUEST'; -const BOOKMARKED_STATUSES_FETCH_SUCCESS = 'BOOKMARKED_STATUSES_FETCH_SUCCESS'; -const BOOKMARKED_STATUSES_FETCH_FAIL = 'BOOKMARKED_STATUSES_FETCH_FAIL'; - -const BOOKMARKED_STATUSES_EXPAND_REQUEST = 'BOOKMARKED_STATUSES_EXPAND_REQUEST'; -const BOOKMARKED_STATUSES_EXPAND_SUCCESS = 'BOOKMARKED_STATUSES_EXPAND_SUCCESS'; -const BOOKMARKED_STATUSES_EXPAND_FAIL = 'BOOKMARKED_STATUSES_EXPAND_FAIL'; - -const noOp = () => new Promise(f => f(undefined)); - -const fetchBookmarkedStatuses = () => - (dispatch: AppDispatch, getState: () => RootState) => { - if (getState().status_lists.get('bookmarks')?.isLoading) { - return dispatch(noOp); - } - - dispatch(fetchBookmarkedStatusesRequest()); - - return api(getState).get('/api/v1/bookmarks').then(async (response) => { - const next = response.next(); - const data = await response.json(); - dispatch(importFetchedStatuses(data)); - return dispatch(fetchBookmarkedStatusesSuccess(data, next)); - }).catch(error => { - dispatch(fetchBookmarkedStatusesFail(error)); - }); - }; - -const fetchBookmarkedStatusesRequest = () => ({ - type: BOOKMARKED_STATUSES_FETCH_REQUEST, -}); - -const fetchBookmarkedStatusesSuccess = (statuses: APIEntity[], next: string | null) => ({ - type: BOOKMARKED_STATUSES_FETCH_SUCCESS, - statuses, - next, -}); - -const fetchBookmarkedStatusesFail = (error: unknown) => ({ - type: BOOKMARKED_STATUSES_FETCH_FAIL, - error, -}); - -const expandBookmarkedStatuses = () => - (dispatch: AppDispatch, getState: () => RootState) => { - const bookmarks = 'bookmarks'; - const url = getState().status_lists.get(bookmarks)?.next || null; - - if (url === null || getState().status_lists.get(bookmarks)?.isLoading) { - return dispatch(noOp); - } - - dispatch(expandBookmarkedStatusesRequest()); - - return api(getState).get(url).then(async (response) => { - const next = response.next(); - const data = await response.json(); - dispatch(importFetchedStatuses(data)); - return dispatch(expandBookmarkedStatusesSuccess(data, next)); - }).catch(error => { - dispatch(expandBookmarkedStatusesFail(error)); - }); - }; - -const expandBookmarkedStatusesRequest = () => ({ - type: BOOKMARKED_STATUSES_EXPAND_REQUEST, -}); - -const expandBookmarkedStatusesSuccess = (statuses: APIEntity[], next: string | null) => ({ - type: BOOKMARKED_STATUSES_EXPAND_SUCCESS, - statuses, - next, -}); - -const expandBookmarkedStatusesFail = (error: unknown) => ({ - type: BOOKMARKED_STATUSES_EXPAND_FAIL, - error, -}); - -export { - BOOKMARKED_STATUSES_FETCH_REQUEST, - BOOKMARKED_STATUSES_FETCH_SUCCESS, - BOOKMARKED_STATUSES_FETCH_FAIL, - BOOKMARKED_STATUSES_EXPAND_REQUEST, - BOOKMARKED_STATUSES_EXPAND_SUCCESS, - BOOKMARKED_STATUSES_EXPAND_FAIL, - fetchBookmarkedStatuses, - fetchBookmarkedStatusesRequest, - fetchBookmarkedStatusesSuccess, - fetchBookmarkedStatusesFail, - expandBookmarkedStatuses, - expandBookmarkedStatusesRequest, - expandBookmarkedStatusesSuccess, - expandBookmarkedStatusesFail, -}; diff --git a/src/reducers/status-lists.ts b/src/reducers/status-lists.ts index 00df43043..ea1185e56 100644 --- a/src/reducers/status-lists.ts +++ b/src/reducers/status-lists.ts @@ -14,14 +14,6 @@ import { } from 'soapbox/actions/status-quotes.ts'; import { STATUS_CREATE_SUCCESS } from 'soapbox/actions/statuses.ts'; -import { - BOOKMARKED_STATUSES_FETCH_REQUEST, - BOOKMARKED_STATUSES_FETCH_SUCCESS, - BOOKMARKED_STATUSES_FETCH_FAIL, - BOOKMARKED_STATUSES_EXPAND_REQUEST, - BOOKMARKED_STATUSES_EXPAND_SUCCESS, - BOOKMARKED_STATUSES_EXPAND_FAIL, -} from '../actions/bookmarks.ts'; import { RECENT_EVENTS_FETCH_REQUEST, RECENT_EVENTS_FETCH_SUCCESS, @@ -156,16 +148,6 @@ export default function statusLists(state = initialState, action: AnyAction) { return normalizeList(state, `favourites:${action.accountId}`, action.statuses, action.next); case ACCOUNT_FAVOURITED_STATUSES_EXPAND_SUCCESS: return appendToList(state, `favourites:${action.accountId}`, action.statuses, action.next); - case BOOKMARKED_STATUSES_FETCH_REQUEST: - case BOOKMARKED_STATUSES_EXPAND_REQUEST: - return setLoading(state, 'bookmarks', true); - case BOOKMARKED_STATUSES_FETCH_FAIL: - case BOOKMARKED_STATUSES_EXPAND_FAIL: - return setLoading(state, 'bookmarks', false); - case BOOKMARKED_STATUSES_FETCH_SUCCESS: - return normalizeList(state, 'bookmarks', action.statuses, action.next); - case BOOKMARKED_STATUSES_EXPAND_SUCCESS: - return appendToList(state, 'bookmarks', action.statuses, action.next); case FAVOURITE_SUCCESS: return prependOneToList(state, 'favourites', action.status); case UNFAVOURITE_SUCCESS: