Dashboard: hooks cleanup

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
This commit is contained in:
marcin mikołajczak 2024-04-07 12:03:10 +02:00
parent 9375f1f117
commit 890975fe93
11 changed files with 142 additions and 88 deletions

View file

@ -1,11 +1,6 @@
export { useCreateDomain, type CreateDomainParams } from './useCreateDomain';
export { useCreateRelay } from './useCreateRelay';
export { useDeleteDomain } from './useDeleteDomain';
export { useDeleteRelay } from './useDeleteRelay';
export { useDomains } from './useDomains'; export { useDomains } from './useDomains';
export { useModerationLog } from './useModerationLog'; export { useModerationLog } from './useModerationLog';
export { useRelays } from './useRelays'; export { useRelays } from './useRelays';
export { useRules } from './useRules'; export { useRules } from './useRules';
export { useSuggest } from './useSuggest'; export { useSuggest } from './useSuggest';
export { useUpdateDomain } from './useUpdateDomain';
export { useVerify } from './useVerify'; export { useVerify } from './useVerify';

View file

@ -1,18 +0,0 @@
import { Entities } from 'soapbox/entity-store/entities';
import { useCreateEntity } from 'soapbox/entity-store/hooks';
import { useApi } from 'soapbox/hooks';
import { relaySchema } from 'soapbox/schemas';
const useCreateRelay = () => {
const api = useApi();
const { createEntity, ...rest } = useCreateEntity([Entities.RELAYS], (relayUrl: string) =>
api.post('/api/v1/pleroma/admin/relay', { relay_url: relayUrl }), { schema: relaySchema });
return {
createRelay: createEntity,
...rest,
};
};
export { useCreateRelay };

View file

@ -1,19 +0,0 @@
import { Entities } from 'soapbox/entity-store/entities';
import { useDeleteEntity } from 'soapbox/entity-store/hooks';
import { useApi } from 'soapbox/hooks';
const useDeleteRelay = () => {
const api = useApi();
const { deleteEntity, ...rest } = useDeleteEntity(Entities.RELAYS, (relayUrl: string) =>
api.delete('/api/v1/pleroma/admin/relay', {
data: { relay_url: relayUrl },
}));
return {
mutate: deleteEntity,
...rest,
};
};
export { useDeleteRelay };

View file

@ -1,8 +1,21 @@
import { useQuery } from '@tanstack/react-query'; import { useMutation, useQuery } from '@tanstack/react-query';
import { useApi } from 'soapbox/hooks'; import { useApi } from 'soapbox/hooks';
import { queryClient } from 'soapbox/queries/client';
import { domainSchema, type Domain } from 'soapbox/schemas'; import { domainSchema, type Domain } from 'soapbox/schemas';
import type { AxiosResponse } from 'axios';
interface CreateDomainParams {
domain: string;
public: boolean;
}
interface UpdateDomainParams {
id: string;
public: boolean;
}
const useDomains = () => { const useDomains = () => {
const api = useApi(); const api = useApi();
@ -14,12 +27,56 @@ const useDomains = () => {
}; };
const result = useQuery<ReadonlyArray<Domain>>({ const result = useQuery<ReadonlyArray<Domain>>({
queryKey: ['domains'], queryKey: ['admin', 'domains'],
queryFn: getDomains, queryFn: getDomains,
placeholderData: [], placeholderData: [],
}); });
return result; const {
mutate: createDomain,
isPending: isCreating,
} = useMutation({
mutationFn: (params: CreateDomainParams) => api.post('/api/v1/pleroma/admin/domains', params),
retry: false,
onSuccess: ({ data }: AxiosResponse) =>
queryClient.setQueryData(['admin', 'domains'], (prevResult: ReadonlyArray<Domain>) =>
[...prevResult, domainSchema.parse(data)],
),
});
const {
mutate: updateDomain,
isPending: isUpdating,
} = useMutation({
mutationFn: ({ id, ...params }: UpdateDomainParams) => api.patch(`/api/v1/pleroma/admin/domains/${id}`, params),
retry: false,
onSuccess: ({ data }: AxiosResponse) =>
queryClient.setQueryData(['admin', 'domains'], (prevResult: ReadonlyArray<Domain>) =>
prevResult.map((domain) => domain.id === data.id ? domainSchema.parse(data) : domain),
),
});
const {
mutate: deleteDomain,
isPending: isDeleting,
} = useMutation({
mutationFn: (id: string) => api.delete(`/api/v1/pleroma/admin/domains/${id}`),
retry: false,
onSuccess: (_, id) =>
queryClient.setQueryData(['admin', 'domains'], (prevResult: ReadonlyArray<Domain>) =>
prevResult.filter(({ id: domainId }) => domainId !== id),
),
});
return {
...result,
createDomain,
isCreating,
updateDomain,
isUpdating,
deleteDomain,
isDeleting,
};
}; };
export { useDomains }; export { useDomains };

View file

@ -25,7 +25,7 @@ const useModerationLog = () => {
}; };
const queryInfo = useInfiniteQuery({ const queryInfo = useInfiniteQuery({
queryKey: ['moderation_log'], queryKey: ['admin', 'moderation_log'],
queryFn: ({ pageParam }) => getModerationLog(pageParam), queryFn: ({ pageParam }) => getModerationLog(pageParam),
initialPageParam: 1, initialPageParam: 1,
getNextPageParam: (page, allPages) => flattenPages(allPages)!.length >= page.total ? undefined : allPages.length + 1, getNextPageParam: (page, allPages) => flattenPages(allPages)!.length >= page.total ? undefined : allPages.length + 1,

View file

@ -1,8 +1,11 @@
import { useQuery } from '@tanstack/react-query'; import { useMutation, useQuery } from '@tanstack/react-query';
import { useApi } from 'soapbox/hooks'; import { useApi } from 'soapbox/hooks';
import { queryClient } from 'soapbox/queries/client';
import { relaySchema, type Relay } from 'soapbox/schemas'; import { relaySchema, type Relay } from 'soapbox/schemas';
import type { AxiosResponse } from 'axios';
const useRelays = () => { const useRelays = () => {
const api = useApi(); const api = useApi();
@ -14,12 +17,44 @@ const useRelays = () => {
}; };
const result = useQuery<ReadonlyArray<Relay>>({ const result = useQuery<ReadonlyArray<Relay>>({
queryKey: ['relays'], queryKey: ['admin', 'relays'],
queryFn: getRelays, queryFn: getRelays,
placeholderData: [], placeholderData: [],
}); });
return result; const {
mutate: followRelay,
isPending: isPendingFollow,
} = useMutation({
mutationFn: (relayUrl: string) => api.post('/api/v1/pleroma/admin/relays', { relay_url: relayUrl }),
retry: false,
onSuccess: ({ data }: AxiosResponse) =>
queryClient.setQueryData(['admin', 'relays'], (prevResult: ReadonlyArray<Relay>) =>
[...prevResult, relaySchema.parse(data)],
),
});
const {
mutate: unfollowRelay,
isPending: isPendingUnfollow,
} = useMutation({
mutationFn: (relayUrl: string) => api.delete('/api/v1/pleroma/admin/relays', {
data: { relay_url: relayUrl },
}),
retry: false,
onSuccess: (_, relayUrl) =>
queryClient.setQueryData(['admin', 'relays'], (prevResult: ReadonlyArray<Relay>) =>
prevResult.filter(({ actor }) => actor !== relayUrl),
),
});
return {
...result,
followRelay,
isPendingFollow,
unfollowRelay,
isPendingUnfollow,
};
}; };
export { useRelays }; export { useRelays };

View file

@ -1,10 +1,11 @@
import { useMutation, useQuery } from '@tanstack/react-query'; import { useMutation, useQuery } from '@tanstack/react-query';
import { AxiosResponse } from 'axios';
import { useApi } from 'soapbox/hooks'; import { useApi } from 'soapbox/hooks';
import { queryClient } from 'soapbox/queries/client'; import { queryClient } from 'soapbox/queries/client';
import { adminRuleSchema, type AdminRule } from 'soapbox/schemas'; import { adminRuleSchema, type AdminRule } from 'soapbox/schemas';
import type { AxiosResponse } from 'axios';
interface CreateRuleParams { interface CreateRuleParams {
priority?: number; priority?: number;
text: string; text: string;

View file

@ -4,7 +4,7 @@
* @module soapbox/api * @module soapbox/api
*/ */
import axios, { AxiosInstance, AxiosResponse } from 'axios'; import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
import LinkHeader from 'http-link-header'; import LinkHeader from 'http-link-header';
import { createSelector } from 'reselect'; import { createSelector } from 'reselect';

View file

@ -1,8 +1,8 @@
import React from 'react'; import React, { useEffect } from 'react';
import { FormattedMessage, defineMessages, useIntl } from 'react-intl'; import { FormattedMessage, defineMessages, useIntl } from 'react-intl';
import { openModal } from 'soapbox/actions/modals'; import { openModal } from 'soapbox/actions/modals';
import { useDeleteDomain, useDomains } from 'soapbox/api/hooks/admin'; import { useDomains } from 'soapbox/api/hooks/admin';
import { dateFormatOptions } from 'soapbox/components/relative-timestamp'; import { dateFormatOptions } from 'soapbox/components/relative-timestamp';
import ScrollableList from 'soapbox/components/scrollable-list'; import ScrollableList from 'soapbox/components/scrollable-list';
import { Button, Column, HStack, Stack, Text } from 'soapbox/components/ui'; import { Button, Column, HStack, Stack, Text } from 'soapbox/components/ui';
@ -30,8 +30,7 @@ const Domain: React.FC<IDomain> = ({ domain }) => {
const intl = useIntl(); const intl = useIntl();
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const { mutate: deleteDomain } = useDeleteDomain(); const { deleteDomain } = useDomains();
const { refetch } = useDomains();
const handleEditDomain = (domain: DomainEntity) => () => { const handleEditDomain = (domain: DomainEntity) => () => {
dispatch(openModal('EDIT_DOMAIN', { domainId: domain.id })); dispatch(openModal('EDIT_DOMAIN', { domainId: domain.id }));
@ -43,10 +42,11 @@ const Domain: React.FC<IDomain> = ({ domain }) => {
message: intl.formatMessage(messages.deleteMessage), message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm), confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => { onConfirm: () => {
deleteDomain(domain.id).then(() => { deleteDomain(domain.id, {
onSuccess: () => {
toast.success(messages.domainDeleteSuccess); toast.success(messages.domainDeleteSuccess);
refetch(); },
}).catch(() => {}); });
}, },
})); }));
}; };
@ -103,12 +103,16 @@ const Domains: React.FC = () => {
const intl = useIntl(); const intl = useIntl();
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const { data: domains, isFetching } = useDomains(); const { data: domains, isFetching, refetch } = useDomains();
const handleCreateDomain = () => { const handleCreateDomain = () => {
dispatch(openModal('EDIT_DOMAIN')); dispatch(openModal('EDIT_DOMAIN'));
}; };
useEffect(() => {
if (!isFetching) refetch();
}, []);
const emptyMessage = <FormattedMessage id='empty_column.admin.domains' defaultMessage='There are no domains yet.' />; const emptyMessage = <FormattedMessage id='empty_column.admin.domains' defaultMessage='There are no domains yet.' />;
return ( return (

View file

@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { FormattedMessage, defineMessages, useIntl } from 'react-intl'; import { FormattedMessage, defineMessages, useIntl } from 'react-intl';
import { useCreateRelay, useDeleteRelay, useRelays } from 'soapbox/api/hooks/admin'; import { useRelays } from 'soapbox/api/hooks/admin';
import ScrollableList from 'soapbox/components/scrollable-list'; import ScrollableList from 'soapbox/components/scrollable-list';
import { Button, Column, Form, HStack, Input, Stack, Text } from 'soapbox/components/ui'; import { Button, Column, Form, HStack, Input, Stack, Text } from 'soapbox/components/ui';
import { useTextField } from 'soapbox/hooks/forms'; import { useTextField } from 'soapbox/hooks/forms';
@ -22,14 +22,14 @@ interface IRelay {
} }
const Relay: React.FC<IRelay> = ({ relay }) => { const Relay: React.FC<IRelay> = ({ relay }) => {
const { mutate: deleteRelay } = useDeleteRelay(); const { unfollowRelay } = useRelays();
const { refetch } = useRelays();
const handleDeleteRelay = () => () => { const handleDeleteRelay = () => () => {
deleteRelay(relay.actor).then(() => { unfollowRelay(relay.actor, {
refetch(); onSuccess: () => {
toast.success(messages.relayDeleteSuccess); toast.success(messages.relayDeleteSuccess);
}).catch(() => {}); },
});
}; };
return ( return (
@ -64,18 +64,16 @@ const NewRelayForm: React.FC = () => {
const name = useTextField(); const name = useTextField();
const { createRelay, isSubmitting } = useCreateRelay(); const { followRelay, isPendingFollow } = useRelays();
const { refetch } = useRelays();
const handleSubmit = (e: React.FormEvent<Element>) => { const handleSubmit = (e: React.FormEvent<Element>) => {
e.preventDefault(); e.preventDefault();
createRelay(name.value, { followRelay(name.value, {
onSuccess() { onSuccess() {
toast.success(messages.createSuccess); toast.success(messages.createSuccess);
refetch();
}, },
onError() { onError() {
toast.success(messages.createFail); toast.error(messages.createFail);
}, },
}); });
}; };
@ -91,13 +89,13 @@ const NewRelayForm: React.FC = () => {
<Input <Input
type='text' type='text'
placeholder={label} placeholder={label}
disabled={isSubmitting} disabled={isPendingFollow}
{...name} {...name}
/> />
</label> </label>
<Button <Button
disabled={isSubmitting} disabled={isPendingFollow}
onClick={handleSubmit} onClick={handleSubmit}
theme='primary' theme='primary'
> >

View file

@ -2,7 +2,7 @@ import React, { useState } from 'react';
import { FormattedMessage, defineMessages, useIntl } from 'react-intl'; import { FormattedMessage, defineMessages, useIntl } from 'react-intl';
import { closeModal } from 'soapbox/actions/modals'; import { closeModal } from 'soapbox/actions/modals';
import { useCreateDomain, useDomains, useUpdateDomain } from 'soapbox/api/hooks/admin'; import { useDomains } from 'soapbox/api/hooks/admin';
import { Form, FormGroup, HStack, Input, Modal, Stack, Text, Toggle } from 'soapbox/components/ui'; import { Form, FormGroup, HStack, Input, Modal, Stack, Text, Toggle } from 'soapbox/components/ui';
import { useAppDispatch } from 'soapbox/hooks'; import { useAppDispatch } from 'soapbox/hooks';
import { Domain } from 'soapbox/schemas'; import { Domain } from 'soapbox/schemas';
@ -24,9 +24,7 @@ const EditDomainModal: React.FC<IEditDomainModal> = ({ onClose, domainId }) => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const intl = useIntl(); const intl = useIntl();
const { data: domains, refetch } = useDomains(); const { data: domains, createDomain, isCreating, updateDomain, isUpdating } = useDomains();
const { createDomain, isSubmitting: isCreating } = useCreateDomain();
const { updateDomain, isSubmitting: isUpdating } = useUpdateDomain(domainId!);
const [domain] = useState<Domain | null>(domainId ? domains!.find(({ id }) => domainId === id)! : null); const [domain] = useState<Domain | null>(domainId ? domains!.find(({ id }) => domainId === id)! : null);
const [domainName, setDomainName] = useState(domain?.domain || ''); const [domainName, setDomainName] = useState(domain?.domain || '');
@ -39,21 +37,24 @@ const EditDomainModal: React.FC<IEditDomainModal> = ({ onClose, domainId }) => {
const handleSubmit = () => { const handleSubmit = () => {
if (domainId) { if (domainId) {
updateDomain({ updateDomain({
id: domainId,
public: isPublic, public: isPublic,
}).then(() => { }, {
onSuccess: () => {
toast.success(messages.domainUpdateSuccess); toast.success(messages.domainUpdateSuccess);
dispatch(closeModal('EDIT_DOMAIN')); dispatch(closeModal('EDIT_DOMAIN'));
refetch(); },
}).catch(() => {}); });
} else { } else {
createDomain({ createDomain({
domain: domainName, domain: domainName,
public: isPublic, public: isPublic,
}).then(() => { }, {
onSuccess: () => {
toast.success(messages.domainCreateSuccess); toast.success(messages.domainCreateSuccess);
dispatch(closeModal('EDIT_DOMAIN')); dispatch(closeModal('EDIT_DOMAIN'));
refetch(); },
}).catch(() => {}); });
} }
}; };