Reducers: TypeScript

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
environments/review-gleasonato-trtlxz/deployments/373^2
marcin mikołajczak 2022-06-24 00:33:23 +02:00
rodzic b9fc2c6e58
commit 4e545f0638
31 zmienionych plików z 130 dodań i 136 usunięć

Wyświetl plik

@ -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;
@ -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;

Wyświetl plik

@ -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;

Wyświetl plik

@ -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 });

Wyświetl plik

@ -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();

Wyświetl plik

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

Wyświetl plik

@ -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;

Wyświetl plik

@ -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;

Wyświetl plik

@ -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;

Wyświetl plik

@ -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 });

Wyświetl plik

@ -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>

Wyświetl plik

@ -128,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

Wyświetl plik

@ -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);

Wyświetl plik

@ -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') });

Wyświetl plik

@ -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());

Wyświetl plik

@ -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) => {

Wyświetl plik

@ -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));

Wyświetl plik

@ -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

Wyświetl plik

@ -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}

Wyświetl plik

@ -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' />}

Wyświetl plik

@ -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 || '' }} /> }} />}

Wyświetl plik

@ -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;

Wyświetl plik

@ -94,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' />}

Wyświetl plik

@ -50,7 +50,6 @@ const ReblogsModal: React.FC<IReblogsModal> = ({ onClose, statusId }) => {
); );
} }
return ( return (
<Modal <Modal
title={<FormattedMessage id='column.reblogs' defaultMessage='Reposts' />} title={<FormattedMessage id='column.reblogs' defaultMessage='Reposts' />}

Wyświetl plik

@ -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));

Wyświetl plik

@ -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,
})); });
}); });
}); });

Wyświetl plik

@ -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);
}); });
}); });

Wyświetl plik

@ -14,7 +14,6 @@ import compareId from '../compare_id';
import type { AnyAction } from 'redux'; import type { AnyAction } from 'redux';
import type { APIEntity } from 'soapbox/types/entities'; import type { APIEntity } from 'soapbox/types/entities';
const ConversationRecord = ImmutableRecord({ const ConversationRecord = ImmutableRecord({
id: '', id: '',
unread: false, unread: false,

Wyświetl plik

@ -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:

Wyświetl plik

@ -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:

Wyświetl plik

@ -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) => {

Wyświetl plik

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