2023-06-22 21:17:40 -07:00
|
|
|
import { Entities } from 'soapbox/entity-store/entities';
|
|
|
|
import { useChangeEntity } from 'soapbox/entity-store/hooks';
|
2023-06-22 21:38:50 -07:00
|
|
|
import { useLoggedIn } from 'soapbox/hooks';
|
2023-06-22 21:17:40 -07:00
|
|
|
import { useApi } from 'soapbox/hooks/useApi';
|
|
|
|
import { type Account } from 'soapbox/schemas';
|
|
|
|
|
|
|
|
function useChangeAccount() {
|
|
|
|
const { changeEntity: changeAccount } = useChangeEntity<Account>(Entities.ACCOUNTS);
|
|
|
|
return { changeAccount };
|
|
|
|
}
|
|
|
|
|
2023-06-22 21:38:50 -07:00
|
|
|
interface FollowOpts {
|
|
|
|
reblogs?: boolean
|
|
|
|
notify?: boolean
|
|
|
|
languages?: string[]
|
|
|
|
}
|
|
|
|
|
2023-06-22 21:17:40 -07:00
|
|
|
function useFollow() {
|
|
|
|
const api = useApi();
|
2023-06-22 21:38:50 -07:00
|
|
|
const { isLoggedIn } = useLoggedIn();
|
2023-06-22 21:17:40 -07:00
|
|
|
const { changeAccount } = useChangeAccount();
|
|
|
|
|
|
|
|
function incrementFollowers(accountId: string) {
|
|
|
|
changeAccount(accountId, (account) => ({
|
|
|
|
...account,
|
|
|
|
followers_count: account.followers_count + 1,
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
function decrementFollowers(accountId: string) {
|
|
|
|
changeAccount(accountId, (account) => ({
|
|
|
|
...account,
|
2023-06-22 21:47:46 -07:00
|
|
|
followers_count: Math.max(0, account.followers_count - 1),
|
2023-06-22 21:17:40 -07:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2023-06-22 21:38:50 -07:00
|
|
|
async function follow(accountId: string, options: FollowOpts = {}) {
|
|
|
|
if (!isLoggedIn) return;
|
2023-06-22 21:17:40 -07:00
|
|
|
incrementFollowers(accountId);
|
|
|
|
|
|
|
|
try {
|
|
|
|
await api.post(`/api/v1/accounts/${accountId}/follow`, options);
|
|
|
|
} catch (e) {
|
|
|
|
decrementFollowers(accountId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-22 21:38:50 -07:00
|
|
|
async function unfollow(accountId: string) {
|
|
|
|
if (!isLoggedIn) return;
|
2023-06-22 21:17:40 -07:00
|
|
|
decrementFollowers(accountId);
|
|
|
|
|
|
|
|
try {
|
2023-06-22 21:38:50 -07:00
|
|
|
await api.post(`/api/v1/accounts/${accountId}/unfollow`);
|
2023-06-22 21:17:40 -07:00
|
|
|
} catch (e) {
|
|
|
|
incrementFollowers(accountId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
follow,
|
|
|
|
unfollow,
|
|
|
|
incrementFollowers,
|
|
|
|
decrementFollowers,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export { useFollow };
|