2024-01-08 10:57:40 +00:00
|
|
|
import type { Reducer } from '@reduxjs/toolkit';
|
2023-11-03 15:00:03 +00:00
|
|
|
import { Map as ImmutableMap } from 'immutable';
|
|
|
|
|
|
|
|
import {
|
|
|
|
followAccountSuccess,
|
|
|
|
unfollowAccountSuccess,
|
|
|
|
importAccounts,
|
|
|
|
revealAccount,
|
|
|
|
} from 'mastodon/actions/accounts_typed';
|
|
|
|
import type { ApiAccountJSON } from 'mastodon/api_types/accounts';
|
|
|
|
import { me } from 'mastodon/initial_state';
|
|
|
|
import type { Account } from 'mastodon/models/account';
|
|
|
|
import { createAccountFromServerJSON } from 'mastodon/models/account';
|
|
|
|
|
|
|
|
const initialState = ImmutableMap<string, Account>();
|
|
|
|
|
|
|
|
const normalizeAccount = (
|
|
|
|
state: typeof initialState,
|
|
|
|
account: ApiAccountJSON,
|
|
|
|
) => {
|
|
|
|
return state.set(
|
|
|
|
account.id,
|
|
|
|
createAccountFromServerJSON(account).set(
|
|
|
|
'hidden',
|
|
|
|
state.get(account.id)?.hidden === false
|
|
|
|
? false
|
|
|
|
: account.limited || false,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
const normalizeAccounts = (
|
|
|
|
state: typeof initialState,
|
|
|
|
accounts: ApiAccountJSON[],
|
|
|
|
) => {
|
|
|
|
accounts.forEach((account) => {
|
|
|
|
state = normalizeAccount(state, account);
|
|
|
|
});
|
|
|
|
|
|
|
|
return state;
|
|
|
|
};
|
|
|
|
|
2023-11-04 21:52:56 +00:00
|
|
|
function getCurrentUser() {
|
|
|
|
if (!me)
|
2023-11-03 15:00:03 +00:00
|
|
|
throw new Error(
|
|
|
|
'No current user (me) defined when calling `accountsReducer`',
|
|
|
|
);
|
|
|
|
|
2023-11-04 21:52:56 +00:00
|
|
|
return me;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const accountsReducer: Reducer<typeof initialState> = (
|
|
|
|
state = initialState,
|
|
|
|
action,
|
|
|
|
) => {
|
2023-11-03 15:00:03 +00:00
|
|
|
if (revealAccount.match(action))
|
|
|
|
return state.setIn([action.payload.id, 'hidden'], false);
|
|
|
|
else if (importAccounts.match(action))
|
|
|
|
return normalizeAccounts(state, action.payload.accounts);
|
2023-11-04 21:52:56 +00:00
|
|
|
else if (followAccountSuccess.match(action)) {
|
2023-11-03 15:00:03 +00:00
|
|
|
return state
|
|
|
|
.update(
|
|
|
|
action.payload.relationship.id,
|
|
|
|
(account) => account?.update('followers_count', (n) => n + 1),
|
|
|
|
)
|
|
|
|
.update(
|
2023-11-04 21:52:56 +00:00
|
|
|
getCurrentUser(),
|
2023-11-03 15:00:03 +00:00
|
|
|
(account) => account?.update('following_count', (n) => n + 1),
|
|
|
|
);
|
2023-11-04 21:52:56 +00:00
|
|
|
} else if (unfollowAccountSuccess.match(action))
|
2023-11-03 15:00:03 +00:00
|
|
|
return state
|
|
|
|
.update(
|
|
|
|
action.payload.relationship.id,
|
|
|
|
(account) =>
|
|
|
|
account?.update('followers_count', (n) => Math.max(0, n - 1)),
|
|
|
|
)
|
|
|
|
.update(
|
2023-11-04 21:52:56 +00:00
|
|
|
getCurrentUser(),
|
2023-11-03 15:00:03 +00:00
|
|
|
(account) =>
|
|
|
|
account?.update('following_count', (n) => Math.max(0, n - 1)),
|
|
|
|
);
|
|
|
|
else return state;
|
|
|
|
};
|