Adds Copy Button to Inventory List and Project List

This commit is contained in:
Alex Corey
2020-05-06 14:00:47 -04:00
parent 3aa6e8a457
commit d566b465aa
7 changed files with 435 additions and 176 deletions

View File

@@ -167,6 +167,7 @@ function InventoryList({ i18n }) {
key={inventory.id} key={inventory.id}
value={inventory.name} value={inventory.name}
inventory={inventory} inventory={inventory}
fetchInventories={fetchInventories}
detailUrl={ detailUrl={
inventory.kind === 'smart' inventory.kind === 'smart'
? `${match.url}/smart_inventory/${inventory.id}/details` ? `${match.url}/smart_inventory/${inventory.id}/details`
@@ -182,6 +183,7 @@ function InventoryList({ i18n }) {
<AlertModal <AlertModal
isOpen={deletionError} isOpen={deletionError}
variant="error" variant="error"
aria-label={i18n._(t`Deletion Error`)}
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}
onClose={clearDeletionError} onClose={clearDeletionError}
> >

View File

@@ -279,7 +279,7 @@ describe('<InventoryList />', () => {
}); });
wrapper.update(); wrapper.update();
const modal = wrapper.find('Modal'); const modal = wrapper.find('Modal[aria-label="Deletion Error"]');
expect(modal).toHaveLength(1); expect(modal).toHaveLength(1);
expect(modal.prop('title')).toEqual('Error!'); expect(modal.prop('title')).toEqual('Error!');
}); });

View File

@@ -1,4 +1,4 @@
import React from 'react'; import React, { useState, useCallback } from 'react';
import { string, bool, func } from 'prop-types'; import { string, bool, func } from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { import {
@@ -16,79 +16,106 @@ import { t } from '@lingui/macro';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import styled from 'styled-components'; import styled from 'styled-components';
import { PencilAltIcon } from '@patternfly/react-icons'; import { PencilAltIcon } from '@patternfly/react-icons';
import { timeOfDay } from '@util/dates';
import { InventoriesAPI } from '@api';
import { Inventory } from '@types'; import { Inventory } from '@types';
import CopyButton from '../../../components/CopyButton/CopyButton';
const DataListAction = styled(_DataListAction)` const DataListAction = styled(_DataListAction)`
align-items: center; align-items: center;
display: grid; display: grid;
grid-gap: 16px; grid-gap: 16px;
grid-template-columns: 40px; grid-template-columns: repeat(2, 40px);
`; `;
class InventoryListItem extends React.Component { function InventoryListItem({
static propTypes = { inventory,
isSelected,
onSelect,
detailUrl,
i18n,
fetchInventories,
}) {
InventoryListItem.propTypes = {
inventory: Inventory.isRequired, inventory: Inventory.isRequired,
detailUrl: string.isRequired, detailUrl: string.isRequired,
isSelected: bool.isRequired, isSelected: bool.isRequired,
onSelect: func.isRequired, onSelect: func.isRequired,
}; };
const [isDisabled, setIsDisabled] = useState(false);
render() { const copyInventory = useCallback(async () => {
const { inventory, isSelected, onSelect, detailUrl, i18n } = this.props; await InventoriesAPI.copy(inventory.id, {
const labelId = `check-action-${inventory.id}`; name: `${inventory.name} @ ${timeOfDay()}`,
return ( });
<DataListItem await fetchInventories();
key={inventory.id} }, [inventory.id, inventory.name, fetchInventories]);
aria-labelledby={labelId}
id={`${inventory.id}`} const labelId = `check-action-${inventory.id}`;
> return (
<DataListItemRow> <DataListItem
<DataListCheck key={inventory.id}
id={`select-inventory-${inventory.id}`} aria-labelledby={labelId}
checked={isSelected} id={`${inventory.id}`}
onChange={onSelect} >
aria-labelledby={labelId} <DataListItemRow>
/> <DataListCheck
<DataListItemCells id={`select-inventory-${inventory.id}`}
dataListCells={[ checked={isSelected}
<DataListCell key="divider"> onChange={onSelect}
<Link to={`${detailUrl}`}> aria-labelledby={labelId}
<b>{inventory.name}</b> />
</Link> <DataListItemCells
</DataListCell>, dataListCells={[
<DataListCell key="kind"> <DataListCell key="divider">
{inventory.kind === 'smart' <Link to={`${detailUrl}`}>
? i18n._(t`Smart Inventory`) <b>{inventory.name}</b>
: i18n._(t`Inventory`)} </Link>
</DataListCell>, </DataListCell>,
]} <DataListCell key="kind">
/> {inventory.kind === 'smart'
<DataListAction ? i18n._(t`Smart Inventory`)
aria-label="actions" : i18n._(t`Inventory`)}
aria-labelledby={labelId} </DataListCell>,
id={labelId} ]}
> />
{inventory.summary_fields.user_capabilities.edit ? ( <DataListAction
<Tooltip content={i18n._(t`Edit Inventory`)} position="top"> aria-label="actions"
<Button aria-labelledby={labelId}
aria-label={i18n._(t`Edit Inventory`)} id={labelId}
variant="plain" >
component={Link} {inventory.summary_fields.user_capabilities.edit ? (
to={`/inventories/${ <Tooltip content={i18n._(t`Edit Inventory`)} position="top">
inventory.kind === 'smart' ? 'smart_inventory' : 'inventory' <Button
}/${inventory.id}/edit`} isDisabled={isDisabled}
> aria-label={i18n._(t`Edit Inventory`)}
<PencilAltIcon /> variant="plain"
</Button> component={Link}
</Tooltip> to={`/inventories/${
) : ( inventory.kind === 'smart' ? 'smart_inventory' : 'inventory'
'' }/${inventory.id}/edit`}
)} >
</DataListAction> <PencilAltIcon />
</DataListItemRow> </Button>
</DataListItem> </Tooltip>
); ) : (
} ''
)}
{inventory.summary_fields.user_capabilities.copy && (
<CopyButton
copyItem={copyInventory}
isDisabled={isDisabled}
onLoading={() => setIsDisabled(true)}
onDoneLoading={() => setIsDisabled(false)}
helperText={{
tooltip: i18n._(t`Copy Inventory`),
errorMessage: i18n._(t`Failed to copy inventory.`),
}}
/>
)}
</DataListAction>
</DataListItemRow>
</DataListItem>
);
} }
export default withI18n()(InventoryListItem); export default withI18n()(InventoryListItem);

View File

@@ -1,9 +1,13 @@
import React from 'react'; import React from 'react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { I18nProvider } from '@lingui/react'; import { I18nProvider } from '@lingui/react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts } from '@testUtils/enzymeHelpers'; import { mountWithContexts } from '@testUtils/enzymeHelpers';
import { InventoriesAPI } from '@api';
import InventoryListItem from './InventoryListItem'; import InventoryListItem from './InventoryListItem';
jest.mock('@api/models/Inventories');
describe('<InventoryListItem />', () => { describe('<InventoryListItem />', () => {
test('initially renders succesfully', () => { test('initially renders succesfully', () => {
mountWithContexts( mountWithContexts(
@@ -85,4 +89,104 @@ describe('<InventoryListItem />', () => {
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy(); expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy();
}); });
test('should call api to copy inventory', async () => {
InventoriesAPI.copy.mockResolvedValue();
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/inventories']} initialIndex={0}>
<InventoryListItem
inventory={{
id: 1,
name: 'Inventory',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
detailUrl="/inventories/inventory/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
expect(InventoriesAPI.copy).toHaveBeenCalled();
jest.clearAllMocks();
});
test('should render proper alert modal on copy error', async () => {
InventoriesAPI.copy.mockRejectedValue(new Error());
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/inventories']} initialIndex={0}>
<InventoryListItem
inventory={{
id: 1,
name: 'Inventory',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
detailUrl="/inventories/inventory/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
wrapper.update();
expect(wrapper.find('Modal').prop('isOpen')).toBe(true);
jest.clearAllMocks();
});
test('should not render copy button', async () => {
const wrapper = mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/inventories']} initialIndex={0}>
<InventoryListItem
inventory={{
id: 1,
name: 'Inventory',
summary_fields: {
organization: {
id: 1,
name: 'Default',
},
user_capabilities: {
edit: false,
copy: false,
},
},
}}
detailUrl="/inventories/inventory/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);
expect(wrapper.find('CopyButton').length).toBe(0);
});
}); });

View File

@@ -170,6 +170,7 @@ function ProjectList({ i18n }) {
)} )}
renderItem={o => ( renderItem={o => (
<ProjectListItem <ProjectListItem
fetchProjects={fetchProjects}
key={o.id} key={o.id}
project={o} project={o}
detailUrl={`${match.url}/${o.id}`} detailUrl={`${match.url}/${o.id}`}
@@ -188,6 +189,7 @@ function ProjectList({ i18n }) {
<AlertModal <AlertModal
isOpen={deletionError} isOpen={deletionError}
variant="error" variant="error"
aria-label={i18n._(t`Deletion Error`)}
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}
onClose={clearDeletionError} onClose={clearDeletionError}
> >

View File

@@ -1,4 +1,4 @@
import React, { Fragment } from 'react'; import React, { Fragment, useState, useCallback } from 'react';
import { string, bool, func } from 'prop-types'; import { string, bool, func } from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { import {
@@ -16,35 +16,45 @@ import { t } from '@lingui/macro';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { PencilAltIcon, SyncIcon } from '@patternfly/react-icons'; import { PencilAltIcon, SyncIcon } from '@patternfly/react-icons';
import styled from 'styled-components'; import styled from 'styled-components';
import { timeOfDay } from '@util/dates';
import { ProjectsAPI } from '@api';
import ClipboardCopyButton from '@components/ClipboardCopyButton'; import ClipboardCopyButton from '@components/ClipboardCopyButton';
import ProjectSyncButton from '../shared/ProjectSyncButton';
import StatusIcon from '@components/StatusIcon'; import StatusIcon from '@components/StatusIcon';
import { toTitleCase } from '@util/strings'; import { toTitleCase } from '@util/strings';
import CopyButton from '@components/CopyButton';
import ProjectSyncButton from '../shared/ProjectSyncButton';
import { Project } from '@types'; import { Project } from '@types';
const DataListAction = styled(_DataListAction)` const DataListAction = styled(_DataListAction)`
align-items: center; align-items: center;
display: grid; display: grid;
grid-gap: 16px; grid-gap: 16px;
grid-template-columns: repeat(2, 40px); grid-template-columns: repeat(3, 40px);
`; `;
class ProjectListItem extends React.Component { function ProjectListItem({
static propTypes = { project,
isSelected,
onSelect,
detailUrl,
i18n,
fetchProjects,
}) {
const [isDisabled, setIsDisabled] = useState(false);
ProjectListItem.propTypes = {
project: Project.isRequired, project: Project.isRequired,
detailUrl: string.isRequired, detailUrl: string.isRequired,
isSelected: bool.isRequired, isSelected: bool.isRequired,
onSelect: func.isRequired, onSelect: func.isRequired,
}; };
constructor(props) { const copyProject = useCallback(async () => {
super(props); await ProjectsAPI.copy(project.id, {
name: `${project.name} @ ${timeOfDay()}`,
});
await fetchProjects();
}, [project.id, project.name, fetchProjects]);
this.generateLastJobTooltip = this.generateLastJobTooltip.bind(this); const generateLastJobTooltip = job => {
}
generateLastJobTooltip = job => {
const { i18n } = this.props;
return ( return (
<Fragment> <Fragment>
<div>{i18n._(t`MOST RECENT SYNC`)}</div> <div>{i18n._(t`MOST RECENT SYNC`)}</div>
@@ -63,107 +73,116 @@ class ProjectListItem extends React.Component {
); );
}; };
render() { const labelId = `check-action-${project.id}`;
const { project, isSelected, onSelect, detailUrl, i18n } = this.props; return (
const labelId = `check-action-${project.id}`; <DataListItem
return ( key={project.id}
<DataListItem aria-labelledby={labelId}
key={project.id} id={`${project.id}`}
aria-labelledby={labelId} >
id={`${project.id}`} <DataListItemRow>
> <DataListCheck
<DataListItemRow> id={`select-project-${project.id}`}
<DataListCheck checked={isSelected}
id={`select-project-${project.id}`} onChange={onSelect}
checked={isSelected} aria-labelledby={labelId}
onChange={onSelect} />
aria-labelledby={labelId} <DataListItemCells
/> dataListCells={[
<DataListItemCells <DataListCell key="status" isFilled={false}>
dataListCells={[ {project.summary_fields.last_job && (
<DataListCell key="status" isFilled={false}> <Tooltip
{project.summary_fields.last_job && ( position="top"
<Tooltip content={generateLastJobTooltip(
position="top" project.summary_fields.last_job
content={this.generateLastJobTooltip(
project.summary_fields.last_job
)}
key={project.summary_fields.last_job.id}
>
<Link
to={`/jobs/project/${project.summary_fields.last_job.id}`}
>
<StatusIcon
status={project.summary_fields.last_job.status}
/>
</Link>
</Tooltip>
)}
</DataListCell>,
<DataListCell key="name">
<Link id={labelId} to={`${detailUrl}`}>
<b>{project.name}</b>
</Link>
</DataListCell>,
<DataListCell key="type">
{project.scm_type === ''
? i18n._(t`Manual`)
: toTitleCase(project.scm_type)}
</DataListCell>,
<DataListCell key="revision">
{project.scm_revision.substring(0, 7)}
{project.scm_revision ? (
<ClipboardCopyButton
stringToCopy={project.scm_revision}
hoverTip={i18n._(t`Copy full revision to clipboard.`)}
clickTip={i18n._(t`Successfully copied to clipboard!`)}
/>
) : null}
</DataListCell>,
]}
/>
<DataListAction
aria-label="actions"
aria-labelledby={labelId}
id={labelId}
>
{project.summary_fields.user_capabilities.start ? (
<Tooltip content={i18n._(t`Sync Project`)} position="top">
<ProjectSyncButton projectId={project.id}>
{handleSync => (
<Button
aria-label={i18n._(t`Sync Project`)}
css="grid-column: 1"
variant="plain"
onClick={handleSync}
>
<SyncIcon />
</Button>
)} )}
</ProjectSyncButton> key={project.summary_fields.last_job.id}
</Tooltip>
) : (
''
)}
{project.summary_fields.user_capabilities.edit ? (
<Tooltip content={i18n._(t`Edit Project`)} position="top">
<Button
aria-label={i18n._(t`Edit Project`)}
css="grid-column: 2"
variant="plain"
component={Link}
to={`/projects/${project.id}/edit`}
> >
<PencilAltIcon /> <Link
</Button> to={`/jobs/project/${project.summary_fields.last_job.id}`}
</Tooltip> >
) : ( <StatusIcon
'' status={project.summary_fields.last_job.status}
)} />
</DataListAction> </Link>
</DataListItemRow> </Tooltip>
</DataListItem> )}
); </DataListCell>,
} <DataListCell key="name">
<Link id={labelId} to={`${detailUrl}`}>
<b>{project.name}</b>
</Link>
</DataListCell>,
<DataListCell key="type">
{project.scm_type === ''
? i18n._(t`Manual`)
: toTitleCase(project.scm_type)}
</DataListCell>,
<DataListCell key="revision">
{project.scm_revision.substring(0, 7)}
{project.scm_revision ? (
<ClipboardCopyButton
stringToCopy={project.scm_revision}
hoverTip={i18n._(t`Copy full revision to clipboard.`)}
clickTip={i18n._(t`Successfully copied to clipboard!`)}
/>
) : null}
</DataListCell>,
]}
/>
<DataListAction
aria-label="actions"
aria-labelledby={labelId}
id={labelId}
>
{project.summary_fields.user_capabilities.start ? (
<Tooltip content={i18n._(t`Sync Project`)} position="top">
<ProjectSyncButton projectId={project.id}>
{handleSync => (
<Button
isDisabled={isDisabled}
aria-label={i18n._(t`Sync Project`)}
variant="plain"
onClick={handleSync}
>
<SyncIcon />
</Button>
)}
</ProjectSyncButton>
</Tooltip>
) : (
''
)}
{project.summary_fields.user_capabilities.edit ? (
<Tooltip content={i18n._(t`Edit Project`)} position="top">
<Button
isDisabled={isDisabled}
aria-label={i18n._(t`Edit Project`)}
variant="plain"
component={Link}
to={`/projects/${project.id}/edit`}
>
<PencilAltIcon />
</Button>
</Tooltip>
) : (
''
)}
{project.summary_fields.user_capabilities.copy && (
<CopyButton
copyItem={copyProject}
isDisabled={isDisabled}
onLoading={() => setIsDisabled(true)}
onDoneLoading={() => setIsDisabled(false)}
helperText={{
tooltip: i18n._(t`Copy Project`),
errorMessage: i18n._(t`Failed to copy project.`),
}}
/>
)}
</DataListAction>
</DataListItemRow>
</DataListItem>
);
} }
export default withI18n()(ProjectListItem); export default withI18n()(ProjectListItem);

View File

@@ -1,8 +1,11 @@
import React from 'react'; import React from 'react';
import { mountWithContexts } from '@testUtils/enzymeHelpers'; import { mountWithContexts } from '@testUtils/enzymeHelpers';
import { act } from 'react-dom/test-utils';
import ProjectsListItem from './ProjectListItem'; import ProjectsListItem from './ProjectListItem';
import { ProjectsAPI } from '@api';
jest.mock('@api/models/Projects');
describe('<ProjectsListItem />', () => { describe('<ProjectsListItem />', () => {
test('launch button shown to users with start capabilities', () => { test('launch button shown to users with start capabilities', () => {
@@ -32,6 +35,7 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('ProjectSyncButton').exists()).toBeTruthy(); expect(wrapper.find('ProjectSyncButton').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(
<ProjectsListItem <ProjectsListItem
@@ -59,6 +63,7 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('ProjectSyncButton').exists()).toBeFalsy(); expect(wrapper.find('ProjectSyncButton').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(
<ProjectsListItem <ProjectsListItem
@@ -86,6 +91,7 @@ describe('<ProjectsListItem />', () => {
); );
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(
<ProjectsListItem <ProjectsListItem
@@ -113,4 +119,103 @@ describe('<ProjectsListItem />', () => {
); );
expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy(); expect(wrapper.find('PencilAltIcon').exists()).toBeFalsy();
}); });
test('should call api to copy project', async () => {
ProjectsAPI.copy.mockResolvedValue();
const wrapper = mountWithContexts(
<ProjectsListItem
isSelected={false}
detailUrl="/project/1"
onSelect={() => {}}
project={{
id: 1,
name: 'Project 1',
url: '/api/v2/projects/1',
type: 'project',
scm_type: 'git',
scm_revision: '7788f7erga0jijodfgsjisiodf98sdga9hg9a98gaf',
summary_fields: {
last_job: {
id: 9000,
status: 'successful',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
/>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
expect(ProjectsAPI.copy).toHaveBeenCalled();
jest.clearAllMocks();
});
test('should render proper alert modal on copy error', async () => {
ProjectsAPI.copy.mockRejectedValue(new Error());
const wrapper = mountWithContexts(
<ProjectsListItem
isSelected={false}
detailUrl="/project/1"
onSelect={() => {}}
project={{
id: 1,
name: 'Project 1',
url: '/api/v2/projects/1',
type: 'project',
scm_type: 'git',
scm_revision: '7788f7erga0jijodfgsjisiodf98sdga9hg9a98gaf',
summary_fields: {
last_job: {
id: 9000,
status: 'successful',
},
user_capabilities: {
edit: false,
copy: true,
},
},
}}
/>
);
await act(async () =>
wrapper.find('Button[aria-label="Copy"]').prop('onClick')()
);
wrapper.update();
expect(wrapper.find('Modal').prop('isOpen')).toBe(true);
jest.clearAllMocks();
});
test('should not render copy button', async () => {
const wrapper = mountWithContexts(
<ProjectsListItem
isSelected={false}
detailUrl="/foo/bar"
onSelect={() => {}}
project={{
id: 1,
name: 'Project 1',
url: '/api/v2/projects/1',
type: 'project',
scm_type: 'git',
scm_revision: '7788f7erga0jijodfgsjisiodf98sdga9hg9a98gaf',
summary_fields: {
last_job: {
id: 9000,
status: 'successful',
},
user_capabilities: {
edit: false,
copy: false,
},
},
}}
/>
);
expect(wrapper.find('CopyButton').length).toBe(0);
});
}); });