Merge branch 'ts' into 'develop'

Reducers: TypeScript

See merge request soapbox-pub/soapbox-fe!1562
This commit is contained in:
marcin mikołajczak 2022-06-25 06:00:44 +00:00
commit dfbe05b390
65 changed files with 558 additions and 487 deletions

View File

@ -1,4 +1,4 @@
import { Map as ImmutableMap } from 'immutable'; import { Record as ImmutableRecord } from 'immutable';
import { __stub } from 'soapbox/api'; import { __stub } from 'soapbox/api';
import { mockStore } from 'soapbox/jest/test-helpers'; import { mockStore } from 'soapbox/jest/test-helpers';
@ -113,7 +113,7 @@ describe('expandBlocks()', () => {
beforeEach(() => { beforeEach(() => {
const state = rootReducer(undefined, {}) const state = rootReducer(undefined, {})
.set('me', '1234') .set('me', '1234')
.set('user_lists', ImmutableMap({ blocks: { next: null } })); .set('user_lists', ImmutableRecord({ blocks: { next: null } })());
store = mockStore(state); store = mockStore(state);
}); });
@ -129,7 +129,7 @@ describe('expandBlocks()', () => {
beforeEach(() => { beforeEach(() => {
const state = rootReducer(undefined, {}) const state = rootReducer(undefined, {})
.set('me', '1234') .set('me', '1234')
.set('user_lists', ImmutableMap({ blocks: { next: 'example' } })); .set('user_lists', ImmutableRecord({ blocks: { next: 'example' } })());
store = mockStore(state); store = mockStore(state);
}); });

View File

@ -410,7 +410,6 @@ const unmuteAccountFail = (error: AxiosError) => ({
error, error,
}); });
const subscribeAccount = (id: string, notifications?: boolean) => const subscribeAccount = (id: string, notifications?: boolean) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return null; if (!isLoggedIn(getState)) return null;
@ -465,7 +464,6 @@ const unsubscribeAccountFail = (error: AxiosError) => ({
error, error,
}); });
const removeFromFollowers = (id: string) => const removeFromFollowers = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
@ -532,7 +530,7 @@ const expandFollowers = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
const url = getState().user_lists.getIn(['followers', id, 'next']); const url = getState().user_lists.followers.get(id)?.next as string;
if (url === null) { if (url === null) {
return; return;
@ -606,7 +604,7 @@ const expandFollowing = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
const url = getState().user_lists.getIn(['following', id, 'next']); const url = getState().user_lists.following.get(id)!.next;
if (url === null) { if (url === null) {
return; return;
@ -713,7 +711,7 @@ const expandFollowRequests = () =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
const url = getState().user_lists.getIn(['follow_requests', 'next']); const url = getState().user_lists.follow_requests.next;
if (url === null) { if (url === null) {
return; return;
@ -771,7 +769,6 @@ const authorizeFollowRequestFail = (id: string, error: AxiosError) => ({
error, error,
}); });
const rejectFollowRequest = (id: string) => const rejectFollowRequest = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;

View File

@ -269,7 +269,6 @@ export const fetchOwnAccounts = () =>
}); });
}; };
export const register = (params: Record<string, any>) => export const register = (params: Record<string, any>) =>
(dispatch: AppDispatch) => { (dispatch: AppDispatch) => {
params.fullname = params.username; params.fullname = params.username;

View File

@ -58,7 +58,7 @@ const expandBlocks = () => (dispatch: React.Dispatch<AnyAction>, getState: () =>
if (!isLoggedIn(getState)) return null; if (!isLoggedIn(getState)) return null;
const nextLinkName = getNextLinkName(getState); const nextLinkName = getNextLinkName(getState);
const url = getState().user_lists.getIn(['blocks', 'next']); const url = getState().user_lists.blocks.next;
if (url === null) { if (url === null) {
return null; return null;

View File

@ -285,7 +285,7 @@ const submitCompose = (routerHistory: History, force = false) =>
}; };
dispatch(createStatus(params, idempotencyKey, statusId)).then(function(data) { dispatch(createStatus(params, idempotencyKey, statusId)).then(function(data) {
if (!statusId && data.visibility === 'direct' && getState().conversations.get('mounted') <= 0 && routerHistory) { if (!statusId && data.visibility === 'direct' && getState().conversations.mounted <= 0 && routerHistory) {
routerHistory.push('/messages'); routerHistory.push('/messages');
} }
handleComposeSubmit(dispatch, getState, data, status); handleComposeSubmit(dispatch, getState, data, status);

View File

@ -49,7 +49,7 @@ const expandConversations = ({ maxId }: Record<string, any> = {}) => (dispatch:
const params: Record<string, any> = { max_id: maxId }; const params: Record<string, any> = { max_id: maxId };
if (!maxId) { if (!maxId) {
params.since_id = getState().conversations.getIn(['items', 0, 'id']); params.since_id = getState().conversations.items.getIn([0, 'id']);
} }
const isLoadingRecent = !!params.since_id; const isLoadingRecent = !!params.since_id;

View File

@ -44,7 +44,7 @@ const expandDirectory = (params: Record<string, any>) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
dispatch(expandDirectoryRequest()); dispatch(expandDirectoryRequest());
const loadedItems = getState().user_lists.getIn(['directory', 'items']).size; const loadedItems = getState().user_lists.directory.items.size;
api(getState).get('/api/v1/directory', { params: { ...params, offset: loadedItems, limit: 20 } }).then(({ data }) => { api(getState).get('/api/v1/directory', { params: { ...params, offset: loadedItems, limit: 20 } }).then(({ data }) => {
dispatch(importFetchedAccounts(data)); dispatch(importFetchedAccounts(data));

View File

@ -65,7 +65,6 @@ const createFilter = (phrase: string, expires_at: string, context: Array<string>
}); });
}; };
const deleteFilter = (id: string) => const deleteFilter = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
dispatch({ type: FILTERS_DELETE_REQUEST }); dispatch({ type: FILTERS_DELETE_REQUEST });

View File

@ -253,7 +253,7 @@ const expandMembers = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
const url = getState().user_lists.getIn(['groups', id, 'next']); const url = getState().user_lists.groups.get(id)!.next;
if (url === null) { if (url === null) {
return; return;
@ -329,7 +329,7 @@ const expandRemovedAccounts = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
const url = getState().user_lists.getIn(['groups_removed_accounts', id, 'next']); const url = getState().user_lists.groups_removed_accounts.get(id)!.next;
if (url === null) { if (url === null) {
return; return;

View File

@ -22,14 +22,12 @@ const uploadMediaV1 = (data: FormData, onUploadProgress = noOp) =>
onUploadProgress: onUploadProgress, onUploadProgress: onUploadProgress,
}); });
const uploadMediaV2 = (data: FormData, onUploadProgress = noOp) => const uploadMediaV2 = (data: FormData, onUploadProgress = noOp) =>
(dispatch: any, getState: () => RootState) => (dispatch: any, getState: () => RootState) =>
api(getState).post('/api/v2/media', data, { api(getState).post('/api/v2/media', data, {
onUploadProgress: onUploadProgress, onUploadProgress: onUploadProgress,
}); });
const uploadMedia = (data: FormData, onUploadProgress = noOp) => const uploadMedia = (data: FormData, onUploadProgress = noOp) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const state = getState(); const state = getState();

View File

@ -162,7 +162,6 @@ const deleteStatusModal = (intl: IntlShape, statusId: string, afterConfirm = ()
})); }));
}; };
export { export {
deactivateUserModal, deactivateUserModal,
deleteUserModal, deleteUserModal,

View File

@ -57,7 +57,7 @@ const expandMutes = () =>
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;
const nextLinkName = getNextLinkName(getState); const nextLinkName = getNextLinkName(getState);
const url = getState().user_lists.getIn(['mutes', 'next']); const url = getState().user_lists.mutes.next;
if (url === null) { if (url === null) {
return; return;

View File

@ -38,7 +38,7 @@ const unsubscribe = ({ registration, subscription }: {
const sendSubscriptionToBackend = (subscription: PushSubscription, me: Me) => const sendSubscriptionToBackend = (subscription: PushSubscription, me: Me) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const alerts = getState().push_notifications.get('alerts').toJS(); const alerts = getState().push_notifications.alerts.toJS();
const params = { subscription, data: { alerts } }; const params = { subscription, data: { alerts } };
if (me) { if (me) {
@ -82,7 +82,7 @@ const register = () =>
// We have a subscription, check if it is still valid // We have a subscription, check if it is still valid
const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey!)).toString(); const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey!)).toString();
const subscriptionServerKey = urlBase64ToUint8Array(vapidKey).toString(); const subscriptionServerKey = urlBase64ToUint8Array(vapidKey).toString();
const serverEndpoint = getState().push_notifications.getIn(['subscription', 'endpoint']); const serverEndpoint = getState().push_notifications.subscription?.endpoint;
// If the VAPID public key did not change and the endpoint corresponds // If the VAPID public key did not change and the endpoint corresponds
// to the endpoint saved in the backend, the subscription is valid // to the endpoint saved in the backend, the subscription is valid
@ -136,7 +136,7 @@ const register = () =>
const saveSettings = () => const saveSettings = () =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const state = getState().push_notifications; const state = getState().push_notifications;
const alerts = state.get('alerts'); const alerts = state.alerts;
const data = { alerts }; const data = { alerts };
const me = getState().me; const me = getState().me;

View File

@ -242,7 +242,6 @@ const fetchStatusWithContext = (id: string) =>
} }
}; };
const muteStatus = (id: string) => const muteStatus = (id: string) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
if (!isLoggedIn(getState)) return; if (!isLoggedIn(getState)) return;

View File

@ -82,7 +82,7 @@ const updateTimelineQueue = (timeline: string, statusId: string, accept: ((statu
const dequeueTimeline = (timelineId: string, expandFunc?: (lastStatusId: string) => void, optionalExpandArgs?: any) => const dequeueTimeline = (timelineId: string, expandFunc?: (lastStatusId: string) => void, optionalExpandArgs?: any) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const state = getState(); const state = getState();
const queuedCount = state.timelines.getIn([timelineId, 'totalQueuedItemsCount'], 0); const queuedCount = state.timelines.get(timelineId)?.totalQueuedItemsCount || 0;
if (queuedCount <= 0) return; if (queuedCount <= 0) return;
@ -136,16 +136,16 @@ const parseTags = (tags: Record<string, any[]> = {}, mode: 'any' | 'all' | 'none
const expandTimeline = (timelineId: string, path: string, params: Record<string, any> = {}, done = noOp) => const expandTimeline = (timelineId: string, path: string, params: Record<string, any> = {}, done = noOp) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const timeline = getState().timelines.get(timelineId) || ImmutableMap(); const timeline = getState().timelines.get(timelineId) || {} as Record<string, any>;
const isLoadingMore = !!params.max_id; const isLoadingMore = !!params.max_id;
if (timeline.get('isLoading')) { if (timeline.isLoading) {
done(); done();
return dispatch(noOpAsync()); return dispatch(noOpAsync());
} }
if (!params.max_id && !params.pinned && timeline.get('items', ImmutableOrderedSet()).size > 0) { if (!params.max_id && !params.pinned && (timeline.items || ImmutableOrderedSet()).size > 0) {
params.since_id = timeline.getIn(['items', 0]); params.since_id = timeline.items || 0;
} }
const isLoadingRecent = !!params.since_id; const isLoadingRecent = !!params.since_id;

View File

@ -59,7 +59,6 @@ const removeStoredVerification = () => {
localStorage.removeItem(LOCAL_STORAGE_VERIFICATION_KEY); localStorage.removeItem(LOCAL_STORAGE_VERIFICATION_KEY);
}; };
/** /**
* Fetch and return the Registration token for Pepe. * Fetch and return the Registration token for Pepe.
*/ */
@ -207,7 +206,6 @@ const fetchRegistrationToken = () =>
return null; return null;
} }
return api(getState).post('/api/v1/pepe/registrations') return api(getState).post('/api/v1/pepe/registrations')
.then(response => { .then(response => {
updateStorage({ token: response.data.access_token }); updateStorage({ token: response.data.access_token });

View File

@ -15,7 +15,7 @@ interface IBirthdayPanel {
const BirthdayPanel = ({ limit }: IBirthdayPanel) => { const BirthdayPanel = ({ limit }: IBirthdayPanel) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const birthdays: ImmutableOrderedSet<string> = useAppSelector(state => state.user_lists.getIn(['birthday_reminders', state.me], ImmutableOrderedSet())); const birthdays: ImmutableOrderedSet<string> = useAppSelector(state => state.user_lists.birthday_reminders.get(state.me as string)?.items || ImmutableOrderedSet());
const birthdaysToRender = birthdays.slice(0, limit); const birthdaysToRender = birthdays.slice(0, limit);
React.useEffect(() => { React.useEffect(() => {

View File

@ -171,7 +171,6 @@ class ErrorBoundary extends React.PureComponent<Props, State> {
/> />
)} )}
{browser && ( {browser && (
<Stack> <Stack>
<Text weight='semibold'><FormattedMessage id='alert.unexpected.browser' defaultMessage='Browser' /></Text> <Text weight='semibold'><FormattedMessage id='alert.unexpected.browser' defaultMessage='Browser' /></Text>

View File

@ -1,4 +1,3 @@
import { OrderedSet as ImmutableOrderedSet } from 'immutable';
import React from 'react'; import React from 'react';
import { FormattedMessage } from 'react-intl'; import { FormattedMessage } from 'react-intl';
@ -19,7 +18,7 @@ const SidebarNavigation = () => {
const account = useOwnAccount(); const account = useOwnAccount();
const notificationCount = useAppSelector((state) => state.notifications.get('unread')); const notificationCount = useAppSelector((state) => state.notifications.get('unread'));
const chatsCount = useAppSelector((state) => state.chats.items.reduce((acc, curr) => acc + Math.min(curr.unread || 0, 1), 0)); const chatsCount = useAppSelector((state) => state.chats.items.reduce((acc, curr) => acc + Math.min(curr.unread || 0, 1), 0));
const followRequestsCount = useAppSelector((state) => state.user_lists.getIn(['follow_requests', 'items'], ImmutableOrderedSet()).count()); const followRequestsCount = useAppSelector((state) => state.user_lists.follow_requests.items.count());
const dashboardCount = useAppSelector((state) => state.admin.openReports.count() + state.admin.awaitingApproval.count()); const dashboardCount = useAppSelector((state) => state.admin.openReports.count() + state.admin.awaitingApproval.count());
const features = getFeatures(instance); const features = getFeatures(instance);

View File

@ -50,7 +50,7 @@ interface IModal {
/** Don't focus the "confirm" button on mount. */ /** Don't focus the "confirm" button on mount. */
skipFocus?: boolean, skipFocus?: boolean,
/** Title text for the modal. */ /** Title text for the modal. */
title: React.ReactNode, title?: React.ReactNode,
width?: Widths, width?: Widths,
} }
@ -86,28 +86,32 @@ const Modal: React.FC<IModal> = ({
<div data-testid='modal' className={classNames('block w-full p-6 mx-auto overflow-hidden text-left align-middle transition-all transform bg-white dark:bg-slate-800 text-black dark:text-white shadow-xl rounded-2xl pointer-events-auto', widths[width])}> <div data-testid='modal' className={classNames('block w-full p-6 mx-auto overflow-hidden text-left align-middle transition-all transform bg-white dark:bg-slate-800 text-black dark:text-white shadow-xl rounded-2xl pointer-events-auto', widths[width])}>
<div className='sm:flex sm:items-start w-full justify-between'> <div className='sm:flex sm:items-start w-full justify-between'>
<div className='w-full'> <div className='w-full'>
<div {title && (
className={classNames('w-full flex items-center gap-2', { <div
'flex-row-reverse': closePosition === 'left', className={classNames('w-full flex items-center gap-2', {
})} 'flex-row-reverse': closePosition === 'left',
> })}
<h3 className='flex-grow text-lg leading-6 font-medium text-gray-900 dark:text-white'> >
{title} <h3 className='flex-grow text-lg leading-6 font-medium text-gray-900 dark:text-white'>
</h3> {title}
</h3>
{onClose && ( {onClose && (
<IconButton <IconButton
src={closeIcon} src={closeIcon}
title={intl.formatMessage(messages.close)} title={intl.formatMessage(messages.close)}
onClick={onClose} onClick={onClose}
className='text-gray-500 hover:text-gray-700 dark:text-gray-300 dark:hover:text-gray-200' className='text-gray-500 hover:text-gray-700 dark:text-gray-300 dark:hover:text-gray-200'
/> />
)} )}
</div> </div>
)}
<div className={classNames('mt-2 w-full')}> {title ? (
{children} <div className='w-full mt-2'>
</div> {children}
</div>
) : children}
</div> </div>
</div> </div>
@ -124,7 +128,6 @@ const Modal: React.FC<IModal> = ({
)} )}
</div> </div>
<div className='flex flex-row space-x-2'> <div className='flex flex-row space-x-2'>
{secondaryAction && ( {secondaryAction && (
<Button <Button

View File

@ -63,8 +63,8 @@ const AccountGallery = () => {
}); });
const isAccount = useAppSelector((state) => !!state.accounts.get(accountId)); const isAccount = useAppSelector((state) => !!state.accounts.get(accountId));
const attachments: ImmutableList<Attachment> = useAppSelector((state) => getAccountGallery(state, accountId as string)); const attachments: ImmutableList<Attachment> = useAppSelector((state) => getAccountGallery(state, accountId as string));
const isLoading = useAppSelector((state) => state.timelines.getIn([`account:${accountId}:media`, 'isLoading'])); const isLoading = useAppSelector((state) => state.timelines.get(`account:${accountId}:media`)?.isLoading);
const hasMore = useAppSelector((state) => state.timelines.getIn([`account:${accountId}:media`, 'hasMore'])); const hasMore = useAppSelector((state) => state.timelines.get(`account:${accountId}:media`)?.hasMore);
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
const [width] = useState(323); const [width] = useState(323);

View File

@ -226,7 +226,6 @@ const mapDispatchToProps = (dispatch, { intl }) => ({
.catch(() => {}); .catch(() => {});
}, },
onPromoteToAdmin(account) { onPromoteToAdmin(account) {
const message = intl.formatMessage(messages.promotedToAdmin, { acct: account.get('acct') }); const message = intl.formatMessage(messages.promotedToAdmin, { acct: account.get('acct') });

View File

@ -21,8 +21,8 @@ const Blocks: React.FC = () => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const intl = useIntl(); const intl = useIntl();
const accountIds = useAppSelector((state) => state.user_lists.getIn(['blocks', 'items'])); const accountIds = useAppSelector((state) => state.user_lists.blocks.items);
const hasMore = useAppSelector((state) => !!state.user_lists.getIn(['blocks', 'next'])); const hasMore = useAppSelector((state) => !!state.user_lists.blocks.next);
React.useEffect(() => { React.useEffect(() => {
dispatch(fetchBlocks()); dispatch(fetchBlocks());
@ -47,7 +47,7 @@ const Blocks: React.FC = () => {
emptyMessage={emptyMessage} emptyMessage={emptyMessage}
itemClassName='pb-4' itemClassName='pb-4'
> >
{accountIds.map((id: string) => {accountIds.map((id) =>
<AccountContainer key={id} id={id} actionType='blocking' />, <AccountContainer key={id} id={id} actionType='blocking' />,
)} )}
</ScrollableList> </ScrollableList>

View File

@ -5,8 +5,6 @@ import { markConversationRead } from 'soapbox/actions/conversations';
import StatusContainer from 'soapbox/containers/status_container'; import StatusContainer from 'soapbox/containers/status_container';
import { useAppDispatch, useAppSelector } from 'soapbox/hooks'; import { useAppDispatch, useAppSelector } from 'soapbox/hooks';
import type { Map as ImmutableMap } from 'immutable';
interface IConversation { interface IConversation {
conversationId: string, conversationId: string,
onMoveUp: (id: string) => void, onMoveUp: (id: string) => void,
@ -18,12 +16,12 @@ const Conversation: React.FC<IConversation> = ({ conversationId, onMoveUp, onMov
const history = useHistory(); const history = useHistory();
const { accounts, unread, lastStatusId } = useAppSelector((state) => { const { accounts, unread, lastStatusId } = useAppSelector((state) => {
const conversation = state.conversations.get('items').find((x: ImmutableMap<string, any>) => x.get('id') === conversationId); const conversation = state.conversations.items.find(x => x.id === conversationId)!;
return { return {
accounts: conversation.get('accounts').map((accountId: string) => state.accounts.get(accountId, null)), accounts: conversation.accounts.map((accountId: string) => state.accounts.get(accountId, null)!),
unread: conversation.get('unread'), unread: conversation.unread,
lastStatusId: conversation.get('last_status', null), lastStatusId: conversation.last_status || null,
}; };
}); });

View File

@ -14,10 +14,10 @@ const ConversationsList: React.FC = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const ref = useRef<VirtuosoHandle>(null); const ref = useRef<VirtuosoHandle>(null);
const conversations = useAppSelector((state) => state.conversations.get('items')); const conversations = useAppSelector((state) => state.conversations.items);
const isLoading = useAppSelector((state) => state.conversations.get('isLoading', true)); const isLoading = useAppSelector((state) => state.conversations.isLoading);
const getCurrentIndex = (id: string) => conversations.findIndex((x: any) => x.get('id') === id); const getCurrentIndex = (id: string) => conversations.findIndex(x => x.id === id);
const handleMoveUp = (id: string) => { const handleMoveUp = (id: string) => {
const elementIndex = getCurrentIndex(id) - 1; const elementIndex = getCurrentIndex(id) - 1;
@ -60,8 +60,8 @@ const ConversationsList: React.FC = () => {
> >
{conversations.map((item: any) => ( {conversations.map((item: any) => (
<Conversation <Conversation
key={item.get('id')} key={item.id}
conversationId={item.get('id')} conversationId={item.id}
onMoveUp={handleMoveUp} onMoveUp={handleMoveUp}
onMoveDown={handleMoveDown} onMoveDown={handleMoveDown}
/> />

View File

@ -20,7 +20,7 @@ const DirectTimeline = () => {
const intl = useIntl(); const intl = useIntl();
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const hasUnread = useAppSelector((state) => state.timelines.getIn(['direct', 'unread']) > 0); const hasUnread = useAppSelector((state) => (state.timelines.get('direct')?.unread || 0) > 0);
useEffect(() => { useEffect(() => {
dispatch(expandDirectTimeline()); dispatch(expandDirectTimeline());

View File

@ -1,5 +1,4 @@
import classNames from 'classnames'; import classNames from 'classnames';
import { List as ImmutableList } from 'immutable';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { defineMessages, useIntl } from 'react-intl'; import { defineMessages, useIntl } from 'react-intl';
import { useDispatch } from 'react-redux'; import { useDispatch } from 'react-redux';
@ -28,8 +27,8 @@ const Directory = () => {
const { search } = useLocation(); const { search } = useLocation();
const params = new URLSearchParams(search); const params = new URLSearchParams(search);
const accountIds = useAppSelector((state) => state.user_lists.getIn(['directory', 'items'], ImmutableList())); const accountIds = useAppSelector((state) => state.user_lists.directory.items);
const isLoading = useAppSelector((state) => state.user_lists.getIn(['directory', 'isLoading'], true)); const isLoading = useAppSelector((state) => state.user_lists.directory.isLoading);
const title = useAppSelector((state) => state.instance.get('title')); const title = useAppSelector((state) => state.instance.get('title'));
const features = useAppSelector((state) => getFeatures(state.instance)); const features = useAppSelector((state) => getFeatures(state.instance));
@ -69,7 +68,7 @@ const Directory = () => {
</div> </div>
<div className={classNames('directory__list', { loading: isLoading })}> <div className={classNames('directory__list', { loading: isLoading })}>
{accountIds.map((accountId: string) => <AccountCard id={accountId} key={accountId} />)} {accountIds.map((accountId) => <AccountCard id={accountId} key={accountId} />)}
</div> </div>
<LoadMore onClick={handleLoadMore} visible={!isLoading} /> <LoadMore onClick={handleLoadMore} visible={!isLoading} />

View File

@ -24,8 +24,8 @@ const FollowRequests: React.FC = () => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const intl = useIntl(); const intl = useIntl();
const accountIds = useAppSelector<string[]>((state) => state.user_lists.getIn(['follow_requests', 'items'])); const accountIds = useAppSelector((state) => state.user_lists.follow_requests.items);
const hasMore = useAppSelector((state) => !!state.user_lists.getIn(['follow_requests', 'next'])); const hasMore = useAppSelector((state) => !!state.user_lists.follow_requests.next);
React.useEffect(() => { React.useEffect(() => {
dispatch(fetchFollowRequests()); dispatch(fetchFollowRequests());

View File

@ -48,8 +48,8 @@ const mapStateToProps = (state, { params, withReplies = false }) => {
accountId, accountId,
unavailable, unavailable,
isAccount: !!state.getIn(['accounts', accountId]), isAccount: !!state.getIn(['accounts', accountId]),
accountIds: state.getIn(['user_lists', 'followers', accountId, 'items']), accountIds: state.user_lists.followers.get(accountId)?.items,
hasMore: !!state.getIn(['user_lists', 'followers', accountId, 'next']), hasMore: !!state.user_lists.followers.get(accountId)?.next,
diffCount, diffCount,
}; };
}; };

View File

@ -48,8 +48,8 @@ const mapStateToProps = (state, { params, withReplies = false }) => {
accountId, accountId,
unavailable, unavailable,
isAccount: !!state.getIn(['accounts', accountId]), isAccount: !!state.getIn(['accounts', accountId]),
accountIds: state.getIn(['user_lists', 'following', accountId, 'items']), accountIds: state.user_lists.following.get(accountId)?.items,
hasMore: !!state.getIn(['user_lists', 'following', accountId, 'next']), hasMore: !!state.user_lists.following.get(accountId)?.next,
diffCount, diffCount,
}; };
}; };

View File

@ -18,8 +18,8 @@ import Column from '../../ui/components/column';
const mapStateToProps = (state, { params: { id } }) => ({ const mapStateToProps = (state, { params: { id } }) => ({
group: state.getIn(['groups', id]), group: state.getIn(['groups', id]),
accountIds: state.getIn(['user_lists', 'groups', id, 'items']), accountIds: state.user_lists.groups.get(id)?.items,
hasMore: !!state.getIn(['user_lists', 'groups', id, 'next']), hasMore: !!state.user_lists.groups.get(id)?.next,
}); });
export default @connect(mapStateToProps) export default @connect(mapStateToProps)

View File

@ -23,8 +23,8 @@ const messages = defineMessages({
const mapStateToProps = (state, { params: { id } }) => ({ const mapStateToProps = (state, { params: { id } }) => ({
group: state.getIn(['groups', id]), group: state.getIn(['groups', id]),
accountIds: state.getIn(['user_lists', 'groups_removed_accounts', id, 'items']), accountIds: state.user_lists.groups_removed_accounts.get(id)?.items,
hasMore: !!state.getIn(['user_lists', 'groups_removed_accounts', id, 'next']), hasMore: !!state.user_lists.groups_removed_accounts.get(id)?.next,
}); });
export default @connect(mapStateToProps) export default @connect(mapStateToProps)

View File

@ -16,7 +16,7 @@ const HomeTimeline: React.FC = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const polling = useRef<NodeJS.Timer | null>(null); const polling = useRef<NodeJS.Timer | null>(null);
const isPartial = useAppSelector(state => state.timelines.getIn(['home', 'isPartial']) === true); const isPartial = useAppSelector(state => state.timelines.get('home')?.isPartial === true);
const siteTitle = useAppSelector(state => state.instance.title); const siteTitle = useAppSelector(state => state.instance.title);
const handleLoadMore = (maxId: string) => { const handleLoadMore = (maxId: string) => {

View File

@ -26,7 +26,7 @@ const ListTimeline: React.FC = () => {
// const history = useHistory(); // const history = useHistory();
const list = useAppSelector((state) => state.lists.get(id)); const list = useAppSelector((state) => state.lists.get(id));
// const hasUnread = useAppSelector((state) => state.timelines.getIn([`list:${props.params.id}`, 'unread']) > 0); // const hasUnread = useAppSelector((state) => state.timelines.get(`list:${props.params.id}`)?.unread > 0);
useEffect(() => { useEffect(() => {
dispatch(fetchList(id)); dispatch(fetchList(id));

View File

@ -21,8 +21,8 @@ const Mutes: React.FC = () => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const intl = useIntl(); const intl = useIntl();
const accountIds = useAppSelector((state) => state.user_lists.getIn(['mutes', 'items'])); const accountIds = useAppSelector((state) => state.user_lists.mutes.items);
const hasMore = useAppSelector((state) => !!state.user_lists.getIn(['mutes', 'next'])); const hasMore = useAppSelector((state) => !!state.user_lists.mutes.next);
React.useEffect(() => { React.useEffect(() => {
dispatch(fetchMutes()); dispatch(fetchMutes());
@ -47,7 +47,7 @@ const Mutes: React.FC = () => {
emptyMessage={emptyMessage} emptyMessage={emptyMessage}
itemClassName='pb-4' itemClassName='pb-4'
> >
{accountIds.map((id: string) => {accountIds.map((id) =>
<AccountContainer key={id} id={id} actionType='muting' />, <AccountContainer key={id} id={id} actionType='muting' />,
)} )}
</ScrollableList> </ScrollableList>

View File

@ -91,8 +91,6 @@ const SuggestedAccountsStep = ({ onNext }: { onNext: () => void }) => {
<div className='sm:w-2/3 md:w-1/2 mx-auto'> <div className='sm:w-2/3 md:w-1/2 mx-auto'>
<Stack> <Stack>
<Stack justifyContent='center' space={2}> <Stack justifyContent='center' space={2}>
<Button <Button
block block

View File

@ -3,28 +3,29 @@ import { Map as ImmutableMap } from 'immutable';
import { normalizeStatus } from 'soapbox/normalizers/status'; import { normalizeStatus } from 'soapbox/normalizers/status';
import { calculateStatus } from 'soapbox/reducers/statuses'; import { calculateStatus } from 'soapbox/reducers/statuses';
import { makeGetAccount } from 'soapbox/selectors'; import { makeGetAccount } from 'soapbox/selectors';
import { RootState } from 'soapbox/store';
export const buildStatus = (state: RootState, scheduledStatus: ImmutableMap<string, any>) => { import type { ScheduledStatus } from 'soapbox/reducers/scheduled_statuses';
import type { RootState } from 'soapbox/store';
export const buildStatus = (state: RootState, scheduledStatus: ScheduledStatus) => {
const getAccount = makeGetAccount(); const getAccount = makeGetAccount();
const me = state.me as string; const me = state.me as string;
const params = scheduledStatus.get('params');
const account = getAccount(state, me); const account = getAccount(state, me);
const status = ImmutableMap({ const status = ImmutableMap({
account, account,
content: params.get('text', '').replace(new RegExp('\n', 'g'), '<br>'), /* eslint-disable-line no-control-regex */ content: scheduledStatus.text.replace(new RegExp('\n', 'g'), '<br>'), /* eslint-disable-line no-control-regex */
created_at: params.get('scheduled_at'), created_at: scheduledStatus.scheduled_at,
id: scheduledStatus.get('id'), id: scheduledStatus.id,
in_reply_to_id: params.get('in_reply_to_id'), in_reply_to_id: scheduledStatus.in_reply_to_id,
media_attachments: scheduledStatus.get('media_attachments'), media_attachments: scheduledStatus.media_attachments,
poll: params.get('poll'), poll: scheduledStatus.poll,
sensitive: params.get('sensitive'), sensitive: scheduledStatus.sensitive,
uri: `/scheduled_statuses/${scheduledStatus.get('id')}`, uri: `/scheduled_statuses/${scheduledStatus.id}`,
url: `/scheduled_statuses/${scheduledStatus.get('id')}`, url: `/scheduled_statuses/${scheduledStatus.id}`,
visibility: params.get('visibility'), visibility: scheduledStatus.visibility,
}); });
return calculateStatus(normalizeStatus(status)); return calculateStatus(normalizeStatus(status));

View File

@ -20,7 +20,7 @@ interface IScheduledStatus {
} }
const ScheduledStatus: React.FC<IScheduledStatus> = ({ statusId, ...other }) => { const ScheduledStatus: React.FC<IScheduledStatus> = ({ statusId, ...other }) => {
const status = useAppSelector((state) => buildStatus(state, state.scheduled_statuses.get(statusId))) as StatusEntity; const status = useAppSelector((state) => buildStatus(state, state.scheduled_statuses.get(statusId)!)) as StatusEntity;
if (!status) return null; if (!status) return null;

View File

@ -163,7 +163,6 @@ class DetailedStatus extends ImmutablePureComponent<IDetailedStatus, IDetailedSt
<HStack justifyContent='between' alignItems='center' className='py-2'> <HStack justifyContent='between' alignItems='center' className='py-2'>
<StatusInteractionBar status={status} /> <StatusInteractionBar status={status} />
<div className='detailed-status__timestamp'> <div className='detailed-status__timestamp'>
{statusTypeIcon} {statusTypeIcon}

View File

@ -11,7 +11,7 @@ interface IBirthdaysModal {
} }
const BirthdaysModal = ({ onClose }: IBirthdaysModal) => { const BirthdaysModal = ({ onClose }: IBirthdaysModal) => {
const accountIds = useAppSelector<string[]>(state => state.user_lists.getIn(['birthday_reminders', state.me])); const accountIds = useAppSelector(state => state.user_lists.birthday_reminders.get(state.me as string)?.items);
const onClickClose = () => { const onClickClose = () => {
onClose('BIRTHDAYS'); onClose('BIRTHDAYS');
@ -37,7 +37,6 @@ const BirthdaysModal = ({ onClose }: IBirthdaysModal) => {
); );
} }
return ( return (
<Modal <Modal
title={<FormattedMessage id='column.birthdays' defaultMessage='Birthdays' />} title={<FormattedMessage id='column.birthdays' defaultMessage='Birthdays' />}

View File

@ -1,14 +1,18 @@
import React from 'react'; import React from 'react';
import { Modal } from 'soapbox/components/ui';
import DetailedCryptoAddress from 'soapbox/features/crypto_donate/components/detailed_crypto_address'; import DetailedCryptoAddress from 'soapbox/features/crypto_donate/components/detailed_crypto_address';
import type { ICryptoAddress } from '../../crypto_donate/components/crypto_address'; import type { ICryptoAddress } from '../../crypto_donate/components/crypto_address';
const CryptoDonateModal: React.FC<ICryptoAddress> = (props) => { const CryptoDonateModal: React.FC<ICryptoAddress & { onClose: () => void }> = ({ onClose, ...props }) => {
return ( return (
<div className='modal-root__modal crypto-donate-modal'> <Modal onClose={onClose} width='xs'>
<DetailedCryptoAddress {...props} /> <div className='crypto-donate-modal'>
</div> <DetailedCryptoAddress {...props} />
</div>
</Modal>
); );
}; };

View File

@ -17,7 +17,7 @@ interface IFamiliarFollowersModal {
const FamiliarFollowersModal = ({ accountId, onClose }: IFamiliarFollowersModal) => { const FamiliarFollowersModal = ({ accountId, onClose }: IFamiliarFollowersModal) => {
const account = useAppSelector(state => getAccount(state, accountId)); const account = useAppSelector(state => getAccount(state, accountId));
const familiarFollowerIds: ImmutableOrderedSet<string> = useAppSelector(state => state.user_lists.getIn(['familiar_followers', accountId])); const familiarFollowerIds: ImmutableOrderedSet<string> = useAppSelector(state => state.user_lists.familiar_followers.get(accountId)?.items || ImmutableOrderedSet());
const onClickClose = () => { const onClickClose = () => {
onClose('FAMILIAR_FOLLOWERS'); onClose('FAMILIAR_FOLLOWERS');
@ -43,7 +43,6 @@ const FamiliarFollowersModal = ({ accountId, onClose }: IFamiliarFollowersModal)
); );
} }
return ( return (
<Modal <Modal
title={<FormattedMessage id='column.familiar_followers' defaultMessage='People you know following {name}' values={{ name: <span dangerouslySetInnerHTML={{ __html: account?.display_name_html || '' }} /> }} />} title={<FormattedMessage id='column.familiar_followers' defaultMessage='People you know following {name}' values={{ name: <span dangerouslySetInnerHTML={{ __html: account?.display_name_html || '' }} /> }} />}

View File

@ -15,7 +15,7 @@ interface IFavouritesModal {
const FavouritesModal: React.FC<IFavouritesModal> = ({ onClose, statusId }) => { const FavouritesModal: React.FC<IFavouritesModal> = ({ onClose, statusId }) => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const accountIds = useAppSelector((state) => state.user_lists.getIn(['favourited_by', statusId])); const accountIds = useAppSelector((state) => state.user_lists.favourited_by.get(statusId)?.items);
const fetchData = () => { const fetchData = () => {
dispatch(fetchFavourites(statusId)); dispatch(fetchFavourites(statusId));
@ -42,7 +42,7 @@ const FavouritesModal: React.FC<IFavouritesModal> = ({ onClose, statusId }) => {
emptyMessage={emptyMessage} emptyMessage={emptyMessage}
itemClassName='pb-3' itemClassName='pb-3'
> >
{accountIds.map((id: string) => {accountIds.map((id) =>
<AccountContainer key={id} id={id} />, <AccountContainer key={id} id={id} />,
)} )}
</ScrollableList> </ScrollableList>

View File

@ -30,7 +30,7 @@ const OtherActionsStep = ({ account }: IOtherActionsStep) => {
const features = useFeatures(); const features = useFeatures();
const intl = useIntl(); const intl = useIntl();
const statusIds = useAppSelector((state) => OrderedSet(state.timelines.getIn([`account:${account.id}:with_replies`, 'items'])).union(state.reports.new.status_ids) as OrderedSet<string>); const statusIds = useAppSelector((state) => OrderedSet(state.timelines.get(`account:${account.id}:with_replies`)!.items).union(state.reports.new.status_ids) as OrderedSet<string>);
const isBlocked = useAppSelector((state) => state.reports.new.block); const isBlocked = useAppSelector((state) => state.reports.new.block);
const isForward = useAppSelector((state) => state.reports.new.forward); const isForward = useAppSelector((state) => state.reports.new.forward);
const canForward = isRemote(account) && features.federating; const canForward = isRemote(account) && features.federating;

View File

@ -1,4 +1,4 @@
import { List as ImmutableList } from 'immutable'; import { OrderedSet as ImmutableOrderedSet } from 'immutable';
import React, { useEffect } from 'react'; import React, { useEffect } from 'react';
import { FormattedMessage } from 'react-intl'; import { FormattedMessage } from 'react-intl';
@ -16,7 +16,7 @@ interface IPinnedAccountsPanel {
const PinnedAccountsPanel: React.FC<IPinnedAccountsPanel> = ({ account, limit }) => { const PinnedAccountsPanel: React.FC<IPinnedAccountsPanel> = ({ account, limit }) => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const pinned = useAppSelector((state) => state.user_lists.getIn(['pinned', account.id, 'items'], ImmutableList())).slice(0, limit); const pinned = useAppSelector((state) => state.user_lists.pinned.get(account.id)?.items || ImmutableOrderedSet<string>()).slice(0, limit);
useEffect(() => { useEffect(() => {
dispatch(fetchPinnedAccounts(account.id)); dispatch(fetchPinnedAccounts(account.id));
@ -36,7 +36,7 @@ const PinnedAccountsPanel: React.FC<IPinnedAccountsPanel> = ({ account, limit })
}} }}
/>} />}
> >
{pinned && pinned.map((suggestion: string) => ( {pinned && pinned.map((suggestion) => (
<AccountContainer <AccountContainer
key={suggestion} key={suggestion}
id={suggestion} id={suggestion}

View File

@ -24,7 +24,7 @@ const ProfileFamiliarFollowers: React.FC<IProfileFamiliarFollowers> = ({ account
const dispatch = useDispatch(); const dispatch = useDispatch();
const me = useAppSelector((state) => state.me); const me = useAppSelector((state) => state.me);
const features = useFeatures(); const features = useFeatures();
const familiarFollowerIds: ImmutableOrderedSet<string> = useAppSelector(state => state.user_lists.getIn(['familiar_followers', account.id], ImmutableOrderedSet())); const familiarFollowerIds = useAppSelector(state => state.user_lists.familiar_followers.get(account.id)?.items || ImmutableOrderedSet<string>());
const familiarFollowers: ImmutableOrderedSet<Account | null> = useAppSelector(state => familiarFollowerIds.slice(0, 2).map(accountId => getAccount(state, accountId))); const familiarFollowers: ImmutableOrderedSet<Account | null> = useAppSelector(state => familiarFollowerIds.slice(0, 2).map(accountId => getAccount(state, accountId)));
useEffect(() => { useEffect(() => {

View File

@ -7,6 +7,7 @@ import ScrollableList from 'soapbox/components/scrollable_list';
import { Emoji, Modal, Spinner, Tabs } from 'soapbox/components/ui'; import { Emoji, Modal, Spinner, Tabs } from 'soapbox/components/ui';
import AccountContainer from 'soapbox/containers/account_container'; import AccountContainer from 'soapbox/containers/account_container';
import { useAppDispatch, useAppSelector } from 'soapbox/hooks'; import { useAppDispatch, useAppSelector } from 'soapbox/hooks';
import { ReactionRecord } from 'soapbox/reducers/user_lists';
import type { Item } from 'soapbox/components/ui/tabs/tabs'; import type { Item } from 'soapbox/components/ui/tabs/tabs';
@ -25,14 +26,10 @@ const ReactionsModal: React.FC<IReactionsModal> = ({ onClose, statusId, reaction
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const intl = useIntl(); const intl = useIntl();
const [reaction, setReaction] = useState(initialReaction); const [reaction, setReaction] = useState(initialReaction);
const reactions = useAppSelector<ImmutableList<{ const reactions = useAppSelector<ImmutableList<ReturnType<typeof ReactionRecord>> | undefined>((state) => {
accounts: Array<string>, const favourites = state.user_lists.favourited_by.get(statusId)?.items;
count: number, const reactions = state.user_lists.reactions.get(statusId)?.items;
name: string, return favourites && reactions && ImmutableList(favourites?.size ? [ReactionRecord({ accounts: favourites, count: favourites.size, name: '👍' })] : []).concat(reactions || []);
}>>((state) => {
const favourites = state.user_lists.getIn(['favourited_by', statusId]);
const reactions = state.user_lists.getIn(['reactions', statusId]);
return favourites && reactions && ImmutableList(favourites.size ? [{ accounts: favourites, count: favourites.size, name: '👍' }] : []).concat(reactions || []);
}); });
const fetchData = () => { const fetchData = () => {
@ -53,7 +50,7 @@ const ReactionsModal: React.FC<IReactionsModal> = ({ onClose, statusId, reaction
}, },
]; ];
reactions.forEach(reaction => items.push( reactions!.forEach(reaction => items.push(
{ {
text: <div className='flex items-center gap-1'> text: <div className='flex items-center gap-1'>
<Emoji className='w-4 h-4' emoji={reaction.name} /> <Emoji className='w-4 h-4' emoji={reaction.name} />
@ -73,7 +70,7 @@ const ReactionsModal: React.FC<IReactionsModal> = ({ onClose, statusId, reaction
const accounts = reactions && (reaction const accounts = reactions && (reaction
? reactions.find(({ name }) => name === reaction)?.accounts.map(account => ({ id: account, reaction: reaction })) ? reactions.find(({ name }) => name === reaction)?.accounts.map(account => ({ id: account, reaction: reaction }))
: reactions.map(({ accounts, name }) => accounts.map(account => ({ id: account, reaction: name }))).flatten()) as Array<{ id: string, reaction: string }>; : reactions.map(({ accounts, name }) => accounts.map(account => ({ id: account, reaction: name }))).flatten()) as ImmutableList<{ id: string, reaction: string }>;
let body; let body;
@ -97,7 +94,6 @@ const ReactionsModal: React.FC<IReactionsModal> = ({ onClose, statusId, reaction
</>); </>);
} }
return ( return (
<Modal <Modal
title={<FormattedMessage id='column.reactions' defaultMessage='Reactions' />} title={<FormattedMessage id='column.reactions' defaultMessage='Reactions' />}

View File

@ -15,7 +15,7 @@ interface IReblogsModal {
const ReblogsModal: React.FC<IReblogsModal> = ({ onClose, statusId }) => { const ReblogsModal: React.FC<IReblogsModal> = ({ onClose, statusId }) => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const accountIds = useAppSelector((state) => state.user_lists.getIn(['reblogged_by', statusId])); const accountIds = useAppSelector((state) => state.user_lists.reblogged_by.get(statusId)?.items);
const fetchData = () => { const fetchData = () => {
dispatch(fetchReblogs(statusId)); dispatch(fetchReblogs(statusId));
@ -43,14 +43,13 @@ const ReblogsModal: React.FC<IReblogsModal> = ({ onClose, statusId }) => {
emptyMessage={emptyMessage} emptyMessage={emptyMessage}
itemClassName='pb-3' itemClassName='pb-3'
> >
{accountIds.map((id: string) => {accountIds.map((id) =>
<AccountContainer key={id} id={id} />, <AccountContainer key={id} id={id} />,
)} )}
</ScrollableList> </ScrollableList>
); );
} }
return ( return (
<Modal <Modal
title={<FormattedMessage id='column.reblogs' defaultMessage='Reposts' />} title={<FormattedMessage id='column.reblogs' defaultMessage='Reposts' />}

View File

@ -27,12 +27,12 @@ const Timeline: React.FC<ITimeline> = ({
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const getStatusIds = useCallback(makeGetStatusIds, [])(); const getStatusIds = useCallback(makeGetStatusIds, [])();
const lastStatusId = useAppSelector(state => state.timelines.getIn([timelineId, 'items'], ImmutableOrderedSet()).last() as string | undefined); const lastStatusId = useAppSelector(state => (state.timelines.get(timelineId)?.items || ImmutableOrderedSet()).last() as string | undefined);
const statusIds = useAppSelector(state => getStatusIds(state, { type: timelineId })); const statusIds = useAppSelector(state => getStatusIds(state, { type: timelineId }));
const isLoading = useAppSelector(state => state.timelines.getIn([timelineId, 'isLoading'], true) === true); const isLoading = useAppSelector(state => (state.timelines.get(timelineId) || { isLoading: true }).isLoading === true);
const isPartial = useAppSelector(state => state.timelines.getIn([timelineId, 'isPartial'], false) === true); const isPartial = useAppSelector(state => (state.timelines.get(timelineId)?.isPartial || false) === true);
const hasMore = useAppSelector(state => state.timelines.getIn([timelineId, 'hasMore']) === true); const hasMore = useAppSelector(state => state.timelines.get(timelineId)?.hasMore === true);
const totalQueuedItemsCount = useAppSelector(state => state.timelines.getIn([timelineId, 'totalQueuedItemsCount'])); const totalQueuedItemsCount = useAppSelector(state => state.timelines.get(timelineId)?.totalQueuedItemsCount || 0);
const handleDequeueTimeline = () => { const handleDequeueTimeline = () => {
dispatch(dequeueTimeline(timelineId, onLoadMore)); dispatch(dequeueTimeline(timelineId, onLoadMore));

View File

@ -1,4 +1,4 @@
import { Map as ImmutableMap, List as ImmutableList } from 'immutable'; import { List as ImmutableList, Record as ImmutableRecord } from 'immutable';
import * as actions from 'soapbox/actions/conversations'; import * as actions from 'soapbox/actions/conversations';
@ -6,30 +6,30 @@ import reducer from '../conversations';
describe('conversations reducer', () => { describe('conversations reducer', () => {
it('should return the initial state', () => { it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(ImmutableMap({ expect(reducer(undefined, {} as any)).toMatchObject({
items: ImmutableList(), items: ImmutableList(),
isLoading: false, isLoading: false,
hasMore: true, hasMore: true,
mounted: false, mounted: 0,
})); });
}); });
it('should handle CONVERSATIONS_FETCH_REQUEST', () => { it('should handle CONVERSATIONS_FETCH_REQUEST', () => {
const state = ImmutableMap({ isLoading: false }); const state = ImmutableRecord({ isLoading: false })();
const action = { const action = {
type: actions.CONVERSATIONS_FETCH_REQUEST, type: actions.CONVERSATIONS_FETCH_REQUEST,
}; };
expect(reducer(state, action).toJS()).toMatchObject({ expect(reducer(state as any, action).toJS()).toMatchObject({
isLoading: true, isLoading: true,
}); });
}); });
it('should handle CONVERSATIONS_FETCH_FAIL', () => { it('should handle CONVERSATIONS_FETCH_FAIL', () => {
const state = ImmutableMap({ isLoading: true }); const state = ImmutableRecord({ isLoading: true })();
const action = { const action = {
type: actions.CONVERSATIONS_FETCH_FAIL, type: actions.CONVERSATIONS_FETCH_FAIL,
}; };
expect(reducer(state, action).toJS()).toMatchObject({ expect(reducer(state as any, action).toJS()).toMatchObject({
isLoading: false, isLoading: false,
}); });
}); });

View File

@ -1,21 +1,19 @@
import { Map as ImmutableMap } from 'immutable';
import reducer from '../push_notifications'; import reducer from '../push_notifications';
describe('push_notifications reducer', () => { describe('push_notifications reducer', () => {
it('should return the initial state', () => { it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(ImmutableMap({ expect(reducer(undefined, {} as any).toJS()).toEqual({
subscription: null, subscription: null,
alerts: ImmutableMap({ alerts: {
follow: true, follow: true,
follow_request: true, follow_request: true,
favourite: true, favourite: true,
reblog: true, reblog: true,
mention: true, mention: true,
poll: true, poll: true,
}), },
isSubscribed: false, isSubscribed: false,
browserSupport: false, browserSupport: false,
})); });
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet, fromJS } from 'immutable'; import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet, Record as ImmutableRecord, fromJS } from 'immutable';
import { import {
TIMELINE_EXPAND_REQUEST, TIMELINE_EXPAND_REQUEST,
@ -10,7 +10,7 @@ import reducer from '../timelines';
describe('timelines reducer', () => { describe('timelines reducer', () => {
it('should return the initial state', () => { it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(ImmutableMap()); expect(reducer(undefined, {} as any)).toEqual(ImmutableMap());
}); });
describe('TIMELINE_EXPAND_REQUEST', () => { describe('TIMELINE_EXPAND_REQUEST', () => {
@ -27,16 +27,16 @@ describe('timelines reducer', () => {
describe('TIMELINE_EXPAND_FAIL', () => { describe('TIMELINE_EXPAND_FAIL', () => {
it('sets loading to false', () => { it('sets loading to false', () => {
const state = ImmutableMap(fromJS({ const state = ImmutableMap({
home: { isLoading: true }, home: ImmutableRecord({ isLoading: true })(),
})); });
const action = { const action = {
type: TIMELINE_EXPAND_FAIL, type: TIMELINE_EXPAND_FAIL,
timeline: 'home', timeline: 'home',
}; };
const result = reducer(state, action); const result = reducer(state as any, action);
expect(result.getIn(['home', 'isLoading'])).toBe(false); expect(result.getIn(['home', 'isLoading'])).toBe(false);
}); });
}); });
@ -44,7 +44,7 @@ describe('timelines reducer', () => {
describe('TIMELINE_EXPAND_SUCCESS', () => { describe('TIMELINE_EXPAND_SUCCESS', () => {
it('sets loading to false', () => { it('sets loading to false', () => {
const state = ImmutableMap(fromJS({ const state = ImmutableMap(fromJS({
home: { isLoading: true }, home: ImmutableRecord({ isLoading: true })(),
})); }));
const action = { const action = {
@ -52,7 +52,7 @@ describe('timelines reducer', () => {
timeline: 'home', timeline: 'home',
}; };
const result = reducer(state, action); const result = reducer(state as any, action);
expect(result.getIn(['home', 'isLoading'])).toBe(false); expect(result.getIn(['home', 'isLoading'])).toBe(false);
}); });
@ -71,7 +71,7 @@ describe('timelines reducer', () => {
it('merges new status IDs', () => { it('merges new status IDs', () => {
const state = ImmutableMap(fromJS({ const state = ImmutableMap(fromJS({
home: { items: ImmutableOrderedSet(['5', '2', '1']) }, home: ImmutableRecord({ items: ImmutableOrderedSet(['5', '2', '1']) })(),
})); }));
const expected = ImmutableOrderedSet(['6', '5', '4', '2', '1']); const expected = ImmutableOrderedSet(['6', '5', '4', '2', '1']);
@ -82,13 +82,13 @@ describe('timelines reducer', () => {
statuses: [{ id: '6' }, { id: '5' }, { id: '4' }], statuses: [{ id: '6' }, { id: '5' }, { id: '4' }],
}; };
const result = reducer(state, action); const result = reducer(state as any, action);
expect(result.getIn(['home', 'items'])).toEqual(expected); expect(result.getIn(['home', 'items'])).toEqual(expected);
}); });
it('merges old status IDs', () => { it('merges old status IDs', () => {
const state = ImmutableMap(fromJS({ const state = ImmutableMap(fromJS({
home: { items: ImmutableOrderedSet(['6', '4', '3']) }, home: ImmutableRecord({ items: ImmutableOrderedSet(['6', '4', '3']) })(),
})); }));
const expected = ImmutableOrderedSet(['6', '4', '3', '5', '2', '1']); const expected = ImmutableOrderedSet(['6', '4', '3', '5', '2', '1']);
@ -99,13 +99,13 @@ describe('timelines reducer', () => {
statuses: [{ id: '5' }, { id: '2' }, { id: '1' }], statuses: [{ id: '5' }, { id: '2' }, { id: '1' }],
}; };
const result = reducer(state, action); const result = reducer(state as any, action);
expect(result.getIn(['home', 'items'])).toEqual(expected); expect(result.getIn(['home', 'items'])).toEqual(expected);
}); });
it('overrides pinned post IDs', () => { it('overrides pinned post IDs', () => {
const state = ImmutableMap(fromJS({ const state = ImmutableMap(fromJS({
'account:1:pinned': { items: ImmutableOrderedSet(['5', '2', '1']) }, 'account:1:pinned': ImmutableRecord({ items: ImmutableOrderedSet(['5', '2', '1']) })(),
})); }));
const expected = ImmutableOrderedSet(['9', '8', '7']); const expected = ImmutableOrderedSet(['9', '8', '7']);
@ -116,7 +116,7 @@ describe('timelines reducer', () => {
statuses: [{ id: '9' }, { id: '8' }, { id: '7' }], statuses: [{ id: '9' }, { id: '8' }, { id: '7' }],
}; };
const result = reducer(state, action); const result = reducer(state as any, action);
expect(result.getIn(['home', 'items'])).toEqual(expected); expect(result.getIn(['home', 'items'])).toEqual(expected);
}); });
}); });

View File

@ -1,23 +1,24 @@
import { Map as ImmutableMap } from 'immutable'; import { OrderedSet as ImmutableOrderedSet } from 'immutable';
import reducer from '../user_lists'; import reducer from '../user_lists';
describe('user_lists reducer', () => { describe('user_lists reducer', () => {
it('should return the initial state', () => { it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(ImmutableMap({ expect(reducer(undefined, {} as any)).toMatchObject({
followers: ImmutableMap(), followers: {},
following: ImmutableMap(), following: {},
reblogged_by: ImmutableMap(), reblogged_by: {},
favourited_by: ImmutableMap(), favourited_by: {},
follow_requests: ImmutableMap(), reactions: {},
blocks: ImmutableMap(), follow_requests: { next: null, items: ImmutableOrderedSet(), isLoading: false },
reactions: ImmutableMap(), blocks: { next: null, items: ImmutableOrderedSet(), isLoading: false },
mutes: ImmutableMap(), mutes: { next: null, items: ImmutableOrderedSet(), isLoading: false },
groups: ImmutableMap(), directory: { next: null, items: ImmutableOrderedSet(), isLoading: true },
groups_removed_accounts: ImmutableMap(), groups: {},
pinned: ImmutableMap(), groups_removed_accounts: {},
birthday_reminders: ImmutableMap(), pinned: {},
familiar_followers: ImmutableMap(), birthday_reminders: {},
})); familiar_followers: {},
});
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Map as ImmutableMap, List as ImmutableList } from 'immutable'; import { List as ImmutableList, Record as ImmutableRecord } from 'immutable';
import { import {
CONVERSATIONS_MOUNT, CONVERSATIONS_MOUNT,
@ -11,21 +11,35 @@ import {
} from '../actions/conversations'; } from '../actions/conversations';
import compareId from '../compare_id'; import compareId from '../compare_id';
const initialState = ImmutableMap({ import type { AnyAction } from 'redux';
items: ImmutableList(), import type { APIEntity } from 'soapbox/types/entities';
isLoading: false,
hasMore: true, const ConversationRecord = ImmutableRecord({
mounted: false, id: '',
unread: false,
accounts: ImmutableList<string>(),
last_status: null as string | null,
}); });
const conversationToMap = item => ImmutableMap({ const ReducerRecord = ImmutableRecord({
items: ImmutableList<Conversation>(),
isLoading: false,
hasMore: true,
mounted: 0,
});
type State = ReturnType<typeof ReducerRecord>;
type Conversation = ReturnType<typeof ConversationRecord>;
const conversationToMap = (item: APIEntity) => ConversationRecord({
id: item.id, id: item.id,
unread: item.unread, unread: item.unread,
accounts: ImmutableList(item.accounts.map(a => a.id)), accounts: ImmutableList(item.accounts.map((a: APIEntity) => a.id)),
last_status: item.last_status ? item.last_status.id : null, last_status: item.last_status ? item.last_status.id : null,
}); });
const updateConversation = (state, item) => state.update('items', list => { const updateConversation = (state: State, item: APIEntity) => state.update('items', list => {
const index = list.findIndex(x => x.get('id') === item.id); const index = list.findIndex(x => x.get('id') === item.id);
const newItem = conversationToMap(item); const newItem = conversationToMap(item);
@ -36,7 +50,7 @@ const updateConversation = (state, item) => state.update('items', list => {
} }
}); });
const expandNormalizedConversations = (state, conversations, next, isLoadingRecent) => { const expandNormalizedConversations = (state: State, conversations: APIEntity[], next: string | null, isLoadingRecent?: boolean) => {
let items = ImmutableList(conversations.map(conversationToMap)); let items = ImmutableList(conversations.map(conversationToMap));
return state.withMutations(mutable => { return state.withMutations(mutable => {
@ -52,7 +66,7 @@ const expandNormalizedConversations = (state, conversations, next, isLoadingRece
const newItem = items.get(newItemIndex); const newItem = items.get(newItemIndex);
items = items.delete(newItemIndex); items = items.delete(newItemIndex);
return newItem; return newItem!;
}); });
list = list.concat(items); list = list.concat(items);
@ -75,7 +89,7 @@ const expandNormalizedConversations = (state, conversations, next, isLoadingRece
}); });
}; };
export default function conversations(state = initialState, action) { export default function conversations(state = ReducerRecord(), action: AnyAction) {
switch (action.type) { switch (action.type) {
case CONVERSATIONS_FETCH_REQUEST: case CONVERSATIONS_FETCH_REQUEST:
return state.set('isLoading', true); return state.set('isLoading', true);

View File

@ -1,11 +1,11 @@
import { List as ImmutableList, Map as ImmutableMap, Record as ImmutableRecord, fromJS } from 'immutable'; import { List as ImmutableList, Map as ImmutableMap, Record as ImmutableRecord, fromJS } from 'immutable';
import { AnyAction } from 'redux';
import { import {
STATUS_CREATE_REQUEST, STATUS_CREATE_REQUEST,
STATUS_CREATE_SUCCESS, STATUS_CREATE_SUCCESS,
} from 'soapbox/actions/statuses'; } from 'soapbox/actions/statuses';
import type { AnyAction } from 'redux';
import type { StatusVisibility } from 'soapbox/normalizers/status'; import type { StatusVisibility } from 'soapbox/normalizers/status';
const PendingStatusRecord = ImmutableRecord({ const PendingStatusRecord = ImmutableRecord({

View File

@ -1,10 +1,17 @@
import { Map as ImmutableMap } from 'immutable'; import { Map as ImmutableMap, Record as ImmutableRecord } from 'immutable';
import { SET_BROWSER_SUPPORT, SET_SUBSCRIPTION, CLEAR_SUBSCRIPTION, SET_ALERTS } from '../actions/push_notifications'; import { SET_BROWSER_SUPPORT, SET_SUBSCRIPTION, CLEAR_SUBSCRIPTION, SET_ALERTS } from '../actions/push_notifications';
const initialState = ImmutableMap({ import type { AnyAction } from 'redux';
subscription: null,
alerts: new ImmutableMap({ const SubscriptionRecord = ImmutableRecord({
id: '',
endpoint: '',
});
const ReducerRecord = ImmutableRecord({
subscription: null as Subscription | null,
alerts: ImmutableMap<string, boolean>({
follow: true, follow: true,
follow_request: true, follow_request: true,
favourite: true, favourite: true,
@ -16,20 +23,22 @@ const initialState = ImmutableMap({
browserSupport: false, browserSupport: false,
}); });
export default function push_subscriptions(state = initialState, action) { type Subscription = ReturnType<typeof SubscriptionRecord>;
export default function push_subscriptions(state = ReducerRecord(), action: AnyAction) {
switch (action.type) { switch (action.type) {
case SET_SUBSCRIPTION: case SET_SUBSCRIPTION:
return state return state
.set('subscription', new ImmutableMap({ .set('subscription', SubscriptionRecord({
id: action.subscription.id, id: action.subscription.id,
endpoint: action.subscription.endpoint, endpoint: action.subscription.endpoint,
})) }))
.set('alerts', new ImmutableMap(action.subscription.alerts)) .set('alerts', ImmutableMap(action.subscription.alerts))
.set('isSubscribed', true); .set('isSubscribed', true);
case SET_BROWSER_SUPPORT: case SET_BROWSER_SUPPORT:
return state.set('browserSupport', action.value); return state.set('browserSupport', action.value);
case CLEAR_SUBSCRIPTION: case CLEAR_SUBSCRIPTION:
return initialState; return ReducerRecord();
case SET_ALERTS: case SET_ALERTS:
return state.setIn(action.path, action.value); return state.setIn(action.path, action.value);
default: default:

View File

@ -1,38 +0,0 @@
import { Map as ImmutableMap, fromJS } from 'immutable';
import {
SCHEDULED_STATUSES_FETCH_SUCCESS,
SCHEDULED_STATUS_CANCEL_REQUEST,
SCHEDULED_STATUS_CANCEL_SUCCESS,
} from 'soapbox/actions/scheduled_statuses';
import { STATUS_CREATE_SUCCESS } from 'soapbox/actions/statuses';
import { STATUS_IMPORT, STATUSES_IMPORT } from '../actions/importer';
const importStatus = (state, status) => {
if (!status.scheduled_at) return state;
return state.set(status.id, fromJS(status));
};
const importStatuses = (state, statuses) =>
state.withMutations(mutable => statuses.forEach(status => importStatus(mutable, status)));
const deleteStatus = (state, id) => state.delete(id);
const initialState = ImmutableMap();
export default function scheduled_statuses(state = initialState, action) {
switch (action.type) {
case STATUS_IMPORT:
case STATUS_CREATE_SUCCESS:
return importStatus(state, action.status);
case STATUSES_IMPORT:
case SCHEDULED_STATUSES_FETCH_SUCCESS:
return importStatuses(state, action.statuses);
case SCHEDULED_STATUS_CANCEL_REQUEST:
case SCHEDULED_STATUS_CANCEL_SUCCESS:
return deleteStatus(state, action.id);
default:
return state;
}
}

View File

@ -0,0 +1,57 @@
import { List as ImmutableList, Map as ImmutableMap, Record as ImmutableRecord, fromJS } from 'immutable';
import { STATUS_IMPORT, STATUSES_IMPORT } from 'soapbox/actions/importer';
import {
SCHEDULED_STATUSES_FETCH_SUCCESS,
SCHEDULED_STATUS_CANCEL_REQUEST,
SCHEDULED_STATUS_CANCEL_SUCCESS,
} from 'soapbox/actions/scheduled_statuses';
import { STATUS_CREATE_SUCCESS } from 'soapbox/actions/statuses';
import type { AnyAction } from 'redux';
import type { StatusVisibility } from 'soapbox/normalizers/status';
import type { APIEntity } from 'soapbox/types/entities';
const ScheduledStatusRecord = ImmutableRecord({
id: '',
scheduled_at: new Date(),
media_attachments: null as ImmutableList<ImmutableMap<string, any>> | null,
text: '',
in_reply_to_id: null as string | null,
media_ids: null as ImmutableList<string> | null,
sensitive: false,
spoiler_text: '',
visibility: 'public' as StatusVisibility,
poll: null as ImmutableMap<string, any> | null,
});
export type ScheduledStatus = ReturnType<typeof ScheduledStatusRecord>;
type State = ImmutableMap<string, ScheduledStatus>;
const initialState: State = ImmutableMap();
const importStatus = (state: State, { params, ...status }: APIEntity) => {
if (!status.scheduled_at) return state;
return state.set(status.id, ScheduledStatusRecord(ImmutableMap(fromJS({ ...status, ...params }))));
};
const importStatuses = (state: State, statuses: APIEntity[]) =>
state.withMutations(mutable => statuses.forEach(status => importStatus(mutable, status)));
const deleteStatus = (state: State, id: string) => state.delete(id);
export default function scheduled_statuses(state: State = initialState, action: AnyAction) {
switch (action.type) {
case STATUS_IMPORT:
case STATUS_CREATE_SUCCESS:
return importStatus(state, action.status);
case STATUSES_IMPORT:
case SCHEDULED_STATUSES_FETCH_SUCCESS:
return importStatuses(state, action.statuses);
case SCHEDULED_STATUS_CANCEL_REQUEST:
case SCHEDULED_STATUS_CANCEL_SUCCESS:
return deleteStatus(state, action.id);
default:
return state;
}
}

View File

@ -1,4 +1,5 @@
import { Map as ImmutableMap, fromJS } from 'immutable'; import { Map as ImmutableMap, fromJS } from 'immutable';
import { AnyAction } from 'redux';
import { ME_FETCH_SUCCESS } from 'soapbox/actions/me'; import { ME_FETCH_SUCCESS } from 'soapbox/actions/me';
@ -12,23 +13,24 @@ import {
FE_NAME, FE_NAME,
} from '../actions/settings'; } from '../actions/settings';
import type { Emoji } from 'soapbox/components/autosuggest_emoji';
import type { APIEntity } from 'soapbox/types/entities';
type State = ImmutableMap<string, any>;
const updateFrequentEmojis = (state: State, emoji: Emoji) => state.update('frequentlyUsedEmojis', ImmutableMap(), map => map.update(emoji.id, 0, (count: number) => count + 1)).set('saved', false);
const importSettings = (state: State, account: APIEntity) => {
account = fromJS(account);
const prefs = account.getIn(['pleroma', 'settings_store', FE_NAME], ImmutableMap());
return state.merge(prefs) as State;
};
// Default settings are in action/settings.js // Default settings are in action/settings.js
// //
// Settings should be accessed with `getSettings(getState()).getIn(...)` // Settings should be accessed with `getSettings(getState()).getIn(...)`
// instead of directly from the state. // instead of directly from the state.
const initialState = ImmutableMap({ export default function settings(state: State = ImmutableMap<string, any>({ saved: true }), action: AnyAction): State {
saved: true,
});
const updateFrequentEmojis = (state, emoji) => state.update('frequentlyUsedEmojis', ImmutableMap(), map => map.update(emoji.id, 0, count => count + 1)).set('saved', false);
const importSettings = (state, account) => {
account = fromJS(account);
const prefs = account.getIn(['pleroma', 'settings_store', FE_NAME], ImmutableMap());
return state.merge(prefs);
};
export default function settings(state = initialState, action) {
switch (action.type) { switch (action.type) {
case ME_FETCH_SUCCESS: case ME_FETCH_SUCCESS:
return importSettings(state, action.me); return importSettings(state, action.me);
@ -43,7 +45,7 @@ export default function settings(state = initialState, action) {
case SETTING_SAVE: case SETTING_SAVE:
return state.set('saved', true); return state.set('saved', true);
case SETTINGS_UPDATE: case SETTINGS_UPDATE:
return fromJS(action.settings); return ImmutableMap<string, any>(fromJS(action.settings));
default: default:
return state; return state;
} }

View File

@ -2,6 +2,7 @@ import {
Map as ImmutableMap, Map as ImmutableMap,
List as ImmutableList, List as ImmutableList,
OrderedSet as ImmutableOrderedSet, OrderedSet as ImmutableOrderedSet,
Record as ImmutableRecord,
fromJS, fromJS,
} from 'immutable'; } from 'immutable';
@ -30,54 +31,63 @@ import {
TIMELINE_SCROLL_TOP, TIMELINE_SCROLL_TOP,
} from '../actions/timelines'; } from '../actions/timelines';
import type { AnyAction } from 'redux';
import type { StatusVisibility } from 'soapbox/normalizers/status';
import type { APIEntity, Status } from 'soapbox/types/entities';
const TRUNCATE_LIMIT = 40; const TRUNCATE_LIMIT = 40;
const TRUNCATE_SIZE = 20; const TRUNCATE_SIZE = 20;
const initialState = ImmutableMap(); const TimelineRecord = ImmutableRecord({
const initialTimeline = ImmutableMap({
unread: 0, unread: 0,
online: false, online: false,
top: true, top: true,
isLoading: false, isLoading: false,
hasMore: true, hasMore: true,
items: ImmutableOrderedSet(), items: ImmutableOrderedSet<string>(),
queuedItems: ImmutableOrderedSet(), //max= MAX_QUEUED_ITEMS queuedItems: ImmutableOrderedSet<string>(), //max= MAX_QUEUED_ITEMS
totalQueuedItemsCount: 0, //used for queuedItems overflow for MAX_QUEUED_ITEMS+ totalQueuedItemsCount: 0, //used for queuedItems overflow for MAX_QUEUED_ITEMS+
loadingFailed: false,
isPartial: false,
}); });
const getStatusIds = (statuses = ImmutableList()) => ( const initialState = ImmutableMap<string, Timeline>();
type State = ImmutableMap<string, Timeline>;
type Timeline = ReturnType<typeof TimelineRecord>;
const getStatusIds = (statuses: ImmutableList<ImmutableMap<string, any>> = ImmutableList()) => (
statuses.map(status => status.get('id')).toOrderedSet() statuses.map(status => status.get('id')).toOrderedSet()
); );
const mergeStatusIds = (oldIds = ImmutableOrderedSet(), newIds = ImmutableOrderedSet()) => ( const mergeStatusIds = (oldIds = ImmutableOrderedSet<string>(), newIds = ImmutableOrderedSet<string>()) => (
newIds.union(oldIds) newIds.union(oldIds)
); );
const addStatusId = (oldIds = ImmutableOrderedSet(), newId) => ( const addStatusId = (oldIds = ImmutableOrderedSet<string>(), newId: string) => (
mergeStatusIds(oldIds, ImmutableOrderedSet([newId])) mergeStatusIds(oldIds, ImmutableOrderedSet([newId]))
); );
// Like `take`, but only if the collection's size exceeds truncateLimit // Like `take`, but only if the collection's size exceeds truncateLimit
const truncate = (items, truncateLimit, newSize) => ( const truncate = (items: ImmutableOrderedSet<string>, truncateLimit: number, newSize: number) => (
items.size > truncateLimit ? items.take(newSize) : items items.size > truncateLimit ? items.take(newSize) : items
); );
const truncateIds = items => truncate(items, TRUNCATE_LIMIT, TRUNCATE_SIZE); const truncateIds = (items: ImmutableOrderedSet<string>) => truncate(items, TRUNCATE_LIMIT, TRUNCATE_SIZE);
const setLoading = (state, timelineId, loading) => { const setLoading = (state: State, timelineId: string, loading: boolean) => {
return state.update(timelineId, initialTimeline, timeline => timeline.set('isLoading', loading)); return state.update(timelineId, TimelineRecord(), timeline => timeline.set('isLoading', loading));
}; };
// Keep track of when a timeline failed to load // Keep track of when a timeline failed to load
const setFailed = (state, timelineId, failed) => { const setFailed = (state: State, timelineId: string, failed: boolean) => {
return state.update(timelineId, initialTimeline, timeline => timeline.set('loadingFailed', failed)); return state.update(timelineId, TimelineRecord(), timeline => timeline.set('loadingFailed', failed));
}; };
const expandNormalizedTimeline = (state, timelineId, statuses, next, isPartial, isLoadingRecent) => { const expandNormalizedTimeline = (state: State, timelineId: string, statuses: ImmutableList<ImmutableMap<string, any>>, next: string | null, isPartial: boolean, isLoadingRecent: boolean) => {
const newIds = getStatusIds(statuses); const newIds = getStatusIds(statuses);
return state.update(timelineId, initialTimeline, timeline => timeline.withMutations(timeline => { return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => {
timeline.set('isLoading', false); timeline.set('isLoading', false);
timeline.set('loadingFailed', false); timeline.set('loadingFailed', false);
timeline.set('isPartial', isPartial); timeline.set('isPartial', isPartial);
@ -91,8 +101,8 @@ const expandNormalizedTimeline = (state, timelineId, statuses, next, isPartial,
} }
if (!newIds.isEmpty()) { if (!newIds.isEmpty()) {
timeline.update('items', ImmutableOrderedSet(), oldIds => { timeline.update('items', oldIds => {
if (newIds.first() > oldIds.first()) { if (newIds.first() > oldIds.first()!) {
return mergeStatusIds(oldIds, newIds); return mergeStatusIds(oldIds, newIds);
} else { } else {
return mergeStatusIds(newIds, oldIds); return mergeStatusIds(newIds, oldIds);
@ -102,16 +112,16 @@ const expandNormalizedTimeline = (state, timelineId, statuses, next, isPartial,
})); }));
}; };
const updateTimeline = (state, timelineId, statusId) => { const updateTimeline = (state: State, timelineId: string, statusId: string) => {
const top = state.getIn([timelineId, 'top']); const top = state.get(timelineId)?.top;
const oldIds = state.getIn([timelineId, 'items'], ImmutableOrderedSet()); const oldIds = state.get(timelineId)?.items || ImmutableOrderedSet<string>();
const unread = state.getIn([timelineId, 'unread'], 0); const unread = state.get(timelineId)?.unread || 0;
if (oldIds.includes(statusId)) return state; if (oldIds.includes(statusId)) return state;
const newIds = addStatusId(oldIds, statusId); const newIds = addStatusId(oldIds, statusId);
return state.update(timelineId, initialTimeline, timeline => timeline.withMutations(timeline => { return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => {
if (top) { if (top) {
// For performance, truncate items if user is scrolled to the top // For performance, truncate items if user is scrolled to the top
timeline.set('items', truncateIds(newIds)); timeline.set('items', truncateIds(newIds));
@ -122,33 +132,33 @@ const updateTimeline = (state, timelineId, statusId) => {
})); }));
}; };
const updateTimelineQueue = (state, timelineId, statusId) => { const updateTimelineQueue = (state: State, timelineId: string, statusId: string) => {
const queuedIds = state.getIn([timelineId, 'queuedItems'], ImmutableOrderedSet()); const queuedIds = state.get(timelineId)?.queuedItems || ImmutableOrderedSet<string>();
const listedIds = state.getIn([timelineId, 'items'], ImmutableOrderedSet()); const listedIds = state.get(timelineId)?.items || ImmutableOrderedSet<string>();
const queuedCount = state.getIn([timelineId, 'totalQueuedItemsCount'], 0); const queuedCount = state.get(timelineId)?.totalQueuedItemsCount || 0;
if (queuedIds.includes(statusId)) return state; if (queuedIds.includes(statusId)) return state;
if (listedIds.includes(statusId)) return state; if (listedIds.includes(statusId)) return state;
return state.update(timelineId, initialTimeline, timeline => timeline.withMutations(timeline => { return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => {
timeline.set('totalQueuedItemsCount', queuedCount + 1); timeline.set('totalQueuedItemsCount', queuedCount + 1);
timeline.set('queuedItems', addStatusId(queuedIds, statusId).take(MAX_QUEUED_ITEMS)); timeline.set('queuedItems', addStatusId(queuedIds, statusId).take(MAX_QUEUED_ITEMS));
})); }));
}; };
const shouldDelete = (timelineId, excludeAccount) => { const shouldDelete = (timelineId: string, excludeAccount?: string) => {
if (!excludeAccount) return true; if (!excludeAccount) return true;
if (timelineId === `account:${excludeAccount}`) return false; if (timelineId === `account:${excludeAccount}`) return false;
if (timelineId.startsWith(`account:${excludeAccount}:`)) return false; if (timelineId.startsWith(`account:${excludeAccount}:`)) return false;
return true; return true;
}; };
const deleteStatus = (state, statusId, accountId, references, excludeAccount = null) => { const deleteStatus = (state: State, statusId: string, accountId: string, references: ImmutableMap<string, [string, string]> | Array<[string, string]>, excludeAccount?: string) => {
return state.withMutations(state => { return state.withMutations(state => {
state.keySeq().forEach(timelineId => { state.keySeq().forEach(timelineId => {
if (shouldDelete(timelineId, excludeAccount)) { if (shouldDelete(timelineId, excludeAccount)) {
state.updateIn([timelineId, 'items'], ids => ids.delete(statusId)); state.updateIn([timelineId, 'items'], ids => (ids as ImmutableOrderedSet<string>).delete(statusId));
state.updateIn([timelineId, 'queuedItems'], ids => ids.delete(statusId)); state.updateIn([timelineId, 'queuedItems'], ids => (ids as ImmutableOrderedSet<string>).delete(statusId));
} }
}); });
@ -159,51 +169,51 @@ const deleteStatus = (state, statusId, accountId, references, excludeAccount = n
}); });
}; };
const clearTimeline = (state, timelineId) => { const clearTimeline = (state: State, timelineId: string) => {
return state.set(timelineId, initialTimeline); return state.set(timelineId, TimelineRecord());
}; };
const updateTop = (state, timelineId, top) => { const updateTop = (state: State, timelineId: string, top: boolean) => {
return state.update(timelineId, initialTimeline, timeline => timeline.withMutations(timeline => { return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => {
if (top) timeline.set('unread', 0); if (top) timeline.set('unread', 0);
timeline.set('top', top); timeline.set('top', top);
})); }));
}; };
const isReblogOf = (reblog, status) => reblog.get('reblog') === status.get('id'); const isReblogOf = (reblog: Status, status: Status) => reblog.reblog === status.id;
const statusToReference = status => [status.get('id'), status.get('account')]; const statusToReference = (status: Status) => [status.id, status.account];
const buildReferencesTo = (statuses, status) => ( const buildReferencesTo = (statuses: ImmutableMap<string, Status>, status: Status) => (
statuses statuses
.filter(reblog => isReblogOf(reblog, status)) .filter(reblog => isReblogOf(reblog, status))
.map(statusToReference) .map(statusToReference) as ImmutableMap<string, [string, string]>
); );
const filterTimeline = (state, timelineId, relationship, statuses) => const filterTimeline = (state: State, timelineId: string, relationship: APIEntity, statuses: ImmutableList<ImmutableMap<string, any>>) =>
state.updateIn([timelineId, 'items'], ImmutableOrderedSet(), ids => state.updateIn([timelineId, 'items'], ImmutableOrderedSet(), (ids) =>
ids.filterNot(statusId => (ids as ImmutableOrderedSet<string>).filterNot(statusId =>
statuses.getIn([statusId, 'account']) === relationship.id, statuses.getIn([statusId, 'account']) === relationship.id,
)); ));
const filterTimelines = (state, relationship, statuses) => { const filterTimelines = (state: State, relationship: APIEntity, statuses: ImmutableMap<string, Status>) => {
return state.withMutations(state => { return state.withMutations(state => {
statuses.forEach(status => { statuses.forEach(status => {
if (status.get('account') !== relationship.id) return; if (status.get('account') !== relationship.id) return;
const references = buildReferencesTo(statuses, status); const references = buildReferencesTo(statuses, status);
deleteStatus(state, status.get('id'), status.get('account'), references, relationship.id); deleteStatus(state, status.get('id'), status.get('account') as string, references, relationship.id);
}); });
}); });
}; };
const removeStatusFromGroup = (state, groupId, statusId) => { const removeStatusFromGroup = (state: State, groupId: string, statusId: string) => {
return state.updateIn([`group:${groupId}`, 'items'], ImmutableOrderedSet(), ids => ids.delete(statusId)); return state.updateIn([`group:${groupId}`, 'items'], ImmutableOrderedSet(), ids => (ids as ImmutableOrderedSet<string>).delete(statusId));
}; };
const timelineDequeue = (state, timelineId) => { const timelineDequeue = (state: State, timelineId: string) => {
const top = state.getIn([timelineId, 'top']); const top = state.getIn([timelineId, 'top']);
return state.update(timelineId, initialTimeline, timeline => timeline.withMutations(timeline => { return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations((timeline: Timeline) => {
const queuedIds = timeline.get('queuedItems'); const queuedIds = timeline.queuedItems;
timeline.update('items', ids => { timeline.update('items', ids => {
const newIds = mergeStatusIds(ids, queuedIds); const newIds = mergeStatusIds(ids, queuedIds);
@ -215,12 +225,12 @@ const timelineDequeue = (state, timelineId) => {
})); }));
}; };
const timelineConnect = (state, timelineId) => { const timelineConnect = (state: State, timelineId: string) => {
return state.update(timelineId, initialTimeline, timeline => timeline.set('online', true)); return state.update(timelineId, TimelineRecord(), timeline => timeline.set('online', true));
}; };
const timelineDisconnect = (state, timelineId) => { const timelineDisconnect = (state: State, timelineId: string) => {
return state.update(timelineId, initialTimeline, timeline => timeline.withMutations(timeline => { return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => {
timeline.set('online', false); timeline.set('online', false);
const items = timeline.get('items', ImmutableOrderedSet()); const items = timeline.get('items', ImmutableOrderedSet());
@ -232,7 +242,7 @@ const timelineDisconnect = (state, timelineId) => {
})); }));
}; };
const getTimelinesByVisibility = visibility => { const getTimelinesByVisibility = (visibility: StatusVisibility) => {
switch (visibility) { switch (visibility) {
case 'direct': case 'direct':
return ['direct']; return ['direct'];
@ -244,7 +254,7 @@ const getTimelinesByVisibility = visibility => {
}; };
// Given an OrderedSet of IDs, replace oldId with newId maintaining its position // Given an OrderedSet of IDs, replace oldId with newId maintaining its position
const replaceId = (ids, oldId, newId) => { const replaceId = (ids: ImmutableOrderedSet<string>, oldId: string, newId: string) => {
const list = ImmutableList(ids); const list = ImmutableList(ids);
const index = list.indexOf(oldId); const index = list.indexOf(oldId);
@ -255,7 +265,7 @@ const replaceId = (ids, oldId, newId) => {
} }
}; };
const importPendingStatus = (state, params, idempotencyKey) => { const importPendingStatus = (state: State, params: APIEntity, idempotencyKey: string) => {
const statusId = `末pending-${idempotencyKey}`; const statusId = `末pending-${idempotencyKey}`;
return state.withMutations(state => { return state.withMutations(state => {
@ -267,19 +277,19 @@ const importPendingStatus = (state, params, idempotencyKey) => {
}); });
}; };
const replacePendingStatus = (state, idempotencyKey, newId) => { const replacePendingStatus = (state: State, idempotencyKey: string, newId: string) => {
const oldId = `末pending-${idempotencyKey}`; const oldId = `末pending-${idempotencyKey}`;
// Loop through timelines and replace the pending status with the real one // Loop through timelines and replace the pending status with the real one
return state.withMutations(state => { return state.withMutations(state => {
state.keySeq().forEach(timelineId => { state.keySeq().forEach(timelineId => {
state.updateIn([timelineId, 'items'], ids => replaceId(ids, oldId, newId)); state.updateIn([timelineId, 'items'], ids => replaceId((ids as ImmutableOrderedSet<string>), oldId, newId));
state.updateIn([timelineId, 'queuedItems'], ids => replaceId(ids, oldId, newId)); state.updateIn([timelineId, 'queuedItems'], ids => replaceId((ids as ImmutableOrderedSet<string>), oldId, newId));
}); });
}); });
}; };
const importStatus = (state, status, idempotencyKey) => { const importStatus = (state: State, status: APIEntity, idempotencyKey: string) => {
return state.withMutations(state => { return state.withMutations(state => {
replacePendingStatus(state, idempotencyKey, status.id); replacePendingStatus(state, idempotencyKey, status.id);
@ -291,14 +301,14 @@ const importStatus = (state, status, idempotencyKey) => {
}); });
}; };
const handleExpandFail = (state, timelineId) => { const handleExpandFail = (state: State, timelineId: string) => {
return state.withMutations(state => { return state.withMutations(state => {
setLoading(state, timelineId, false); setLoading(state, timelineId, false);
setFailed(state, timelineId, true); setFailed(state, timelineId, true);
}); });
}; };
export default function timelines(state = initialState, action) { export default function timelines(state: State = initialState, action: AnyAction) {
switch (action.type) { switch (action.type) {
case STATUS_CREATE_REQUEST: case STATUS_CREATE_REQUEST:
if (action.params.scheduled_at) return state; if (action.params.scheduled_at) return state;
@ -311,7 +321,7 @@ export default function timelines(state = initialState, action) {
case TIMELINE_EXPAND_FAIL: case TIMELINE_EXPAND_FAIL:
return handleExpandFail(state, action.timeline); return handleExpandFail(state, action.timeline);
case TIMELINE_EXPAND_SUCCESS: case TIMELINE_EXPAND_SUCCESS:
return expandNormalizedTimeline(state, action.timeline, fromJS(action.statuses), action.next, action.partial, action.isLoadingRecent); return expandNormalizedTimeline(state, action.timeline, fromJS(action.statuses) as ImmutableList<ImmutableMap<string, any>>, action.next, action.partial, action.isLoadingRecent);
case TIMELINE_UPDATE: case TIMELINE_UPDATE:
return updateTimeline(state, action.timeline, action.statusId); return updateTimeline(state, action.timeline, action.statusId);
case TIMELINE_UPDATE_QUEUE: case TIMELINE_UPDATE_QUEUE:

View File

@ -1,150 +0,0 @@
import {
Map as ImmutableMap,
OrderedSet as ImmutableOrderedSet,
} from 'immutable';
import {
FOLLOWERS_FETCH_SUCCESS,
FOLLOWERS_EXPAND_SUCCESS,
FOLLOWING_FETCH_SUCCESS,
FOLLOWING_EXPAND_SUCCESS,
FOLLOW_REQUESTS_FETCH_SUCCESS,
FOLLOW_REQUESTS_EXPAND_SUCCESS,
FOLLOW_REQUEST_AUTHORIZE_SUCCESS,
FOLLOW_REQUEST_REJECT_SUCCESS,
PINNED_ACCOUNTS_FETCH_SUCCESS,
BIRTHDAY_REMINDERS_FETCH_SUCCESS,
} from '../actions/accounts';
import {
BLOCKS_FETCH_SUCCESS,
BLOCKS_EXPAND_SUCCESS,
} from '../actions/blocks';
import {
DIRECTORY_FETCH_REQUEST,
DIRECTORY_FETCH_SUCCESS,
DIRECTORY_FETCH_FAIL,
DIRECTORY_EXPAND_REQUEST,
DIRECTORY_EXPAND_SUCCESS,
DIRECTORY_EXPAND_FAIL,
} from '../actions/directory';
import {
FAMILIAR_FOLLOWERS_FETCH_SUCCESS,
} from '../actions/familiar_followers';
import {
GROUP_MEMBERS_FETCH_SUCCESS,
GROUP_MEMBERS_EXPAND_SUCCESS,
GROUP_REMOVED_ACCOUNTS_FETCH_SUCCESS,
GROUP_REMOVED_ACCOUNTS_EXPAND_SUCCESS,
GROUP_REMOVED_ACCOUNTS_REMOVE_SUCCESS,
} from '../actions/groups';
import {
REBLOGS_FETCH_SUCCESS,
FAVOURITES_FETCH_SUCCESS,
REACTIONS_FETCH_SUCCESS,
} from '../actions/interactions';
import {
MUTES_FETCH_SUCCESS,
MUTES_EXPAND_SUCCESS,
} from '../actions/mutes';
import {
NOTIFICATIONS_UPDATE,
} from '../actions/notifications';
const initialState = ImmutableMap({
followers: ImmutableMap(),
following: ImmutableMap(),
reblogged_by: ImmutableMap(),
favourited_by: ImmutableMap(),
reactions: ImmutableMap(),
follow_requests: ImmutableMap(),
blocks: ImmutableMap(),
mutes: ImmutableMap(),
groups: ImmutableMap(),
groups_removed_accounts: ImmutableMap(),
pinned: ImmutableMap(),
birthday_reminders: ImmutableMap(),
familiar_followers: ImmutableMap(),
});
const normalizeList = (state, type, id, accounts, next) => {
return state.setIn([type, id], ImmutableMap({
next,
items: ImmutableOrderedSet(accounts.map(item => item.id)),
}));
};
const appendToList = (state, type, id, accounts, next) => {
return state.updateIn([type, id], map => {
return map.set('next', next).update('items', ImmutableOrderedSet(), list => list.concat(accounts.map(item => item.id)));
});
};
const normalizeFollowRequest = (state, notification) => {
return state.updateIn(['follow_requests', 'items'], ImmutableOrderedSet(), list => {
return ImmutableOrderedSet([notification.account.id]).union(list);
});
};
export default function userLists(state = initialState, action) {
switch (action.type) {
case FOLLOWERS_FETCH_SUCCESS:
return normalizeList(state, 'followers', action.id, action.accounts, action.next);
case FOLLOWERS_EXPAND_SUCCESS:
return appendToList(state, 'followers', action.id, action.accounts, action.next);
case FOLLOWING_FETCH_SUCCESS:
return normalizeList(state, 'following', action.id, action.accounts, action.next);
case FOLLOWING_EXPAND_SUCCESS:
return appendToList(state, 'following', action.id, action.accounts, action.next);
case REBLOGS_FETCH_SUCCESS:
return state.setIn(['reblogged_by', action.id], ImmutableOrderedSet(action.accounts.map(item => item.id)));
case FAVOURITES_FETCH_SUCCESS:
return state.setIn(['favourited_by', action.id], ImmutableOrderedSet(action.accounts.map(item => item.id)));
case REACTIONS_FETCH_SUCCESS:
return state.setIn(['reactions', action.id], action.reactions.map(({ accounts, ...reaction }) => ({ ...reaction, accounts: ImmutableOrderedSet(accounts.map(account => account.id)) })));
case NOTIFICATIONS_UPDATE:
return action.notification.type === 'follow_request' ? normalizeFollowRequest(state, action.notification) : state;
case FOLLOW_REQUESTS_FETCH_SUCCESS:
return state.setIn(['follow_requests', 'items'], ImmutableOrderedSet(action.accounts.map(item => item.id))).setIn(['follow_requests', 'next'], action.next);
case FOLLOW_REQUESTS_EXPAND_SUCCESS:
return state.updateIn(['follow_requests', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['follow_requests', 'next'], action.next);
case FOLLOW_REQUEST_AUTHORIZE_SUCCESS:
case FOLLOW_REQUEST_REJECT_SUCCESS:
return state.updateIn(['follow_requests', 'items'], list => list.filterNot(item => item === action.id));
case BLOCKS_FETCH_SUCCESS:
return state.setIn(['blocks', 'items'], ImmutableOrderedSet(action.accounts.map(item => item.id))).setIn(['blocks', 'next'], action.next);
case BLOCKS_EXPAND_SUCCESS:
return state.updateIn(['blocks', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['blocks', 'next'], action.next);
case MUTES_FETCH_SUCCESS:
return state.setIn(['mutes', 'items'], ImmutableOrderedSet(action.accounts.map(item => item.id))).setIn(['mutes', 'next'], action.next);
case MUTES_EXPAND_SUCCESS:
return state.updateIn(['mutes', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['mutes', 'next'], action.next);
case DIRECTORY_FETCH_SUCCESS:
return state.setIn(['directory', 'items'], ImmutableOrderedSet(action.accounts.map(item => item.id))).setIn(['directory', 'isLoading'], false);
case DIRECTORY_EXPAND_SUCCESS:
return state.updateIn(['directory', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['directory', 'isLoading'], false);
case DIRECTORY_FETCH_REQUEST:
case DIRECTORY_EXPAND_REQUEST:
return state.setIn(['directory', 'isLoading'], true);
case DIRECTORY_FETCH_FAIL:
case DIRECTORY_EXPAND_FAIL:
return state.setIn(['directory', 'isLoading'], false);
case GROUP_MEMBERS_FETCH_SUCCESS:
return normalizeList(state, 'groups', action.id, action.accounts, action.next);
case GROUP_MEMBERS_EXPAND_SUCCESS:
return appendToList(state, 'groups', action.id, action.accounts, action.next);
case GROUP_REMOVED_ACCOUNTS_FETCH_SUCCESS:
return normalizeList(state, 'groups_removed_accounts', action.id, action.accounts, action.next);
case GROUP_REMOVED_ACCOUNTS_EXPAND_SUCCESS:
return appendToList(state, 'groups_removed_accounts', action.id, action.accounts, action.next);
case GROUP_REMOVED_ACCOUNTS_REMOVE_SUCCESS:
return state.updateIn(['groups_removed_accounts', action.groupId, 'items'], list => list.filterNot(item => item === action.id));
case PINNED_ACCOUNTS_FETCH_SUCCESS:
return normalizeList(state, 'pinned', action.id, action.accounts, action.next);
case BIRTHDAY_REMINDERS_FETCH_SUCCESS:
return state.setIn(['birthday_reminders', action.id], ImmutableOrderedSet(action.accounts.map(item => item.id)));
case FAMILIAR_FOLLOWERS_FETCH_SUCCESS:
return state.setIn(['familiar_followers', action.id], ImmutableOrderedSet(action.accounts.map(item => item.id)));
default:
return state;
}
}

View File

@ -0,0 +1,193 @@
import {
Map as ImmutableMap,
OrderedSet as ImmutableOrderedSet,
Record as ImmutableRecord,
} from 'immutable';
import { AnyAction } from 'redux';
import {
FOLLOWERS_FETCH_SUCCESS,
FOLLOWERS_EXPAND_SUCCESS,
FOLLOWING_FETCH_SUCCESS,
FOLLOWING_EXPAND_SUCCESS,
FOLLOW_REQUESTS_FETCH_SUCCESS,
FOLLOW_REQUESTS_EXPAND_SUCCESS,
FOLLOW_REQUEST_AUTHORIZE_SUCCESS,
FOLLOW_REQUEST_REJECT_SUCCESS,
PINNED_ACCOUNTS_FETCH_SUCCESS,
BIRTHDAY_REMINDERS_FETCH_SUCCESS,
} from '../actions/accounts';
import {
BLOCKS_FETCH_SUCCESS,
BLOCKS_EXPAND_SUCCESS,
} from '../actions/blocks';
import {
DIRECTORY_FETCH_REQUEST,
DIRECTORY_FETCH_SUCCESS,
DIRECTORY_FETCH_FAIL,
DIRECTORY_EXPAND_REQUEST,
DIRECTORY_EXPAND_SUCCESS,
DIRECTORY_EXPAND_FAIL,
} from '../actions/directory';
import {
FAMILIAR_FOLLOWERS_FETCH_SUCCESS,
} from '../actions/familiar_followers';
import {
GROUP_MEMBERS_FETCH_SUCCESS,
GROUP_MEMBERS_EXPAND_SUCCESS,
GROUP_REMOVED_ACCOUNTS_FETCH_SUCCESS,
GROUP_REMOVED_ACCOUNTS_EXPAND_SUCCESS,
GROUP_REMOVED_ACCOUNTS_REMOVE_SUCCESS,
} from '../actions/groups';
import {
REBLOGS_FETCH_SUCCESS,
FAVOURITES_FETCH_SUCCESS,
REACTIONS_FETCH_SUCCESS,
} from '../actions/interactions';
import {
MUTES_FETCH_SUCCESS,
MUTES_EXPAND_SUCCESS,
} from '../actions/mutes';
import {
NOTIFICATIONS_UPDATE,
} from '../actions/notifications';
import type { APIEntity } from 'soapbox/types/entities';
const ListRecord = ImmutableRecord({
next: null as string | null,
items: ImmutableOrderedSet<string>(),
isLoading: false,
});
export const ReactionRecord = ImmutableRecord({
accounts: ImmutableOrderedSet<string>(),
count: 0,
name: '',
});
const ReactionListRecord = ImmutableRecord({
next: null as string | null,
items: ImmutableOrderedSet<Reaction>(),
isLoading: false,
});
const ReducerRecord = ImmutableRecord({
followers: ImmutableMap<string, List>(),
following: ImmutableMap<string, List>(),
reblogged_by: ImmutableMap<string, List>(),
favourited_by: ImmutableMap<string, List>(),
reactions: ImmutableMap<string, ReactionList>(),
follow_requests: ListRecord(),
blocks: ListRecord(),
mutes: ListRecord(),
directory: ListRecord({ isLoading: true }),
groups: ImmutableMap<string, List>(),
groups_removed_accounts: ImmutableMap<string, List>(),
pinned: ImmutableMap<string, List>(),
birthday_reminders: ImmutableMap<string, List>(),
familiar_followers: ImmutableMap<string, List>(),
});
type State = ReturnType<typeof ReducerRecord>;
type List = ReturnType<typeof ListRecord>;
type Reaction = ReturnType<typeof ReactionRecord>;
type ReactionList = ReturnType<typeof ReactionListRecord>;
type Items = ImmutableOrderedSet<string>;
type NestedListPath = ['followers' | 'following' | 'reblogged_by' | 'favourited_by' | 'reactions' | 'groups' | 'groups_removed_accounts' | 'pinned' | 'birthday_reminders' | 'familiar_followers', string];
type ListPath = ['follow_requests' | 'blocks' | 'mutes' | 'directory'];
const normalizeList = (state: State, path: NestedListPath | ListPath, accounts: APIEntity[], next?: string | null) => {
return state.setIn(path, ListRecord({
next,
items: ImmutableOrderedSet(accounts.map(item => item.id)),
}));
};
const appendToList = (state: State, path: NestedListPath | ListPath, accounts: APIEntity[], next: string | null) => {
return state.updateIn(path, map => {
return (map as List).set('next', next).update('items', list => (list as Items).concat(accounts.map(item => item.id)));
});
};
const removeFromList = (state: State, path: NestedListPath | ListPath, accountId: string) => {
return state.updateIn(path, map => {
return (map as List).update('items', list => (list as Items).filterNot(item => item === accountId));
});
};
const normalizeFollowRequest = (state: State, notification: APIEntity) => {
return state.updateIn(['follow_requests', 'items'], list => {
return ImmutableOrderedSet([notification.account.id]).union(list as Items);
});
};
export default function userLists(state = ReducerRecord(), action: AnyAction) {
switch (action.type) {
case FOLLOWERS_FETCH_SUCCESS:
return normalizeList(state, ['followers', action.id], action.accounts, action.next);
case FOLLOWERS_EXPAND_SUCCESS:
return appendToList(state, ['followers', action.id], action.accounts, action.next);
case FOLLOWING_FETCH_SUCCESS:
return normalizeList(state, ['following', action.id], action.accounts, action.next);
case FOLLOWING_EXPAND_SUCCESS:
return appendToList(state, ['following', action.id], action.accounts, action.next);
case REBLOGS_FETCH_SUCCESS:
return normalizeList(state, ['reblogged_by', action.id], action.accounts);
case FAVOURITES_FETCH_SUCCESS:
return normalizeList(state, ['favourited_by', action.id], action.accounts);
case REACTIONS_FETCH_SUCCESS:
return state.setIn(['reactions', action.id], ReactionListRecord({
items: ImmutableOrderedSet<Reaction>(action.reactions.map(({ accounts, ...reaction }: APIEntity) => ReactionRecord({
...reaction,
accounts: ImmutableOrderedSet(accounts.map((account: APIEntity) => account.id)),
}))),
}));
case NOTIFICATIONS_UPDATE:
return action.notification.type === 'follow_request' ? normalizeFollowRequest(state, action.notification) : state;
case FOLLOW_REQUESTS_FETCH_SUCCESS:
return normalizeList(state, ['follow_requests'], action.accounts, action.next);
case FOLLOW_REQUESTS_EXPAND_SUCCESS:
return appendToList(state, ['follow_requests'], action.accounts, action.next);
case FOLLOW_REQUEST_AUTHORIZE_SUCCESS:
case FOLLOW_REQUEST_REJECT_SUCCESS:
return removeFromList(state, ['follow_requests'], action.id);
case BLOCKS_FETCH_SUCCESS:
return normalizeList(state, ['blocks'], action.accounts, action.next);
case BLOCKS_EXPAND_SUCCESS:
return appendToList(state, ['blocks'], action.accounts, action.next);
case MUTES_FETCH_SUCCESS:
return normalizeList(state, ['mutes'], action.accounts, action.next);
case MUTES_EXPAND_SUCCESS:
return appendToList(state, ['mutes'], action.accounts, action.next);
case DIRECTORY_FETCH_SUCCESS:
return normalizeList(state, ['directory'], action.accounts, action.next);
case DIRECTORY_EXPAND_SUCCESS:
return appendToList(state, ['directory'], action.accounts, action.next);
case DIRECTORY_FETCH_REQUEST:
case DIRECTORY_EXPAND_REQUEST:
return state.setIn(['directory', 'isLoading'], true);
case DIRECTORY_FETCH_FAIL:
case DIRECTORY_EXPAND_FAIL:
return state.setIn(['directory', 'isLoading'], false);
case GROUP_MEMBERS_FETCH_SUCCESS:
return normalizeList(state, ['groups', action.id], action.accounts, action.next);
case GROUP_MEMBERS_EXPAND_SUCCESS:
return appendToList(state, ['groups', action.id], action.accounts, action.next);
case GROUP_REMOVED_ACCOUNTS_FETCH_SUCCESS:
return normalizeList(state, ['groups_removed_accounts', action.id], action.accounts, action.next);
case GROUP_REMOVED_ACCOUNTS_EXPAND_SUCCESS:
return appendToList(state, ['groups_removed_accounts', action.id], action.accounts, action.next);
case GROUP_REMOVED_ACCOUNTS_REMOVE_SUCCESS:
return removeFromList(state, ['groups_removed_accounts', action.groupId], action.id);
case PINNED_ACCOUNTS_FETCH_SUCCESS:
return normalizeList(state, ['pinned', action.id], action.accounts, action.next);
case BIRTHDAY_REMINDERS_FETCH_SUCCESS:
return normalizeList(state, ['birthday_reminders', action.id], action.accounts, action.next);
case FAMILIAR_FOLLOWERS_FETCH_SUCCESS:
return normalizeList(state, ['familiar_followers', action.id], action.accounts, action.next);
default:
return state;
}
}

View File

@ -221,7 +221,7 @@ export const makeGetNotification = () => {
}; };
export const getAccountGallery = createSelector([ export const getAccountGallery = createSelector([
(state: RootState, id: string) => state.timelines.getIn([`account:${id}:media`, 'items'], ImmutableList()), (state: RootState, id: string) => state.timelines.get(`account:${id}:media`)?.items || ImmutableOrderedSet<string>(),
(state: RootState) => state.statuses, (state: RootState) => state.statuses,
(state: RootState) => state.accounts, (state: RootState) => state.accounts,
], (statusIds, statuses, accounts) => { ], (statusIds, statuses, accounts) => {
@ -365,7 +365,7 @@ type ColumnQuery = { type: string, prefix?: string };
export const makeGetStatusIds = () => createSelector([ export const makeGetStatusIds = () => createSelector([
(state: RootState, { type, prefix }: ColumnQuery) => getSettings(state).get(prefix || type, ImmutableMap()), (state: RootState, { type, prefix }: ColumnQuery) => getSettings(state).get(prefix || type, ImmutableMap()),
(state: RootState, { type }: ColumnQuery) => state.timelines.getIn([type, 'items'], ImmutableOrderedSet()), (state: RootState, { type }: ColumnQuery) => state.timelines.get(type)?.items || ImmutableOrderedSet(),
(state: RootState) => state.statuses, (state: RootState) => state.statuses,
], (columnSettings, statusIds: ImmutableOrderedSet<string>, statuses) => { ], (columnSettings, statusIds: ImmutableOrderedSet<string>, statuses) => {
return statusIds.filter((id: string) => { return statusIds.filter((id: string) => {

View File

@ -87,7 +87,6 @@ export function connectStream(
}; };
} }
export default function getStream( export default function getStream(
streamingAPIBaseURL: string, streamingAPIBaseURL: string,
accessToken: string, accessToken: string,

View File

@ -58,12 +58,7 @@
} }
.crypto-donate-modal { .crypto-donate-modal {
background: var(--foreground-color); .crypto-address {
border-radius: 8px; padding: 0;
padding-bottom: 13px;
.crypto-address__actions .svg-icon {
width: 22px;
height: 22px;
} }
} }