pl-fe: remove immutable from timelines reducer

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
This commit is contained in:
marcin mikołajczak 2024-11-10 17:13:39 +01:00
parent b2d5bbf537
commit fb4d14bd8b
8 changed files with 191 additions and 196 deletions

View file

@ -76,7 +76,7 @@ interface TimelineDequeueAction {
const dequeueTimeline = (timelineId: string, expandFunc?: (lastStatusId: string) => void) => const dequeueTimeline = (timelineId: string, expandFunc?: (lastStatusId: string) => void) =>
(dispatch: AppDispatch, getState: () => RootState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const state = getState(); const state = getState();
const queuedCount = state.timelines.get(timelineId)?.totalQueuedItemsCount || 0; const queuedCount = state.timelines[timelineId]?.totalQueuedItemsCount || 0;
if (queuedCount <= 0) return; if (queuedCount <= 0) return;
@ -185,9 +185,9 @@ const fetchHomeTimeline = (expand = false, done = noOp) =>
const params: HomeTimelineParams = {}; const params: HomeTimelineParams = {};
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
if (expand && state.timelines.get('home')?.isLoading) return; if (expand && state.timelines.home?.isLoading) return;
const fn = (expand && state.timelines.get('home')?.next?.()) || getClient(state).timelines.homeTimeline(params); const fn = (expand && state.timelines.home?.next?.()) || getClient(state).timelines.homeTimeline(params);
return dispatch(handleTimelineExpand('home', fn, false, done)); return dispatch(handleTimelineExpand('home', fn, false, done));
}; };
@ -200,9 +200,9 @@ const fetchPublicTimeline = ({ onlyMedia, local, instance }: Record<string, any>
const params: PublicTimelineParams = { only_media: onlyMedia, local: instance ? false : local, instance }; const params: PublicTimelineParams = { only_media: onlyMedia, local: instance ? false : local, instance };
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
if (expand && state.timelines.get(timelineId)?.isLoading) return; if (expand && state.timelines[timelineId]?.isLoading) return;
const fn = (expand && state.timelines.get(timelineId)?.next?.()) || getClient(state).timelines.publicTimeline(params); const fn = (expand && state.timelines[timelineId]?.next?.()) || getClient(state).timelines.publicTimeline(params);
return dispatch(handleTimelineExpand(timelineId, fn, false, done)); return dispatch(handleTimelineExpand(timelineId, fn, false, done));
}; };
@ -215,9 +215,9 @@ const fetchBubbleTimeline = ({ onlyMedia }: Record<string, any> = {}, expand = f
const params: PublicTimelineParams = { only_media: onlyMedia }; const params: PublicTimelineParams = { only_media: onlyMedia };
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
if (expand && state.timelines.get(timelineId)?.isLoading) return; if (expand && state.timelines[timelineId]?.isLoading) return;
const fn = (expand && state.timelines.get(timelineId)?.next?.()) || getClient(state).timelines.bubbleTimeline(params); const fn = (expand && state.timelines[timelineId]?.next?.()) || getClient(state).timelines.bubbleTimeline(params);
return dispatch(handleTimelineExpand(timelineId, fn, false, done)); return dispatch(handleTimelineExpand(timelineId, fn, false, done));
}; };
@ -231,9 +231,9 @@ const fetchAccountTimeline = (accountId: string, { exclude_replies, pinned, only
if (pinned || only_media) params.with_muted = true; if (pinned || only_media) params.with_muted = true;
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
if (expand && state.timelines.get(timelineId)?.isLoading) return; if (expand && state.timelines[timelineId]?.isLoading) return;
const fn = (expand && state.timelines.get(timelineId)?.next?.()) || getClient(state).accounts.getAccountStatuses(accountId, params); const fn = (expand && state.timelines[timelineId]?.next?.()) || getClient(state).accounts.getAccountStatuses(accountId, params);
return dispatch(handleTimelineExpand(timelineId, fn, false, done)); return dispatch(handleTimelineExpand(timelineId, fn, false, done));
}; };
@ -246,9 +246,9 @@ const fetchListTimeline = (listId: string, expand = false, done = noOp) =>
const params: ListTimelineParams = {}; const params: ListTimelineParams = {};
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
if (expand && state.timelines.get(timelineId)?.isLoading) return; if (expand && state.timelines[timelineId]?.isLoading) return;
const fn = (expand && state.timelines.get(timelineId)?.next?.()) || getClient(state).timelines.listTimeline(listId, params); const fn = (expand && state.timelines[timelineId]?.next?.()) || getClient(state).timelines.listTimeline(listId, params);
return dispatch(handleTimelineExpand(timelineId, fn, false, done)); return dispatch(handleTimelineExpand(timelineId, fn, false, done));
}; };
@ -262,9 +262,9 @@ const fetchGroupTimeline = (groupId: string, { only_media, limit }: Record<strin
if (only_media) params.with_muted = true; if (only_media) params.with_muted = true;
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
if (expand && state.timelines.get(timelineId)?.isLoading) return; if (expand && state.timelines[timelineId]?.isLoading) return;
const fn = (expand && state.timelines.get(timelineId)?.next?.()) || getClient(state).timelines.groupTimeline(groupId, params); const fn = (expand && state.timelines[timelineId]?.next?.()) || getClient(state).timelines.groupTimeline(groupId, params);
return dispatch(handleTimelineExpand(timelineId, fn, false, done)); return dispatch(handleTimelineExpand(timelineId, fn, false, done));
}; };
@ -280,11 +280,11 @@ const fetchHashtagTimeline = (hashtag: string, { tags }: Record<string, any> = {
none: parseTags(tags, 'none'), none: parseTags(tags, 'none'),
}; };
if (expand && state.timelines.get(timelineId)?.isLoading) return; if (expand && state.timelines[timelineId]?.isLoading) return;
if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale(); if (useSettingsStore.getState().settings.autoTranslate) params.language = getLocale();
const fn = (expand && state.timelines.get(timelineId)?.next?.()) || getClient(state).timelines.hashtagTimeline(hashtag, params); const fn = (expand && state.timelines[timelineId]?.next?.()) || getClient(state).timelines.hashtagTimeline(hashtag, params);
return dispatch(handleTimelineExpand(timelineId, fn, false, done)); return dispatch(handleTimelineExpand(timelineId, fn, false, done));
}; };

View file

@ -27,8 +27,8 @@ const AccountGallery = () => {
} = useAccountLookup(username, { withRelationship: true }); } = useAccountLookup(username, { withRelationship: true });
const attachments: Array<AccountGalleryAttachment> = useAppSelector((state) => account ? getAccountGallery(state, account.id) : []); const attachments: Array<AccountGalleryAttachment> = useAppSelector((state) => account ? getAccountGallery(state, account.id) : []);
const isLoading = useAppSelector((state) => state.timelines.get(`account:${account?.id}:with_replies:media`)?.isLoading); const isLoading = useAppSelector((state) => state.timelines[`account:${account?.id}:with_replies:media`]?.isLoading);
const hasMore = useAppSelector((state) => state.timelines.get(`account:${account?.id}:with_replies:media`)?.hasMore); const hasMore = useAppSelector((state) => state.timelines[`account:${account?.id}:with_replies:media`]?.hasMore);
const handleScrollToBottom = () => { const handleScrollToBottom = () => {
if (hasMore) { if (hasMore) {

View file

@ -41,8 +41,8 @@ const AccountTimeline: React.FC<IAccountTimeline> = ({ params, withReplies = fal
const isBlocked = account?.relationship?.blocked_by; const isBlocked = account?.relationship?.blocked_by;
const unavailable = isBlocked && !features.blockersVisible; const unavailable = isBlocked && !features.blockersVisible;
const isLoading = useAppSelector(state => state.timelines.get(`account:${path}`)?.isLoading === true); const isLoading = useAppSelector(state => state.timelines[`account:${path}`]?.isLoading === true);
const hasMore = useAppSelector(state => state.timelines.get(`account:${path}`)?.hasMore === true); const hasMore = useAppSelector(state => state.timelines[`account:${path}`]?.hasMore === true);
const accountUsername = account?.username || params.username; const accountUsername = account?.username || params.username;

View file

@ -29,7 +29,7 @@ const HomeTimeline: React.FC = () => {
const polling = useRef<NodeJS.Timeout | null>(null); const polling = useRef<NodeJS.Timeout | null>(null);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const isPartial = useAppSelector(state => state.timelines.get('home')?.isPartial === true); const isPartial = useAppSelector(state => state.timelines.home?.isPartial === true);
const handleLoadMore = (maxId: string) => { const handleLoadMore = (maxId: string) => {
dispatch(fetchHomeTimeline(true)); dispatch(fetchHomeTimeline(true));

View file

@ -1,4 +1,3 @@
import { OrderedSet } from 'immutable';
import React, { useState } from 'react'; import React, { useState } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl'; import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
@ -47,7 +46,7 @@ const OtherActionsStep = ({
const features = useFeatures(); const features = useFeatures();
const intl = useIntl(); const intl = useIntl();
const statusIds = useAppSelector((state) => OrderedSet(state.timelines.get(`account:${account.id}:with_replies`)!.items).union(selectedStatusIds) as OrderedSet<string>); const statusIds = useAppSelector((state) => [...new Set([...state.timelines[`account:${account.id}:with_replies`]!.items, ...selectedStatusIds])]);
const isBlocked = block; const isBlocked = block;
const isForward = forward; const isForward = forward;
const canForward = !account.local && features.federating; const canForward = !account.local && features.federating;

View file

@ -35,10 +35,10 @@ const Timeline: React.FC<ITimeline> = ({
const statusIds = useAppSelector(state => getStatusIds(state, { type: timelineId, prefix })); const statusIds = useAppSelector(state => getStatusIds(state, { type: timelineId, prefix }));
const lastStatusId = statusIds.at(-1); const lastStatusId = statusIds.at(-1);
const isLoading = useAppSelector(state => (state.timelines.get(timelineId) || { isLoading: true }).isLoading === true); const isLoading = useAppSelector(state => state.timelines[timelineId]?.isLoading !== false);
const isPartial = useAppSelector(state => (state.timelines.get(timelineId)?.isPartial || false) === true); const isPartial = useAppSelector(state => (state.timelines[timelineId]?.isPartial || false) === true);
const hasMore = useAppSelector(state => state.timelines.get(timelineId)?.hasMore === true); const hasMore = useAppSelector(state => state.timelines[timelineId]?.hasMore === true);
const totalQueuedItemsCount = useAppSelector(state => state.timelines.get(timelineId)?.totalQueuedItemsCount || 0); const totalQueuedItemsCount = useAppSelector(state => state.timelines[timelineId]?.totalQueuedItemsCount || 0);
const handleDequeueTimeline = useCallback(() => { const handleDequeueTimeline = useCallback(() => {
dispatch(dequeueTimeline(timelineId, onLoadMore)); dispatch(dequeueTimeline(timelineId, onLoadMore));

View file

@ -1,10 +1,5 @@
import {
Map as ImmutableMap,
List as ImmutableList,
OrderedSet as ImmutableOrderedSet,
Record as ImmutableRecord,
} from 'immutable';
import sample from 'lodash/sample'; import sample from 'lodash/sample';
import { create } from 'mutative';
import { ACCOUNT_BLOCK_SUCCESS, ACCOUNT_MUTE_SUCCESS } from '../actions/accounts'; import { ACCOUNT_BLOCK_SUCCESS, ACCOUNT_MUTE_SUCCESS } from '../actions/accounts';
import { PIN_SUCCESS, UNPIN_SUCCESS, type InteractionsAction } from '../actions/interactions'; import { PIN_SUCCESS, UNPIN_SUCCESS, type InteractionsAction } from '../actions/interactions';
@ -32,50 +27,68 @@ import type { AnyAction } from 'redux';
const TRUNCATE_LIMIT = 40; const TRUNCATE_LIMIT = 40;
const TRUNCATE_SIZE = 20; const TRUNCATE_SIZE = 20;
const TimelineRecord = ImmutableRecord({ interface Timeline {
unread: number;
top: boolean;
isLoading: boolean;
hasMore: boolean;
next: (() => Promise<PaginatedResponse<BaseStatus>>) | null;
prev: (() => Promise<PaginatedResponse<BaseStatus>>) | null;
items: Array<string>;
queuedItems: Array<string>; //max= MAX_QUEUED_ITEMS
totalQueuedItemsCount: number; //used for queuedItems overflow for MAX_QUEUED_ITEMS+
loadingFailed: boolean;
isPartial: boolean;
}
const newTimeline = (): Timeline => ({
unread: 0, unread: 0,
top: true, top: true,
isLoading: false, isLoading: false,
hasMore: true, hasMore: true,
next: null as (() => Promise<PaginatedResponse<BaseStatus>>) | null, next: null,
prev: null as (() => Promise<PaginatedResponse<BaseStatus>>) | null, prev: null,
items: ImmutableOrderedSet<string>(), items: [],
queuedItems: ImmutableOrderedSet<string>(), //max= MAX_QUEUED_ITEMS queuedItems: [], //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, loadingFailed: false,
isPartial: false, isPartial: false,
}); });
const initialState = ImmutableMap<string, Timeline>(); const initialState: State = {};
type State = ImmutableMap<string, Timeline>; type State = Record<string, Timeline>;
type Timeline = ReturnType<typeof TimelineRecord>;
const getStatusIds = (statuses: Array<Pick<BaseStatus, 'id'>> = []) => ( const getStatusIds = (statuses: Array<Pick<BaseStatus, 'id'>> = []) => statuses.map(status => status.id);
ImmutableOrderedSet(statuses.map(status => status.id))
);
const mergeStatusIds = (oldIds = ImmutableOrderedSet<string>(), newIds = ImmutableOrderedSet<string>()) => ( const mergeStatusIds = (oldIds: Array<string>, newIds: Array<string>) => [...new Set([...newIds, ...oldIds])];
newIds.union(oldIds)
);
const addStatusId = (oldIds = ImmutableOrderedSet<string>(), newId: string) => ( const addStatusId = (oldIds = Array<string>(), newId: string) => (
mergeStatusIds(oldIds, ImmutableOrderedSet([newId])) mergeStatusIds(oldIds, [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: ImmutableOrderedSet<string>, truncateLimit: number, newSize: number) => ( const truncate = (items: Array<string>, truncateLimit: number, newSize: number) => (
items.size > truncateLimit ? items.take(newSize) : items items.length > truncateLimit ? items.slice(0, newSize) : items
); );
const truncateIds = (items: ImmutableOrderedSet<string>) => truncate(items, TRUNCATE_LIMIT, TRUNCATE_SIZE); const truncateIds = (items: Array<string>) => truncate(items, TRUNCATE_LIMIT, TRUNCATE_SIZE);
const updateTimeline = (state: State, timelineId: string, updater: (timeline: Timeline) => void) => {
state[timelineId] = state[timelineId] || newTimeline();
updater(state[timelineId]);
};
const setLoading = (state: State, timelineId: string, loading: boolean) => const setLoading = (state: State, timelineId: string, loading: boolean) =>
state.update(timelineId, TimelineRecord(), timeline => timeline.set('isLoading', loading)); updateTimeline(state, timelineId, (timeline) => {
timeline.isLoading = loading;
});
// Keep track of when a timeline failed to load // Keep track of when a timeline failed to load
const setFailed = (state: State, timelineId: string, failed: boolean) => const setFailed = (state: State, timelineId: string, failed: boolean) =>
state.update(timelineId, TimelineRecord(), timeline => timeline.set('loadingFailed', failed)); updateTimeline(state, timelineId, (timeline) => {
timeline.loadingFailed = failed;
});
const expandNormalizedTimeline = ( const expandNormalizedTimeline = (
state: State, state: State,
@ -89,65 +102,61 @@ const expandNormalizedTimeline = (
) => { ) => {
const newIds = getStatusIds(statuses); const newIds = getStatusIds(statuses);
return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => { updateTimeline(state, timelineId, (timeline) => {
timeline.set('isLoading', false); timeline.isLoading = false;
timeline.set('loadingFailed', false); timeline.loadingFailed = false;
timeline.set('isPartial', isPartial); timeline.isPartial = isPartial;
timeline.set('next', next); timeline.next = next;
timeline.set('prev', prev); timeline.prev = prev;
if (!next && !isLoadingRecent) timeline.set('hasMore', false); if (!next && !isLoadingRecent) timeline.hasMore = false;
// Pinned timelines can be replaced entirely // Pinned timelines can be replaced entirely
if (timelineId.endsWith(':pinned')) { if (timelineId.endsWith(':pinned')) {
timeline.set('items', newIds); timeline.items = newIds;
return; return;
} }
if (!newIds.isEmpty()) { if (newIds.length) {
timeline.update('items', oldIds => {
if (pos === 'end') { if (pos === 'end') {
return mergeStatusIds(newIds, oldIds); timeline.items = mergeStatusIds(newIds, timeline.items);
} else { } else {
return mergeStatusIds(oldIds, newIds); timeline.items = mergeStatusIds(timeline.items, newIds);
}
} }
}); });
}
}));
}; };
const updateTimeline = (state: State, timelineId: string, statusId: string) => { const appendStatus = (state: State, timelineId: string, statusId: string) => {
const top = state.get(timelineId)?.top; const top = state[timelineId]?.top;
const oldIds = state.get(timelineId)?.items || ImmutableOrderedSet<string>(); const oldIds = state[timelineId]?.items || [];
const unread = state.get(timelineId)?.unread || 0; const unread = state[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, TimelineRecord(), timeline => timeline.withMutations(timeline => { updateTimeline(state, timelineId, (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.items = truncateIds(newIds);
} else { } else {
timeline.set('unread', unread + 1); timeline.unread = unread + 1;
timeline.set('items', newIds); timeline.items = newIds;
} }
})); });
}; };
const updateTimelineQueue = (state: State, timelineId: string, statusId: string) => { const updateTimelineQueue = (state: State, timelineId: string, statusId: string) => {
const queuedIds = state.get(timelineId)?.queuedItems || ImmutableOrderedSet<string>(); updateTimeline(state, timelineId, (timeline) => {
const listedIds = state.get(timelineId)?.items || ImmutableOrderedSet<string>(); const { queuedItems: queuedIds, items: listedIds, totalQueuedItemsCount: queuedCount } = timeline;
const queuedCount = state.get(timelineId)?.totalQueuedItemsCount || 0;
if (queuedIds.includes(statusId)) return state; if (queuedIds.includes(statusId)) return;
if (listedIds.includes(statusId)) return state; if (listedIds.includes(statusId)) return;
return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => { timeline.totalQueuedItemsCount = queuedCount + 1;
timeline.set('totalQueuedItemsCount', queuedCount + 1); timeline.queuedItems = addStatusId(queuedIds, statusId).slice(0, MAX_QUEUED_ITEMS);
timeline.set('queuedItems', addStatusId(queuedIds, statusId).take(MAX_QUEUED_ITEMS)); });
}));
}; };
const shouldDelete = (timelineId: string, excludeAccount?: string) => { const shouldDelete = (timelineId: string, excludeAccount?: string) => {
@ -157,39 +166,39 @@ const shouldDelete = (timelineId: string, excludeAccount?: string) => {
return true; return true;
}; };
const deleteStatus = (state: State, statusId: string, references: ImmutableMap<string, [string, string]> | Array<[string, string]>, excludeAccount?: string) => const deleteStatus = (state: State, statusId: string, references: Array<string>, excludeAccount?: string) => {
state.withMutations(state => { for (const timelineId in state) {
state.keySeq().forEach(timelineId => {
if (shouldDelete(timelineId, excludeAccount)) { if (shouldDelete(timelineId, excludeAccount)) {
state.updateIn([timelineId, 'items'], ids => (ids as ImmutableOrderedSet<string>).delete(statusId)); state[timelineId].items = state[timelineId].items.filter(id => id !== statusId);
state.updateIn([timelineId, 'queuedItems'], ids => (ids as ImmutableOrderedSet<string>).delete(statusId)); state[timelineId].queuedItems = state[timelineId].queuedItems.filter(id => id !== statusId);
}
} }
});
// Remove reblogs of deleted status // Remove reblogs of deleted status
references.forEach(ref => { references.forEach(ref => {
deleteStatus(state, ref[0], [], excludeAccount); deleteStatus(state, ref, [], excludeAccount);
});
}); });
};
const clearTimeline = (state: State, timelineId: string) => state.set(timelineId, TimelineRecord()); const clearTimeline = (state: State, timelineId: string) => {
state[timelineId] = newTimeline();
};
const updateTop = (state: State, timelineId: string, top: boolean) => const updateTop = (state: State, timelineId: string, top: boolean) =>
state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations(timeline => { updateTimeline(state, timelineId, (timeline) => {
if (top) timeline.set('unread', 0); if (top) timeline.unread = 0;
timeline.set('top', top); timeline.top = top;
})); });
const isReblogOf = (reblog: Pick<Status, 'reblog_id'>, status: Pick<Status, 'id'>) => reblog.reblog_id === status.id; const isReblogOf = (reblog: Pick<Status, 'reblog_id'>, status: Pick<Status, 'id'>) => reblog.reblog_id === status.id;
const statusToReference = (status: Pick<Status, 'id' | 'account'>) => [status.id, status.account];
const buildReferencesTo = ( const buildReferencesTo = (
statuses: ImmutableMap<string, Pick<Status, 'id' | 'account' | 'reblog_id'>>, statuses: Record<string, Pick<Status, 'id' | 'account' | 'reblog_id'>>,
status: Pick<Status, 'id'>, status: Pick<Status, 'id'>,
) => ( ) => (
statuses Object.values(statuses)
.filter(reblog => isReblogOf(reblog, status)) .filter(reblog => isReblogOf(reblog, status))
.map(statusToReference) as ImmutableMap<string, [string, string]> .map(status => status.id)
); );
// const filterTimeline = (state: State, timelineId: string, relationship: APIEntity, statuses: ImmutableList<ImmutableMap<string, any>>) => // const filterTimeline = (state: State, timelineId: string, relationship: APIEntity, statuses: ImmutableList<ImmutableMap<string, any>>) =>
@ -198,29 +207,28 @@ const buildReferencesTo = (
// statuses.getIn([statusId, 'account']) === relationship.id, // statuses.getIn([statusId, 'account']) === relationship.id,
// )); // ));
const filterTimelines = (state: State, relationship: Relationship, statuses: ImmutableMap<string, Pick<Status, 'id' | 'account' | 'account_id' | 'reblog_id'>>) => const filterTimelines = (state: State, relationship: Relationship, statuses: Record<string, Pick<Status, 'id' | 'account' | 'account_id' | 'reblog_id'>>) => {
state.withMutations(state => { for (const statusId in statuses) {
statuses.forEach(status => { const status = statuses[statusId];
if (status.account_id !== relationship.id) return; if (status.account_id !== relationship.id) return;
const references = buildReferencesTo(statuses, status); const references = buildReferencesTo(statuses, status);
deleteStatus(state, status.id, references, relationship.id); deleteStatus(state, status.id, references, relationship.id);
}); }
}); };
const timelineDequeue = (state: State, timelineId: string) => { const timelineDequeue = (state: State, timelineId: string) => {
const top = state.getIn([timelineId, 'top']); updateTimeline(state, timelineId, (timeline) => {
const top = timeline.top;
return state.update(timelineId, TimelineRecord(), timeline => timeline.withMutations((timeline: Timeline) => {
const queuedIds = timeline.queuedItems; const queuedIds = timeline.queuedItems;
timeline.update('items', ids => { const newIds = mergeStatusIds(timeline.items, queuedIds);
const newIds = mergeStatusIds(ids, queuedIds); timeline.items = top ? truncateIds(newIds) : newIds;
return top ? truncateIds(newIds) : newIds;
});
timeline.set('queuedItems', ImmutableOrderedSet()); timeline.queuedItems = [];
timeline.set('totalQueuedItemsCount', 0); timeline.totalQueuedItemsCount = 0;
})); });
}; };
// const timelineDisconnect = (state: State, timelineId: string) => // const timelineDisconnect = (state: State, timelineId: string) =>
@ -244,123 +252,111 @@ const getTimelinesForStatus = (status: Pick<BaseStatus, 'visibility' | 'group'>)
}; };
// 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: ImmutableOrderedSet<string>, oldId: string, newId: string) => { const replaceId = (ids: Array<string>, oldId: string, newId: string) => {
const list = ImmutableList(ids); const index = ids.indexOf(oldId);
const index = list.indexOf(oldId);
if (index > -1) { if (index > -1) {
return ImmutableOrderedSet(list.set(index, newId)); ids[index] = newId;
} else {
return ids;
} }
}; };
const importPendingStatus = (state: State, params: BaseStatus, idempotencyKey: string) => { const importPendingStatus = (state: State, params: BaseStatus, idempotencyKey: string) => {
const statusId = `末pending-${idempotencyKey}`; const statusId = `末pending-${idempotencyKey}`;
return state.withMutations(state => {
const timelineIds = getTimelinesForStatus(params); const timelineIds = getTimelinesForStatus(params);
timelineIds.forEach(timelineId => { timelineIds.forEach(timelineId => {
updateTimelineQueue(state, timelineId, statusId); updateTimelineQueue(state, timelineId, statusId);
}); });
});
}; };
const replacePendingStatus = (state: State, idempotencyKey: string, newId: string) => { 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 => { for (const timelineId in state) {
state.keySeq().forEach(timelineId => { replaceId(state[timelineId].items, oldId, newId);
state.updateIn([timelineId, 'items'], ids => replaceId((ids as ImmutableOrderedSet<string>), oldId, newId)); replaceId(state[timelineId].queuedItems, oldId, newId);
state.updateIn([timelineId, 'queuedItems'], ids => replaceId((ids as ImmutableOrderedSet<string>), oldId, newId)); }
});
});
}; };
const importStatus = (state: State, status: BaseStatus, idempotencyKey: string) => const importStatus = (state: State, status: BaseStatus, idempotencyKey: string) =>{
state.withMutations(state => {
replacePendingStatus(state, idempotencyKey, status.id); replacePendingStatus(state, idempotencyKey, status.id);
const timelineIds = getTimelinesForStatus(status); const timelineIds = getTimelinesForStatus(status);
timelineIds.forEach(timelineId => { timelineIds.forEach(timelineId => {
updateTimeline(state, timelineId, status.id); appendStatus(state, timelineId, status.id);
});
}); });
};
const handleExpandFail = (state: State, timelineId: string) => state.withMutations(state => { const handleExpandFail = (state: State, timelineId: string) => {
setLoading(state, timelineId, false); setLoading(state, timelineId, false);
setFailed(state, timelineId, true); setFailed(state, timelineId, true);
}); };
const timelines = (state: State = initialState, action: AnyAction | InteractionsAction | StatusesAction | TimelineAction) => { const timelines = (state: State = initialState, action: AnyAction | InteractionsAction | StatusesAction | TimelineAction): State => {
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;
return importPendingStatus(state, action.params, action.idempotencyKey); return create(state, (draft) => importPendingStatus(draft, action.params, action.idempotencyKey));
case STATUS_CREATE_SUCCESS: case STATUS_CREATE_SUCCESS:
if (action.status.scheduled_at || action.editing) return state; if (action.status.scheduled_at || action.editing) return state;
return importStatus(state, action.status, action.idempotencyKey); return create(state, (draft) => importStatus(draft, action.status, action.idempotencyKey));
case TIMELINE_EXPAND_REQUEST: case TIMELINE_EXPAND_REQUEST:
return setLoading(state, action.timeline, true); return create(state, (draft) => setLoading(draft, action.timeline, true));
case TIMELINE_EXPAND_FAIL: case TIMELINE_EXPAND_FAIL:
return handleExpandFail(state, action.timeline); return create(state, (draft) => handleExpandFail(draft, action.timeline));
case TIMELINE_EXPAND_SUCCESS: case TIMELINE_EXPAND_SUCCESS:
return expandNormalizedTimeline( return create(state, (draft) => expandNormalizedTimeline(
state, draft,
action.timeline, action.timeline,
action.statuses, action.statuses,
action.next, action.next,
action.prev, action.prev,
action.partial, action.partial,
action.isLoadingRecent, action.isLoadingRecent,
); ));
case TIMELINE_UPDATE: case TIMELINE_UPDATE:
return updateTimeline(state, action.timeline, action.statusId); return create(state, (draft) => appendStatus(draft, action.timeline, action.statusId));
case TIMELINE_UPDATE_QUEUE: case TIMELINE_UPDATE_QUEUE:
return updateTimelineQueue(state, action.timeline, action.statusId); return create(state, (draft) => updateTimelineQueue(draft, action.timeline, action.statusId));
case TIMELINE_DEQUEUE: case TIMELINE_DEQUEUE:
return timelineDequeue(state, action.timeline); return create(state, (draft) => timelineDequeue(draft, action.timeline));
case TIMELINE_DELETE: case TIMELINE_DELETE:
return deleteStatus(state, action.statusId, action.references, action.reblogOf); return create(state, (draft) => deleteStatus(draft, action.statusId, action.references, action.reblogOf));
case TIMELINE_CLEAR: case TIMELINE_CLEAR:
return clearTimeline(state, action.timeline); return create(state, (draft) => clearTimeline(draft, action.timeline));
case ACCOUNT_BLOCK_SUCCESS: case ACCOUNT_BLOCK_SUCCESS:
case ACCOUNT_MUTE_SUCCESS: case ACCOUNT_MUTE_SUCCESS:
return filterTimelines(state, action.relationship, action.statuses); return create(state, (draft) => filterTimelines(draft, action.relationship, action.statuses));
// case ACCOUNT_UNFOLLOW_SUCCESS: // case ACCOUNT_UNFOLLOW_SUCCESS:
// return filterTimeline(state, 'home', action.relationship, action.statuses); // return filterTimeline(state, 'home', action.relationship, action.statuses);
case TIMELINE_SCROLL_TOP: case TIMELINE_SCROLL_TOP:
return updateTop(state, action.timeline, action.top); return create(state, (draft) => updateTop(state, action.timeline, action.top));
case TIMELINE_INSERT: case TIMELINE_INSERT:
return state.update(action.timeline, TimelineRecord(), timeline => timeline.withMutations(timeline => { return create(state, (draft) => updateTimeline(draft, action.timeline, (timeline) => {
timeline.update('items', oldIds => { let oldIdsArray = timeline.items;
let oldIdsArray = oldIds.toArray();
const existingSuggestionId = oldIdsArray.find(key => key.includes('末suggestions')); const existingSuggestionId = oldIdsArray.find(key => key.includes('末suggestions'));
if (existingSuggestionId) { if (existingSuggestionId) {
oldIdsArray = oldIdsArray.slice(1); oldIdsArray = oldIdsArray.slice(1);
} }
const positionInTimeline = sample([5, 6, 7, 8, 9]) as number; const positionInTimeline = sample([5, 6, 7, 8, 9]) as number;
if (oldIds.last()) { if (timeline.items.at(-1)) {
oldIdsArray.splice(positionInTimeline, 0, `末suggestions-${oldIds.last()}`); oldIdsArray.splice(positionInTimeline, 0, `末suggestions-${timeline.items.at(-1)}`);
} }
return ImmutableOrderedSet(oldIdsArray);
}); timeline.items = oldIdsArray;
})); }));
case PIN_SUCCESS: case PIN_SUCCESS:
return state.updateIn( return create(state, (draft) => updateTimeline(draft, `account:${action.accountId}:with_replies:pinned`, (timeline) => {
[`account:${action.accountId}:with_replies:pinned`, 'items'], timeline.items = [...new Set([action.statusId, ...timeline.items])];
ids => ImmutableOrderedSet([action.statusId]).union(ids as ImmutableOrderedSet<string>), }));
);
case UNPIN_SUCCESS: case UNPIN_SUCCESS:
return state.updateIn( return create(state, (draft) => updateTimeline(draft, `account:${action.accountId}:with_replies:pinned`, (timeline) => {
[`account:${action.accountId}:with_replies:pinned`, 'items'], timeline.items = timeline.items.filter((id) => id !== action.statusId);
ids => (ids as ImmutableOrderedSet<string>).delete(action.statusId), }));
);
default: default:
return state; return state;
} }

View file

@ -209,7 +209,7 @@ type AccountGalleryAttachment = MediaAttachment & {
} }
const getAccountGallery = createSelector([ const getAccountGallery = createSelector([
(state: RootState, id: string) => state.timelines.get(`account:${id}:with_replies:media`)?.items || ImmutableOrderedSet<string>(), (state: RootState, id: string) => state.timelines[`account:${id}:with_replies:media`]?.items || [],
(state: RootState) => state.statuses, (state: RootState) => state.statuses,
], (statusIds, statuses) => ], (statusIds, statuses) =>
statusIds.reduce((medias: Array<AccountGalleryAttachment>, statusId: string) => { statusIds.reduce((medias: Array<AccountGalleryAttachment>, statusId: string) => {
@ -223,7 +223,7 @@ const getAccountGallery = createSelector([
); );
const getGroupGallery = createSelector([ const getGroupGallery = createSelector([
(state: RootState, id: string) => state.timelines.get(`group:${id}:media`)?.items || ImmutableOrderedSet<string>(), (state: RootState, id: string) => state.timelines[`group:${id}:media`]?.items || [],
(state: RootState) => state.statuses, (state: RootState) => state.statuses,
], (statusIds, statuses) => ], (statusIds, statuses) =>
statusIds.reduce((medias: Array<AccountGalleryAttachment>, statusId: string) => { statusIds.reduce((medias: Array<AccountGalleryAttachment>, statusId: string) => {
@ -340,14 +340,14 @@ type ColumnQuery = { type: string; prefix?: string };
const makeGetStatusIds = () => createSelector([ const makeGetStatusIds = () => createSelector([
(state: RootState, { type, prefix }: ColumnQuery) => useSettingsStore.getState().settings.timelines[prefix || type], (state: RootState, { type, prefix }: ColumnQuery) => useSettingsStore.getState().settings.timelines[prefix || type],
(state: RootState, { type }: ColumnQuery) => state.timelines.get(type)?.items || ImmutableOrderedSet(), (state: RootState, { type }: ColumnQuery) => state.timelines[type]?.items || [],
(state: RootState) => state.statuses, (state: RootState) => state.statuses,
], (columnSettings: any, statusIds: ImmutableOrderedSet<string>, statuses) => ], (columnSettings: any, statusIds: Array<string>, statuses) =>
statusIds.filter((id: string) => { statusIds.filter((id: string) => {
const status = statuses[id]; const status = statuses[id];
if (!status) return true; if (!status) return true;
return !shouldFilter(status, columnSettings); return !shouldFilter(status, columnSettings);
}).toArray(), }),
); );
export { export {