Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes 3257: Create content item delete modal #184

Merged
merged 3 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 18 additions & 20 deletions src/Pages/ContentListTable/ContentListTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import { SkeletonTable } from '@patternfly/react-component-groups';
import {
useBulkDeleteContentItemMutate,
useContentListQuery,
useDeleteContentItemMutate,
useIntrospectRepositoryMutate,
useRepositoryParams,
} from '../../services/Content/ContentQueries';
Expand Down Expand Up @@ -161,14 +160,6 @@ const ContentListTable = () => {
data = { data: [], meta: { count: 0, limit: 20, offset: 0 } },
} = useContentListQuery(page, perPage, filterData, sortString(), contentOrigin);

const { mutateAsync: deleteItem, isLoading: isDeleting } = useDeleteContentItemMutate(
queryClient,
page,
perPage,
filterData,
sortString(),
);

const { mutateAsync: introspectRepository, isLoading: isIntrospecting } =
useIntrospectRepositoryMutate(queryClient, page, perPage, filterData, sortString());

Expand All @@ -186,7 +177,7 @@ const ContentListTable = () => {

// Other update actions will be added to this later.
const actionTakingPlace =
isDeleting || isFetching || repositoryParamsLoading || isIntrospecting || isDeletingItems;
isFetching || repositoryParamsLoading || isIntrospecting || isDeletingItems;

const onSetPage = (_, newPage) => setPage(newPage);

Expand Down Expand Up @@ -292,14 +283,7 @@ const ContentListTable = () => {
{ isSeparator: true },
{
title: 'Delete',
onClick: () =>
deleteItem(rowData?.uuid).then(() => {
clearCheckedRepositories();
// If this is the last item on a page, go to previous page.
if (page > 1 && count / perPage + 1 >= page && (count - 1) % perPage === 0) {
setPage(page - 1);
}
}),
onClick: () => navigate(`delete-repository?repoUUIDS=${rowData.uuid}`),
},
],
[actionTakingPlace, checkedRepositories, isRedHatRepository],
Expand Down Expand Up @@ -378,7 +362,12 @@ const ContentListTable = () => {

return (
<>
<Outlet context={{ clearCheckedRepositories }} />
<Outlet
context={{
clearCheckedRepositories,
deletionContext: { page, perPage, filterData, contentOrigin, sortString: sortString() },
}}
/>
<Grid
data-ouia-safe={!actionTakingPlace}
data-ouia-component-id='content_list_page'
Expand Down Expand Up @@ -614,6 +603,15 @@ const ContentListTable = () => {
};

export const useContentListOutletContext = () =>
useOutletContext<{ clearCheckedRepositories: () => void }>();
useOutletContext<{
clearCheckedRepositories: () => void;
deletionContext: {
page: number;
perPage: number;
filterData: FilterData;
contentOrigin: ContentOrigin;
sortString: string;
};
}>();

export default ContentListTable;
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { render } from '@testing-library/react';
import { ReactQueryTestWrapper, defaultContentItem } from '../../../../testingHelpers';
import { useFetchContent } from '../../../../services/Content/ContentQueries';
import DeleteContentModal from './DeleteContentModal';
import { ContentOrigin } from '../../../../services/Content/ContentApi';

jest.mock('react-query', () => ({
...jest.requireActual('react-query'),
useQueryClient: jest.fn(),
}));

jest.mock('react-router-dom', () => ({
useNavigate: jest.fn(),
useLocation: () => ({
search: `delete-repository?${defaultContentItem.uuid}`,
}),
}));

jest.mock('../../ContentListTable', () => ({
useContentListOutletContext: () => ({
clearCheckedRepositories: () => undefined,
deletionContext: {
page: 1,
perPage: 21,
filterData: undefined,
contentOrigin: ContentOrigin.EXTERNAL,
sortString: '',
},
}),
}));

jest.mock('../../../../Hooks/useRootPath', () => () => 'someUrl');

jest.mock('../../../../services/Content/ContentQueries', () => ({
useDeleteContentItemMutate: () => ({ mutate: () => undefined, isLoading: false }),
useFetchContent: jest.fn(),
}));

jest.mock('../../../../middleware/AppContext', () => ({ useAppContext: () => ({}) }));

it('Render Delete Modal', () => {
const data = defaultContentItem;
(useFetchContent as jest.Mock).mockImplementation(() => ({
isLoading: false,
data: data,
}));

const { queryByText } = render(
<ReactQueryTestWrapper>
<DeleteContentModal />
</ReactQueryTestWrapper>,
);

expect(queryByText(defaultContentItem.name)).toBeInTheDocument();
expect(queryByText(defaultContentItem.url)).toBeInTheDocument();
expect(queryByText(defaultContentItem.distribution_arch)).toBeInTheDocument();
expect(queryByText(defaultContentItem.distribution_versions[0])).toBeInTheDocument();
expect(queryByText('None')).not.toBeInTheDocument();
});

it('Render Delete Modal with no gpg key', () => {
const data = defaultContentItem;
data.gpg_key = '';
(useFetchContent as jest.Mock).mockImplementation(() => ({
isLoading: false,
data: data,
}));

const { queryByText } = render(
<ReactQueryTestWrapper>
<DeleteContentModal />
</ReactQueryTestWrapper>,
);

expect(queryByText(defaultContentItem.name)).toBeInTheDocument();
expect(queryByText(defaultContentItem.url)).toBeInTheDocument();
expect(queryByText(defaultContentItem.distribution_arch)).toBeInTheDocument();
expect(queryByText(defaultContentItem.distribution_versions[0])).toBeInTheDocument();
expect(queryByText('None')).toBeInTheDocument();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import {
Bullseye,
Button,
Grid,
GridItem,
Modal,
ModalVariant,
Spinner,
Stack,
StackItem,
Text,
TextArea,
Title,
} from '@patternfly/react-core';

import { global_Color_100 } from '@patternfly/react-tokens';
import { useEffect, useState } from 'react';
import { createUseStyles } from 'react-jss';
import Hide from '../../../../components/Hide/Hide';
import {
CONTENT_ITEM_KEY,
useFetchContent,
useDeleteContentItemMutate,
} from '../../../../services/Content/ContentQueries';
import { useQueryClient } from 'react-query';
import { useLocation, useNavigate } from 'react-router-dom';
import { useContentListOutletContext } from '../../ContentListTable';
import useRootPath from '../../../../Hooks/useRootPath';

const useStyles = createUseStyles({
description: {
paddingTop: '12px', // 4px on the title bottom padding makes this the "standard" 16 total padding
color: global_Color_100.value,
},
removeButton: {
marginRight: '36px',
transition: 'unset!important',
},
textAreaContent: {
marginTop: '8px',
color: global_Color_100.value,
height: '200px',
},
});

export default function DeleteContentModal() {
const classes = useStyles();
const navigate = useNavigate();
const rootPath = useRootPath();
const queryClient = useQueryClient();
const { search } = useLocation();
const [isLoading, setIsLoading] = useState(true);
const {
clearCheckedRepositories,
deletionContext: { page, perPage, filterData, contentOrigin, sortString },
} = useContentListOutletContext();

const uuids = new URLSearchParams(search).get('repoUUIDS')?.split(',') || [];

const { mutate: deleteItem, isLoading: isDeleting } = useDeleteContentItemMutate(
queryClient,
page,
perPage,
filterData,
contentOrigin,
sortString,
);

const onClose = () => navigate(rootPath);
const onSave = async () => {
deleteItem(data?.uuid || '');
onClose();
clearCheckedRepositories();
queryClient.invalidateQueries(CONTENT_ITEM_KEY);
};

const { data, isError } = useFetchContent(uuids);
const values = data ? [data] : [];

useEffect(() => {
if (data) {
setIsLoading(false);
}
if (isError) {
onClose();
}
}, [values, isError]);

const actionTakingPlace = isDeleting || isLoading;

return (
<Modal
titleIconVariant='warning'
position='top'
variant={ModalVariant.small}
title='Remove repository?'
ouiaId='delete_custom_repository'
ouiaSafe={!actionTakingPlace}
description={
<Text component='p' className={classes.description}>
Are you sure you want to remove this repository?
</Text>
}
isOpen
onClose={onClose}
footer={
<Stack>
<StackItem>
<Button
// className={classes.removeButton}
key='confirm'
ouiaId='delete_modal_confirm'
variant='danger'
isLoading={actionTakingPlace}
isDisabled={actionTakingPlace}
onClick={onSave}
>
Remove
</Button>
<Button key='cancel' variant='link' onClick={onClose} ouiaId='edit_modal_cancel'>
Cancel
</Button>
</StackItem>
</Stack>
}
>
<Hide hide={!isLoading}>
<Bullseye>
<Spinner />
</Bullseye>
</Hide>
<Hide hide={isLoading}>
<Grid hasGutter>
<GridItem>
<Title headingLevel='h6'>Name</Title>
<Text className='pf-v5-u-color-100'>{data?.name}</Text>
</GridItem>
<GridItem>
<Title headingLevel='h6'>URL</Title>
<Text className='pf-v5-u-color-100'>{data?.url}</Text>
</GridItem>
<GridItem>
<Title headingLevel='h6'>Archicture</Title>
<Text className='pf-v5-u-color-100'>{data?.distribution_arch ?? 'Any'}</Text>
</GridItem>
<GridItem>
<Title headingLevel='h6'>Versions</Title>
<Text className='pf-v5-u-color-100'>{data?.distribution_versions ?? 'Any'}</Text>
</GridItem>
<GridItem>
<Title headingLevel='h6'>GPG Key</Title>
{!data?.gpg_key ? (
<Text className='pf-v5-u-color-100'>None</Text>
) : (
<TextArea
aria-label='GPG Key Text'
className={classes.textAreaContent}
value={data.gpg_key}
/>
)}
</GridItem>
</Grid>
</Hide>
</Modal>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,13 @@ export default function SnapshotListModal() {
<Tbody>
{snapshotsList.map(
(
{ uuid: snap_uuid, created_at, content_counts, added_counts, removed_counts }: SnapshotItem,
{
uuid: snap_uuid,
created_at,
content_counts,
added_counts,
removed_counts,
}: SnapshotItem,
index: number,
) => (
<Tr key={created_at + index}>
Expand All @@ -248,8 +254,8 @@ export default function SnapshotListModal() {
<Td>{content_counts?.['rpm.package'] || 0}</Td>
<Td>{content_counts?.['rpm.advisory'] || 0}</Td>
<Td>
<RepoConfig repoUUID={uuid} snapUUID={snap_uuid}/>
</Td>
<RepoConfig repoUUID={uuid} snapUUID={snap_uuid} />
</Td>
</Tr>
),
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const RepoConfig = ({ repoUUID, snapUUID }: Props) => {
const downloadConfigFile = async () => {
const data = await mutateAsync();
const element = document.createElement('a');
const file = new Blob([data], {type: 'text/plain'});
const file = new Blob([data], { type: 'text/plain' });
element.href = URL.createObjectURL(file);
element.download = 'config.repo';
document.body.appendChild(element);
Expand Down
2 changes: 2 additions & 0 deletions src/Routes/useTabbedRoutes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import ViewPayloadModal from '../Pages/AdminTaskTable/components/ViewPayloadModa
import ContentListTable from '../Pages/ContentListTable/ContentListTable';
import AddContent from '../Pages/ContentListTable/components/AddContent/AddContent';
import EditContentModal from '../Pages/ContentListTable/components/EditContentModal/EditContentModal';
import DeleteContentModal from '../Pages/ContentListTable/components/DeleteContentModal/DeleteContentModal';
import PackageModal from '../Pages/ContentListTable/components/PackageModal/PackageModal';
import PopularRepositoriesTable from '../Pages/PopularRepositoriesTable/PopularRepositoriesTable';
import { useAppContext } from '../middleware/AppContext';
Expand Down Expand Up @@ -36,6 +37,7 @@ export default function useTabbedRoutes(): TabbedRoute[] {
? [
{ path: 'edit-repository', Element: EditContentModal },
{ path: 'add-repository', Element: AddContent },
{ path: 'delete-repository', Element: DeleteContentModal },
]
: []),
...(features?.admintasks?.enabled && features.snapshots?.accessible
Expand Down
10 changes: 5 additions & 5 deletions src/services/Content/ContentApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,11 +331,11 @@ export const introspectRepository: (
};

export const getRepoConfigFile: (
repo_uuid: string,
snapshot_uuid: string,
repo_uuid: string,
snapshot_uuid: string,
) => Promise<string> = async (repo_uuid, snapshot_uuid) => {
const { data } = await axios.get(
`/api/content-sources/v1/repositories/${repo_uuid}/snapshots/${snapshot_uuid}/config.repo`
const { data } = await axios.get(
`/api/content-sources/v1/repositories/${repo_uuid}/snapshots/${snapshot_uuid}/config.repo`,
);
return data;
}
};
Loading
Loading