Convert lists to tables

- ProjectJobTemplatesList
- UserTokenList
This commit is contained in:
Keith J. Grant
2021-06-14 11:35:38 -07:00
committed by Shane McDonald
parent 3db92ca668
commit 421d8f215c
8 changed files with 428 additions and 422 deletions

View File

@@ -7,7 +7,11 @@ import { JobTemplatesAPI } from '../../../api';
import AlertModal from '../../../components/AlertModal'; import AlertModal from '../../../components/AlertModal';
import DatalistToolbar from '../../../components/DataListToolbar'; import DatalistToolbar from '../../../components/DataListToolbar';
import ErrorDetail from '../../../components/ErrorDetail'; import ErrorDetail from '../../../components/ErrorDetail';
import PaginatedDataList, { import PaginatedTable, {
HeaderRow,
HeaderCell,
} from '../../../components/PaginatedTable';
import {
ToolbarAddButton, ToolbarAddButton,
ToolbarDeleteButton, ToolbarDeleteButton,
} from '../../../components/PaginatedDataList'; } from '../../../components/PaginatedDataList';
@@ -70,9 +74,13 @@ function ProjectJobTemplatesList() {
fetchTemplates(); fetchTemplates();
}, [fetchTemplates]); }, [fetchTemplates]);
const { selected, isAllSelected, handleSelect, setSelected } = useSelected( const {
jobTemplates selected,
); isAllSelected,
handleSelect,
clearSelected,
selectAll,
} = useSelected(jobTemplates);
const { const {
isLoading: isDeleteLoading, isLoading: isDeleteLoading,
@@ -94,7 +102,7 @@ function ProjectJobTemplatesList() {
const handleTemplateDelete = async () => { const handleTemplateDelete = async () => {
await deleteTemplates(); await deleteTemplates();
setSelected([]); clearSelected();
}; };
const canAddJT = const canAddJT =
@@ -107,14 +115,14 @@ function ProjectJobTemplatesList() {
return ( return (
<> <>
<Card> <Card>
<PaginatedDataList <PaginatedTable
contentError={contentError} contentError={contentError}
hasContentLoading={isDeleteLoading || isLoading} hasContentLoading={isDeleteLoading || isLoading}
items={jobTemplates} items={jobTemplates}
itemCount={itemCount} itemCount={itemCount}
pluralizedItemName={t`Job templates`} pluralizedItemName={t`Job templates`}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
onRowClick={handleSelect} clearSelected={clearSelected}
toolbarSearchColumns={[ toolbarSearchColumns={[
{ {
name: t`Name`, name: t`Name`,
@@ -130,32 +138,6 @@ function ProjectJobTemplatesList() {
key: 'modified_by__username__icontains', key: 'modified_by__username__icontains',
}, },
]} ]}
toolbarSortColumns={[
{
name: t`Inventory`,
key: 'job_template__inventory__id',
},
{
name: t`Last job run`,
key: 'last_job_run',
},
{
name: t`Modified`,
key: 'modified',
},
{
name: t`Name`,
key: 'name',
},
{
name: t`Project`,
key: 'jobtemplate__project__id',
},
{
name: t`Type`,
key: 'type',
},
]}
toolbarSearchableKeys={searchableKeys} toolbarSearchableKeys={searchableKeys}
toolbarRelatedSearchableKeys={relatedSearchableKeys} toolbarRelatedSearchableKeys={relatedSearchableKeys}
renderToolbar={props => ( renderToolbar={props => (
@@ -163,9 +145,7 @@ function ProjectJobTemplatesList() {
{...props} {...props}
showSelectAll showSelectAll
isAllSelected={isAllSelected} isAllSelected={isAllSelected}
onSelectAll={isSelected => onSelectAll={selectAll}
setSelected(isSelected ? [...jobTemplates] : [])
}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
additionalControls={[ additionalControls={[
...(canAddJT ? [addButton] : []), ...(canAddJT ? [addButton] : []),
@@ -178,7 +158,15 @@ function ProjectJobTemplatesList() {
]} ]}
/> />
)} )}
renderItem={template => ( headerRow={
<HeaderRow qsConfig={QS_CONFIG}>
<HeaderCell sortKey="name">{t`Name`}</HeaderCell>
<HeaderCell sortKey="type">{t`Type`}</HeaderCell>
<HeaderCell>{t`Recent jobs`}</HeaderCell>
<HeaderCell>{t`Actions`}</HeaderCell>
</HeaderRow>
}
renderRow={(template, index) => (
<ProjectTemplatesListItem <ProjectTemplatesListItem
key={template.id} key={template.id}
value={template.name} value={template.name}
@@ -186,6 +174,7 @@ function ProjectJobTemplatesList() {
detailUrl={`/templates/${template.type}/${template.id}/details`} detailUrl={`/templates/${template.type}/${template.id}/details`}
onSelect={() => handleSelect(template)} onSelect={() => handleSelect(template)}
isSelected={selected.some(row => row.id === template.id)} isSelected={selected.some(row => row.id === template.id)}
rowIndex={index}
/> />
)} )}
emptyStateControls={canAddJT && addButton} emptyStateControls={canAddJT && addButton}

View File

@@ -1,36 +1,21 @@
import 'styled-components/macro'; import 'styled-components/macro';
import React from 'react'; import React from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { import { Button, Tooltip } from '@patternfly/react-core';
Button, import { Tr, Td } from '@patternfly/react-table';
DataListAction as _DataListAction,
DataListCheck,
DataListItem,
DataListItemRow,
DataListItemCells,
Tooltip,
} from '@patternfly/react-core';
import { t } from '@lingui/macro';
import { import {
ExclamationTriangleIcon, ExclamationTriangleIcon,
PencilAltIcon, PencilAltIcon,
RocketIcon, RocketIcon,
} from '@patternfly/react-icons'; } from '@patternfly/react-icons';
import { t } from '@lingui/macro';
import styled from 'styled-components'; import styled from 'styled-components';
import DataListCell from '../../../components/DataListCell';
import { ActionsTd, ActionItem } from '../../../components/PaginatedTable';
import { LaunchButton } from '../../../components/LaunchButton'; import { LaunchButton } from '../../../components/LaunchButton';
import Sparkline from '../../../components/Sparkline'; import Sparkline from '../../../components/Sparkline';
import { toTitleCase } from '../../../util/strings'; import { toTitleCase } from '../../../util/strings';
const DataListAction = styled(_DataListAction)`
align-items: center;
display: grid;
grid-gap: 16px;
grid-template-columns: repeat(2, 40px);
`;
const ExclamationTriangleIconWarning = styled(ExclamationTriangleIcon)` const ExclamationTriangleIconWarning = styled(ExclamationTriangleIcon)`
color: var(--pf-global--warning-color--100); color: var(--pf-global--warning-color--100);
margin-left: 18px; margin-left: 18px;
@@ -41,8 +26,8 @@ function ProjectJobTemplateListItem({
isSelected, isSelected,
onSelect, onSelect,
detailUrl, detailUrl,
rowIndex,
}) { }) {
const labelId = `check-action-${template.id}`;
const canLaunch = template.summary_fields.user_capabilities.start; const canLaunch = template.summary_fields.user_capabilities.start;
const missingResourceIcon = const missingResourceIcon =
@@ -57,90 +42,75 @@ function ProjectJobTemplateListItem({
!template.execution_environment; !template.execution_environment;
return ( return (
<DataListItem aria-labelledby={labelId} id={`${template.id}`}> <Tr id={`template-row-${template.id}`}>
<DataListItemRow> <Td
<DataListCheck select={{
id={`select-jobTemplate-${template.id}`} rowIndex,
checked={isSelected} isSelected,
onChange={onSelect} onSelect,
aria-labelledby={labelId} }}
/> />
<DataListItemCells <Td dataLabel={t`Name`}>
dataListCells={[ <Link to={`${detailUrl}`}>
<DataListCell key="divider"> {template.name}
<span> {missingResourceIcon && (
<Link to={`${detailUrl}`}> <Tooltip
<b>{template.name}</b> content={t`Resources are missing from this template.`}
</Link> position="right"
</span> >
{missingResourceIcon && ( <ExclamationTriangleIcon css="color: #c9190b; margin-left: 20px;" />
<span> </Tooltip>
<Tooltip )}
content={t`Resources are missing from this template.`} {missingExecutionEnvironment && (
position="right" <Tooltip
> content={t`Custom virtual environment ${template.custom_virtualenv} must be replaced by an execution environment.`}
<ExclamationTriangleIcon css="color: #c9190b; margin-left: 20px;" /> position="right"
</Tooltip> className="missing-execution-environment"
</span> >
)} <ExclamationTriangleIconWarning />
{missingExecutionEnvironment && ( </Tooltip>
<span> )}
<Tooltip </Link>
content={t`Custom virtual environment ${template.custom_virtualenv} must be replaced by an execution environment.`} </Td>
position="right" <Td dataLabel={t`Type`}>{toTitleCase(template.type)}</Td>
className="missing-execution-environment" <Td dataLabel={t`Recent jobs`}>
> <Sparkline jobs={template.summary_fields.recent_jobs} />
<ExclamationTriangleIconWarning /> </Td>
</Tooltip> <ActionsTd dataLabel={t`Actions`}>
</span> <ActionItem
)} visible={canLaunch && template.type === 'job_template'}
</DataListCell>, tooltip={t`Launch Template`}
<DataListCell key="type">
{toTitleCase(template.type)}
</DataListCell>,
<DataListCell key="sparkline">
<Sparkline jobs={template.summary_fields.recent_jobs} />
</DataListCell>,
]}
/>
<DataListAction
aria-label={t`actions`}
aria-labelledby={labelId}
id={labelId}
> >
{canLaunch && template.type === 'job_template' && ( <LaunchButton resource={template}>
<Tooltip content={t`Launch Template`} position="top"> {({ handleLaunch, isLaunching }) => (
<LaunchButton resource={template}>
{({ handleLaunch, isLaunching }) => (
<Button
ouiaId={`${template.id}-launch-button`}
css="grid-column: 1"
variant="plain"
onClick={handleLaunch}
isDisabled={isLaunching}
>
<RocketIcon />
</Button>
)}
</LaunchButton>
</Tooltip>
)}
{template.summary_fields.user_capabilities.edit && (
<Tooltip content={t`Edit Template`} position="top">
<Button <Button
ouiaId={`${template.id}-edit-button`} ouiaId={`${template.id}-launch-button`}
css="grid-column: 2" css="grid-column: 1"
variant="plain" variant="plain"
component={Link} onClick={handleLaunch}
to={`/templates/${template.type}/${template.id}/edit`} isDisabled={isLaunching}
> >
<PencilAltIcon /> <RocketIcon />
</Button> </Button>
</Tooltip> )}
)} </LaunchButton>
</DataListAction> </ActionItem>
</DataListItemRow> <ActionItem
</DataListItem> visible={template.summary_fields.user_capabilities.edit}
tooltip={t`Edit Template`}
>
<Button
ouiaId={`${template.id}-edit-button`}
css="grid-column: 2"
variant="plain"
component={Link}
to={`/templates/${template.type}/${template.id}/edit`}
>
<PencilAltIcon />
</Button>
</ActionItem>
</ActionsTd>
</Tr>
); );
} }

View File

@@ -7,157 +7,195 @@ import ProjectJobTemplatesListItem from './ProjectJobTemplatesListItem';
describe('<ProjectJobTemplatesListItem />', () => { describe('<ProjectJobTemplatesListItem />', () => {
test('launch button shown to users with start capabilities', () => { test('launch button shown to users with start capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
start: true, summary_fields: {
}, user_capabilities: {
}, start: true,
}} },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('LaunchButton').exists()).toBeTruthy(); expect(wrapper.find('LaunchButton').exists()).toBeTruthy();
}); });
test('launch button hidden from users without start capabilities', () => { test('launch button hidden from users without start capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
start: false, summary_fields: {
}, user_capabilities: {
}, start: false,
}} },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('LaunchButton').exists()).toBeFalsy(); expect(wrapper.find('LaunchButton').exists()).toBeFalsy();
}); });
test('edit button shown to users with edit capabilities', () => { test('edit button shown to users with edit capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
edit: true, summary_fields: {
}, user_capabilities: {
}, edit: true,
}} },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeTruthy(); expect(wrapper.find('PencilAltIcon').exists()).toBeTruthy();
}); });
test('edit button hidden from users without edit capabilities', () => { test('edit button hidden from users without edit capabilities', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
edit: false, summary_fields: {
}, user_capabilities: {
}, edit: false,
}} },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy(); expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy();
}); });
test('missing resource icon is shown.', () => { test('missing resource icon is shown.', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
edit: false, summary_fields: {
}, user_capabilities: {
}, edit: false,
}} },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(true); expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(true);
}); });
test('missing resource icon is not shown when there is a project and an inventory.', () => { test('missing resource icon is not shown when there is a project and an inventory.', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
edit: false, summary_fields: {
}, user_capabilities: {
project: { name: 'Foo', id: 2 }, edit: false,
inventory: { name: 'Bar', id: 2 }, },
}, project: { name: 'Foo', id: 2 },
}} inventory: { name: 'Bar', id: 2 },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(false); expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(false);
}); });
test('missing resource icon is not shown when inventory is prompt_on_launch, and a project', () => { test('missing resource icon is not shown when inventory is prompt_on_launch, and a project', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
ask_inventory_on_launch: true, url: '/templates/job_template/1',
summary_fields: { type: 'job_template',
user_capabilities: { ask_inventory_on_launch: true,
edit: false, summary_fields: {
}, user_capabilities: {
project: { name: 'Foo', id: 2 }, edit: false,
}, },
}} project: { name: 'Foo', id: 2 },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(false); expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(false);
}); });
test('missing resource icon is not shown type is workflow_job_template', () => { test('missing resource icon is not shown type is workflow_job_template', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'workflow_job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'workflow_job_template',
edit: false, summary_fields: {
}, user_capabilities: {
}, edit: false,
}} },
/> },
}}
/>
</tbody>
</table>
); );
expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(false); expect(wrapper.find('ExclamationTriangleIcon').exists()).toBe(false);
}); });
@@ -166,19 +204,23 @@ describe('<ProjectJobTemplatesListItem />', () => {
initialEntries: ['/projects/1/job_templates'], initialEntries: ['/projects/1/job_templates'],
}); });
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
detailUrl="/templates/job_template/2/details" <ProjectJobTemplatesListItem
template={{ isSelected={false}
id: 2, detailUrl="/templates/job_template/2/details"
name: 'Template 2', template={{
summary_fields: { id: 2,
user_capabilities: { name: 'Template 2',
edit: false, summary_fields: {
}, user_capabilities: {
}, edit: false,
}} },
/>, },
}}
/>
</tbody>
</table>,
{ context: { router: { history } } } { context: { router: { history } } }
); );
wrapper.find('Link').simulate('click', { button: 0 }); wrapper.find('Link').simulate('click', { button: 0 });
@@ -189,22 +231,26 @@ describe('<ProjectJobTemplatesListItem />', () => {
test('should render warning about missing execution environment', () => { test('should render warning about missing execution environment', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<ProjectJobTemplatesListItem <table>
isSelected={false} <tbody>
template={{ <ProjectJobTemplatesListItem
id: 1, isSelected={false}
name: 'Template 1', template={{
url: '/templates/job_template/1', id: 1,
type: 'job_template', name: 'Template 1',
summary_fields: { url: '/templates/job_template/1',
user_capabilities: { type: 'job_template',
edit: true, summary_fields: {
}, user_capabilities: {
}, edit: true,
custom_virtualenv: '/var/lib/awx/env', },
execution_environment: null, },
}} custom_virtualenv: '/var/lib/awx/env',
/> execution_environment: null,
}}
/>
</tbody>
</table>
); );
expect( expect(

View File

@@ -3,7 +3,11 @@ import { useLocation, useParams } from 'react-router-dom';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { getQSConfig, parseQueryString } from '../../../util/qs'; import { getQSConfig, parseQueryString } from '../../../util/qs';
import PaginatedDataList, { import PaginatedTable, {
HeaderRow,
HeaderCell,
} from '../../../components/PaginatedTable';
import {
ToolbarAddButton, ToolbarAddButton,
ToolbarDeleteButton, ToolbarDeleteButton,
} from '../../../components/PaginatedDataList'; } from '../../../components/PaginatedDataList';
@@ -68,9 +72,13 @@ function UserTokenList() {
fetchTokens(); fetchTokens();
}, [fetchTokens]); }, [fetchTokens]);
const { selected, isAllSelected, handleSelect, setSelected } = useSelected( const {
tokens selected,
); isAllSelected,
handleSelect,
clearSelected,
selectAll,
} = useSelected(tokens);
const { const {
isLoading: isDeleteLoading, isLoading: isDeleteLoading,
@@ -91,21 +99,21 @@ function UserTokenList() {
); );
const handleDelete = async () => { const handleDelete = async () => {
await deleteTokens(); await deleteTokens();
setSelected([]); clearSelected();
}; };
const canAdd = true; const canAdd = true;
return ( return (
<> <>
<PaginatedDataList <PaginatedTable
contentError={error} contentError={error}
hasContentLoading={isLoading || isDeleteLoading} hasContentLoading={isLoading || isDeleteLoading}
items={tokens} items={tokens}
itemCount={itemCount} itemCount={itemCount}
pluralizedItemName={t`Tokens`} pluralizedItemName={t`Tokens`}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
onRowClick={handleSelect} clearSelected={clearSelected}
toolbarSearchColumns={[ toolbarSearchColumns={[
{ {
name: t`Application name`, name: t`Application name`,
@@ -147,9 +155,7 @@ function UserTokenList() {
showSelectAll showSelectAll
isAllSelected={isAllSelected} isAllSelected={isAllSelected}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
onSelectAll={isSelected => onSelectAll={selectAll}
setSelected(isSelected ? [...tokens] : [])
}
additionalControls={[ additionalControls={[
...(canAdd ...(canAdd
? [ ? [
@@ -168,7 +174,14 @@ function UserTokenList() {
]} ]}
/> />
)} )}
renderItem={token => ( headerRow={
<HeaderRow qsConfig={QS_CONFIG}>
<HeaderCell sortKey="application__name">{t`Name`}</HeaderCell>
<HeaderCell sortKey="scope">{t`Scope`}</HeaderCell>
<HeaderCell sortKey="expires">{t`Expires`}</HeaderCell>
</HeaderRow>
}
renderRow={(token, index) => (
<UserTokensListItem <UserTokensListItem
key={token.id} key={token.id}
token={token} token={token}
@@ -176,6 +189,7 @@ function UserTokenList() {
handleSelect(token); handleSelect(token);
}} }}
isSelected={selected.some(row => row.id === token.id)} isSelected={selected.some(row => row.id === token.id)}
rowIndex={index}
/> />
)} )}
emptyStateControls={ emptyStateControls={

View File

@@ -143,32 +143,6 @@ describe('<UserTokenList />', () => {
expect(wrapper.find('UserTokenList').length).toBe(1); expect(wrapper.find('UserTokenList').length).toBe(1);
}); });
test('edit button should be disabled', async () => {
await act(async () => {
wrapper = mountWithContexts(<UserTokenList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
});
test('should enable edit button', async () => {
UsersAPI.readTokens.mockResolvedValue(tokens);
await act(async () => {
wrapper = mountWithContexts(<UserTokenList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
expect(
wrapper.find('DataListCheck[id="select-token-3"]').props().checked
).toBe(false);
await act(async () => {
wrapper.find('DataListCheck[id="select-token-3"]').invoke('onChange')(
true
);
});
wrapper.update();
expect(
wrapper.find('DataListCheck[id="select-token-3"]').props().checked
).toBe(true);
});
test('delete button should be disabled', async () => { test('delete button should be disabled', async () => {
UsersAPI.readTokens.mockResolvedValue(tokens); UsersAPI.readTokens.mockResolvedValue(tokens);
await act(async () => { await act(async () => {
@@ -179,6 +153,7 @@ describe('<UserTokenList />', () => {
true true
); );
}); });
test('should select and then delete item properly', async () => { test('should select and then delete item properly', async () => {
UsersAPI.readTokens.mockResolvedValue(tokens); UsersAPI.readTokens.mockResolvedValue(tokens);
await act(async () => { await act(async () => {
@@ -190,13 +165,17 @@ describe('<UserTokenList />', () => {
); );
await act(async () => { await act(async () => {
wrapper wrapper
.find('DataListCheck[aria-labelledby="check-action-3"]') .find('.pf-c-table__check')
.at(2)
.find('input')
.prop('onChange')(tokens.data.results[0]); .prop('onChange')(tokens.data.results[0]);
}); });
wrapper.update(); wrapper.update();
expect( expect(
wrapper wrapper
.find('DataListCheck[aria-labelledby="check-action-3"]') .find('.pf-c-table__check')
.at(2)
.find('input')
.prop('checked') .prop('checked')
).toBe(true); ).toBe(true);
expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe( expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe(
@@ -213,6 +192,7 @@ describe('<UserTokenList />', () => {
wrapper.update(); wrapper.update();
expect(TokensAPI.destroy).toHaveBeenCalledWith(3); expect(TokensAPI.destroy).toHaveBeenCalledWith(3);
}); });
test('should select and then delete item properly', async () => { test('should select and then delete item properly', async () => {
UsersAPI.readTokens.mockResolvedValue(tokens); UsersAPI.readTokens.mockResolvedValue(tokens);
TokensAPI.destroy.mockRejectedValue( TokensAPI.destroy.mockRejectedValue(
@@ -236,13 +216,17 @@ describe('<UserTokenList />', () => {
); );
await act(async () => { await act(async () => {
wrapper wrapper
.find('DataListCheck[aria-labelledby="check-action-3"]') .find('.pf-c-table__check')
.at(2)
.find('input')
.prop('onChange')(tokens.data.results[0]); .prop('onChange')(tokens.data.results[0]);
}); });
wrapper.update(); wrapper.update();
expect( expect(
wrapper wrapper
.find('DataListCheck[aria-labelledby="check-action-3"]') .find('.pf-c-table__check')
.at(2)
.find('input')
.prop('checked') .prop('checked')
).toBe(true); ).toBe(true);
expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe( expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe(

View File

@@ -2,74 +2,31 @@ import React from 'react';
import { Link, useParams } from 'react-router-dom'; import { Link, useParams } from 'react-router-dom';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { import { Tr, Td } from '@patternfly/react-table';
DataListItemCells,
DataListCheck,
DataListItemRow,
DataListItem,
} from '@patternfly/react-core';
import styled from 'styled-components';
import { toTitleCase } from '../../../util/strings'; import { toTitleCase } from '../../../util/strings';
import { formatDateString } from '../../../util/dates'; import { formatDateString } from '../../../util/dates';
import DataListCell from '../../../components/DataListCell';
const Label = styled.b` function UserTokenListItem({ token, isSelected, onSelect, rowIndex }) {
margin-right: 20px;
`;
const NameLabel = styled.b`
margin-right: 5px;
`;
function UserTokenListItem({ token, isSelected, onSelect }) {
const { id } = useParams(); const { id } = useParams();
const labelId = `check-action-${token.id}`;
return ( return (
<DataListItem key={token.id} aria-labelledby={labelId} id={`${token.id}`}> <Tr id={`token-row-${token.id}`}>
<DataListItemRow> <Td
<DataListCheck select={{
id={`select-token-${token.id}`} rowIndex,
checked={isSelected} isSelected,
onChange={onSelect} onSelect,
aria-labelledby={labelId} }}
/> />
<DataListItemCells <Td dataLabel={t`Name`}>
dataListCells={[ <Link to={`/users/${id}/tokens/${token.id}/details`}>
<DataListCell aria-label={t`Token type`} key="type"> {token.summary_fields?.application
<Link to={`/users/${id}/tokens/${token.id}/details`}> ? token.summary_fields.application.name
{token.summary_fields?.application : `Personal access token`}
? t`Application access token` </Link>
: t`Personal access token`} </Td>
</Link> <Td dataLabel={t`Scope`}>{toTitleCase(token.scope)}</Td>
</DataListCell>, <Td dataLabel={t`Expires`}>{formatDateString(token.expires)}</Td>
<DataListCell </Tr>
aria-label={t`Application name`}
key="applicationName"
>
{token.summary_fields?.application && (
<span>
<NameLabel>{t`Application`}</NameLabel>
<Link
to={`/applications/${token.summary_fields.application.id}/details`}
>
{token.summary_fields.application.name}
</Link>
</span>
)}
</DataListCell>,
<DataListCell aria-label={t`Scope`} key="scope">
<Label>{t`Scope`}</Label>
{toTitleCase(token.scope)}
</DataListCell>,
<DataListCell aria-label={t`Expiration`} key="expiration">
<Label>{t`Expires`}</Label>
{formatDateString(token.expires)}
</DataListCell>,
]}
/>
</DataListItemRow>
</DataListItem>
); );
} }

View File

@@ -39,7 +39,13 @@ describe('<UserTokenListItem />', () => {
let wrapper; let wrapper;
test('should mount properly', async () => { test('should mount properly', async () => {
await act(async () => { await act(async () => {
wrapper = mountWithContexts(<UserTokenListItem token={token} />); wrapper = mountWithContexts(
<table>
<tbody>
<UserTokenListItem token={token} />
</tbody>
</table>
);
}); });
expect(wrapper.find('UserTokenListItem').length).toBe(1); expect(wrapper.find('UserTokenListItem').length).toBe(1);
}); });
@@ -47,62 +53,101 @@ describe('<UserTokenListItem />', () => {
test('should render application access token row properly', async () => { test('should render application access token row properly', async () => {
await act(async () => { await act(async () => {
wrapper = mountWithContexts( wrapper = mountWithContexts(
<UserTokenListItem isSelected={false} token={token} /> <table>
<tbody>
<UserTokenListItem isSelected={false} token={token} />
</tbody>
</table>
); );
}); });
expect(wrapper.find('DataListCheck').prop('checked')).toBe(false);
expect(wrapper.find('PFDataListCell[aria-label="Token type"]').text()).toBe(
'Application access token'
);
expect( expect(
wrapper.find('PFDataListCell[aria-label="Application name"]').text() wrapper
).toContain('Foobar app'); .find('Td')
expect(wrapper.find('PFDataListCell[aria-label="Scope"]').text()).toContain( .first()
'Read' .prop('select').isSelected
); ).toBe(false);
expect( expect(
wrapper.find('PFDataListCell[aria-label="Expiration"]').text() wrapper
.find('Td')
.at(1)
.text()
).toBe('Foobar app');
expect(
wrapper
.find('Td')
.at(2)
.text()
).toContain('Read');
expect(
wrapper
.find('Td')
.at(3)
.text()
).toContain('10/25/3019, 3:06:43 PM'); ).toContain('10/25/3019, 3:06:43 PM');
}); });
test('should render personal access token row properly', async () => { test('should render personal access token row properly', async () => {
await act(async () => { await act(async () => {
wrapper = mountWithContexts( wrapper = mountWithContexts(
<UserTokenListItem <table>
isSelected={false} <tbody>
token={{ <UserTokenListItem
...token, isSelected={false}
refresh_token: null, token={{
application: null, ...token,
scope: 'write', refresh_token: null,
summary_fields: { application: null,
user: token.summary_fields.user, scope: 'write',
}, summary_fields: {
}} user: token.summary_fields.user,
/> },
}}
/>
</tbody>
</table>
); );
}); });
expect(wrapper.find('DataListCheck').prop('checked')).toBe(false);
expect(wrapper.find('PFDataListCell[aria-label="Token type"]').text()).toBe(
'Personal access token'
);
expect( expect(
wrapper.find('PFDataListCell[aria-label="Application name"]').text() wrapper
).toBe(''); .find('Td')
expect(wrapper.find('PFDataListCell[aria-label="Scope"]').text()).toContain( .first()
'Write' .prop('select').isSelected
); ).toBe(false);
expect( expect(
wrapper.find('PFDataListCell[aria-label="Expiration"]').text() wrapper
.find('Td')
.at(1)
.text()
).toEqual('Personal access token');
expect(
wrapper
.find('Td')
.at(2)
.text()
).toEqual('Write');
expect(
wrapper
.find('Td')
.at(3)
.text()
).toContain('10/25/3019, 3:06:43 PM'); ).toContain('10/25/3019, 3:06:43 PM');
}); });
test('should be checked', async () => { test('should be checked', async () => {
await act(async () => { await act(async () => {
wrapper = mountWithContexts( wrapper = mountWithContexts(
<UserTokenListItem isSelected token={token} /> <table>
<tbody>
<UserTokenListItem isSelected token={token} />
</tbody>
</table>
); );
}); });
expect(wrapper.find('DataListCheck').prop('checked')).toBe(true); expect(
wrapper
.find('Td')
.first()
.prop('select').isSelected
).toBe(true);
}); });
}); });

View File

@@ -11,7 +11,8 @@ jest.mock('react-router-dom', () => ({
describe('<Users />', () => { describe('<Users />', () => {
test('initially renders successfully', () => { test('initially renders successfully', () => {
mountWithContexts(<Users />); const wrapper = mountWithContexts(<Users />);
wrapper.unmount();
}); });
test('should display a breadcrumb heading', () => { test('should display a breadcrumb heading', () => {