Refactors TemplateLiost into a functional component

This commit is contained in:
Alex Corey
2020-01-31 12:09:38 -05:00
parent bbea43b1fe
commit 25105d813d
3 changed files with 394 additions and 375 deletions

View File

@@ -1,5 +1,5 @@
import React, { Component } from 'react'; import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom'; import { useParams, useLocation } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { Card } from '@patternfly/react-core'; import { Card } from '@patternfly/react-core';
@@ -29,65 +29,96 @@ const QS_CONFIG = getQSConfig('template', {
type: 'job_template,workflow_job_template', type: 'job_template,workflow_job_template',
}); });
class TemplatesList extends Component { function TemplatesList({ i18n }) {
constructor(props) { const { id: projectId } = useParams();
super(props); const { pathname, search } = useLocation();
this.state = { const [deletionError, setDelectionError] = useState(null);
hasContentLoading: true, const [contentError, setContentError] = useState(null);
contentError: null, const [hasContentLoading, setHasContentLoading] = useState(true);
deletionError: null, const [jtActions, setJTActions] = useState(null);
selected: [], const [wfjtActions, setWFJTActions] = useState(null);
templates: [], const [count, setCount] = useState(0);
itemCount: 0, const [templates, setTemplates] = useState([]);
const [selected, setSelected] = useState([]);
useEffect(
() => {
const loadTemplates = async () => {
const params = {
...parseQueryString(QS_CONFIG, search),
}; };
this.loadTemplates = this.loadTemplates.bind(this); let jtOptionsPromise;
this.handleSelectAll = this.handleSelectAll.bind(this); if (jtActions) {
this.handleSelect = this.handleSelect.bind(this); jtOptionsPromise = Promise.resolve({
this.handleTemplateDelete = this.handleTemplateDelete.bind(this); data: { actions: jtActions },
this.handleDeleteErrorClose = this.handleDeleteErrorClose.bind(this); });
}
componentDidMount() {
this.loadTemplates();
}
componentDidUpdate(prevProps) {
const { location } = this.props;
if (location !== prevProps.location) {
this.loadTemplates();
}
}
componentWillUnmount() {
document.removeEventListener('click', this.handleAddToggle, false);
}
handleDeleteErrorClose() {
this.setState({ deletionError: null });
}
handleSelectAll(isSelected) {
const { templates } = this.state;
const selected = isSelected ? [...templates] : [];
this.setState({ selected });
}
handleSelect(template) {
const { selected } = this.state;
if (selected.some(s => s.id === template.id)) {
this.setState({ selected: selected.filter(s => s.id !== template.id) });
} else { } else {
this.setState({ selected: selected.concat(template) }); jtOptionsPromise = JobTemplatesAPI.readOptions();
}
} }
async handleTemplateDelete() { let wfjtOptionsPromise;
const { selected, itemCount } = this.state; if (wfjtActions) {
wfjtOptionsPromise = Promise.resolve({
data: { actions: wfjtActions },
});
} else {
wfjtOptionsPromise = WorkflowJobTemplatesAPI.readOptions();
}
if (pathname.startsWith('/projects') && projectId) {
params.jobtemplate__project = projectId;
}
this.setState({ hasContentLoading: true }); const promises = Promise.all([
UnifiedJobTemplatesAPI.read(params),
jtOptionsPromise,
wfjtOptionsPromise,
]);
setDelectionError(null);
try {
const [
{
data: { count: itemCount, results },
},
{
data: { actions: jobTemplateActions },
},
{
data: { actions: workFlowJobTemplateActions },
},
] = await promises;
setJTActions(jobTemplateActions);
setWFJTActions(workFlowJobTemplateActions);
setCount(itemCount);
setTemplates(results);
setHasContentLoading(false);
} catch (err) {
setContentError(err);
}
};
loadTemplates();
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[pathname, search, count, projectId]
);
const handleSelectAll = isSelected => {
const selectedItems = isSelected ? [...templates] : [];
setSelected(selectedItems);
};
const handleSelect = template => {
if (selected.some(s => s.id === template.id)) {
setSelected(selected.filter(s => s.id !== template.id));
} else {
setSelected(selected.concat(template));
}
};
const handleTemplateDelete = async () => {
setHasContentLoading(true);
try { try {
await Promise.all( await Promise.all(
selected.map(({ type, id }) => { selected.map(({ type, id }) => {
@@ -100,98 +131,12 @@ class TemplatesList extends Component {
return deletePromise; return deletePromise;
}) })
); );
this.setState({ itemCount: itemCount - selected.length }); setCount(count - selected.length);
} catch (err) { } catch (err) {
this.setState({ deletionError: err }); setDelectionError(err);
} finally {
await this.loadTemplates();
} }
}
async loadTemplates() {
const {
location,
match: {
params: { id: projectId },
url,
},
} = this.props;
const {
jtActions: cachedJTActions,
wfjtActions: cachedWFJTActions,
} = this.state;
const params = {
...parseQueryString(QS_CONFIG, location.search),
}; };
let jtOptionsPromise;
if (cachedJTActions) {
jtOptionsPromise = Promise.resolve({
data: { actions: cachedJTActions },
});
} else {
jtOptionsPromise = JobTemplatesAPI.readOptions();
}
let wfjtOptionsPromise;
if (cachedWFJTActions) {
wfjtOptionsPromise = Promise.resolve({
data: { actions: cachedWFJTActions },
});
} else {
wfjtOptionsPromise = WorkflowJobTemplatesAPI.readOptions();
}
if (url.startsWith('/projects') && projectId) {
params.jobtemplate__project = projectId;
}
const promises = Promise.all([
UnifiedJobTemplatesAPI.read(params),
jtOptionsPromise,
wfjtOptionsPromise,
]);
this.setState({ contentError: null, hasContentLoading: true });
try {
const [
{
data: { count, results },
},
{
data: { actions: jtActions },
},
{
data: { actions: wfjtActions },
},
] = await promises;
this.setState({
jtActions,
wfjtActions,
itemCount: count,
templates: results,
selected: [],
});
} catch (err) {
this.setState({ contentError: err });
} finally {
this.setState({ hasContentLoading: false });
}
}
render() {
const {
contentError,
hasContentLoading,
deletionError,
templates,
itemCount,
selected,
jtActions,
wfjtActions,
} = this.state;
const { match, i18n } = this.props;
const canAddJT = const canAddJT =
jtActions && Object.prototype.hasOwnProperty.call(jtActions, 'POST'); jtActions && Object.prototype.hasOwnProperty.call(jtActions, 'POST');
const canAddWFJT = const canAddWFJT =
@@ -221,10 +166,10 @@ class TemplatesList extends Component {
contentError={contentError} contentError={contentError}
hasContentLoading={hasContentLoading} hasContentLoading={hasContentLoading}
items={templates} items={templates}
itemCount={itemCount} itemCount={count}
pluralizedItemName={i18n._(t`Templates`)} pluralizedItemName={i18n._(t`Templates`)}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
onRowClick={this.handleSelect} onRowClick={handleSelect}
toolbarSearchColumns={[ toolbarSearchColumns={[
{ {
name: i18n._(t`Name`), name: i18n._(t`Name`),
@@ -268,12 +213,12 @@ class TemplatesList extends Component {
showSelectAll showSelectAll
showExpandCollapse showExpandCollapse
isAllSelected={isAllSelected} isAllSelected={isAllSelected}
onSelectAll={this.handleSelectAll} onSelectAll={handleSelectAll}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
additionalControls={[ additionalControls={[
<ToolbarDeleteButton <ToolbarDeleteButton
key="delete" key="delete"
onDelete={this.handleTemplateDelete} onDelete={handleTemplateDelete}
itemsToDelete={selected} itemsToDelete={selected}
pluralizedItemName="Templates" pluralizedItemName="Templates"
/>, />,
@@ -286,8 +231,8 @@ class TemplatesList extends Component {
key={template.id} key={template.id}
value={template.name} value={template.name}
template={template} template={template}
detailUrl={`${match.url}/${template.type}/${template.id}`} detailUrl={`${pathname}/${template.type}/${template.id}`}
onSelect={() => this.handleSelect(template)} onSelect={() => handleSelect(template)}
isSelected={selected.some(row => row.id === template.id)} isSelected={selected.some(row => row.id === template.id)}
/> />
)} )}
@@ -298,7 +243,7 @@ class TemplatesList extends Component {
isOpen={deletionError} isOpen={deletionError}
variant="danger" variant="danger"
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}
onClose={this.handleDeleteErrorClose} onClose={() => setDelectionError(null)}
> >
{i18n._(t`Failed to delete one or more templates.`)} {i18n._(t`Failed to delete one or more templates.`)}
<ErrorDetail error={deletionError} /> <ErrorDetail error={deletionError} />
@@ -306,7 +251,6 @@ class TemplatesList extends Component {
</> </>
); );
} }
}
export { TemplatesList as _TemplatesList }; export { TemplatesList as _TemplatesList };
export default withI18n()(withRouter(TemplatesList)); export default withI18n()(TemplatesList);

View File

@@ -59,7 +59,7 @@ const RightActionButtonCell = styled(ActionButtonCell)`
${rightStyle} ${rightStyle}
`; `;
function TemplateListItem({ i18n, template, isSelected, onSelect }) { function TemplateListItem({ i18n, template, isSelected, onSelect, detailUrl }) {
const canLaunch = template.summary_fields.user_capabilities.start; const canLaunch = template.summary_fields.user_capabilities.start;
const missingResourceIcon = const missingResourceIcon =
@@ -86,7 +86,7 @@ function TemplateListItem({ i18n, template, isSelected, onSelect }) {
<LeftDataListCell key="divider"> <LeftDataListCell key="divider">
<VerticalSeparator /> <VerticalSeparator />
<span> <span>
<Link to={`/templates/${template.type}/${template.id}`}> <Link to={`${detailUrl}`}>
<b>{template.name}</b> <b>{template.name}</b>
</Link> </Link>
</span> </span>

View File

@@ -1,4 +1,5 @@
import React from 'react'; import React from 'react';
import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history'; import { createMemoryHistory } from 'history';
import { Route } from 'react-router-dom'; import { Route } from 'react-router-dom';
import { import {
@@ -8,7 +9,7 @@ import {
} from '@api'; } from '@api';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers'; import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import TemplatesList, { _TemplatesList } from './TemplateList'; import TemplatesList from './TemplateList';
jest.mock('@api'); jest.mock('@api');
@@ -90,7 +91,8 @@ describe('<TemplatesList />', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('initially renders successfully', () => { test('initially renders successfully', async () => {
await act(async () => {
mountWithContexts( mountWithContexts(
<TemplatesList <TemplatesList
match={{ path: '/templates', url: '/templates' }} match={{ path: '/templates', url: '/templates' }}
@@ -98,111 +100,172 @@ describe('<TemplatesList />', () => {
/> />
); );
}); });
test('Templates are retrieved from the api and the components finishes loading', async done => {
const loadTemplates = jest.spyOn(_TemplatesList.prototype, 'loadTemplates');
const wrapper = mountWithContexts(<TemplatesList />);
await waitForElement(
wrapper,
'TemplatesList',
el => el.state('hasContentLoading') === true
);
expect(loadTemplates).toHaveBeenCalled();
await waitForElement(
wrapper,
'TemplatesList',
el => el.state('hasContentLoading') === false
);
done();
}); });
test('handleSelect is called when a template list item is selected', async done => { test('Templates are retrieved from the api and the components finishes loading', async () => {
const handleSelect = jest.spyOn(_TemplatesList.prototype, 'handleSelect'); let wrapper;
const wrapper = mountWithContexts(<TemplatesList />); await act(async () => {
await waitForElement( wrapper = mountWithContexts(<TemplatesList />);
wrapper, });
'TemplatesList', expect(UnifiedJobTemplatesAPI.read).toBeCalled();
el => el.state('hasContentLoading') === false await act(async () => {
); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
await wrapper });
.find('input#select-jobTemplate-1') expect(wrapper.find('TemplateListItem').length).toEqual(5);
.closest('DataListCheck')
.props()
.onChange();
expect(handleSelect).toBeCalled();
await waitForElement(
wrapper,
'TemplatesList',
el => el.state('selected').length === 1
);
done();
}); });
test('handleSelectAll is called when a template list item is selected', async done => { test('handleSelect is called when a template list item is selected', async () => {
const handleSelectAll = jest.spyOn(
_TemplatesList.prototype,
'handleSelectAll'
);
const wrapper = mountWithContexts(<TemplatesList />); const wrapper = mountWithContexts(<TemplatesList />);
await waitForElement( await act(async () => {
wrapper, await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
'TemplatesList', });
el => el.state('hasContentLoading') === false const checkBox = wrapper
); .find('TemplateListItem')
.at(1)
.find('input');
checkBox.simulate('change', {
target: {
id: 2,
name: 'Job Template 2',
url: '/templates/job_template/2',
type: 'job_template',
summary_fields: { user_capabilities: { delete: true } },
},
});
expect(
wrapper wrapper
.find('Checkbox#select-all') .find('TemplateListItem')
.props() .at(1)
.onChange(true); .prop('isSelected')
expect(handleSelectAll).toBeCalled(); ).toBe(true);
await waitForElement(
wrapper,
'TemplatesList',
el => el.state('selected').length === 5
);
done();
}); });
test('delete button is disabled if user does not have delete capabilities on a selected template', async done => { test('handleSelectAll is called when a template list item is selected', async () => {
const wrapper = mountWithContexts(<TemplatesList />); const wrapper = mountWithContexts(<TemplatesList />);
wrapper.find('TemplatesList').setState({ await act(async () => {
templates: mockTemplates, await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
itemCount: 5,
isInitialized: true,
selected: mockTemplates.slice(0, 4),
}); });
await waitForElement( expect(wrapper.find('Checkbox#select-all').prop('isChecked')).toBe(false);
wrapper,
'ToolbarDeleteButton * button', const toolBarCheckBox = wrapper.find('Checkbox#select-all');
el => el.getDOMNode().disabled === false act(() => {
); toolBarCheckBox.prop('onChange')(true);
wrapper.find('TemplatesList').setState({
selected: mockTemplates,
}); });
await waitForElement( wrapper.update();
wrapper, expect(wrapper.find('Checkbox#select-all').prop('isChecked')).toBe(true);
'ToolbarDeleteButton * button',
el => el.getDOMNode().disabled === true
);
done();
}); });
test('api is called to delete templates for each selected template.', () => { test('delete button is disabled if user does not have delete capabilities on a selected template', async () => {
JobTemplatesAPI.destroy = jest.fn();
WorkflowJobTemplatesAPI.destroy = jest.fn();
const wrapper = mountWithContexts(<TemplatesList />); const wrapper = mountWithContexts(<TemplatesList />);
wrapper.find('TemplatesList').setState({ await act(async () => {
templates: mockTemplates, await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
itemCount: 5,
isInitialized: true,
isModalOpen: true,
selected: mockTemplates.slice(0, 4),
}); });
wrapper.find('ToolbarDeleteButton').prop('onDelete')(); const deleteableItem = wrapper
expect(JobTemplatesAPI.destroy).toHaveBeenCalledTimes(3); .find('TemplateListItem')
expect(WorkflowJobTemplatesAPI.destroy).toHaveBeenCalledTimes(1); .at(0)
.find('input');
const nonDeleteableItem = wrapper
.find('TemplateListItem')
.at(4)
.find('input');
deleteableItem.simulate('change', {
id: 1,
name: 'Job Template 1',
url: '/templates/job_template/1',
type: 'job_template',
summary_fields: {
user_capabilities: {
delete: true,
},
},
}); });
test('error is shown when template not successfully deleted from api', async done => { expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe(
false
);
deleteableItem.simulate('change', {
id: 1,
name: 'Job Template 1',
url: '/templates/job_template/1',
type: 'job_template',
summary_fields: {
user_capabilities: {
delete: true,
},
},
});
expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe(
true
);
nonDeleteableItem.simulate('change', {
id: 5,
name: 'Workflow Job Template 2',
url: '/templates/workflow_job_template/5',
type: 'workflow_job_template',
summary_fields: {
user_capabilities: {
delete: false,
},
},
});
expect(wrapper.find('Button[aria-label="Delete"]').prop('isDisabled')).toBe(
true
);
});
test('api is called to delete templates for each selected template.', async () => {
const wrapper = mountWithContexts(<TemplatesList />);
await act(async () => {
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
});
const jobTemplate = wrapper
.find('TemplateListItem')
.at(1)
.find('input');
const workflowJobTemplate = wrapper
.find('TemplateListItem')
.at(3)
.find('input');
jobTemplate.simulate('change', {
target: {
id: 2,
name: 'Job Template 2',
url: '/templates/job_template/2',
type: 'job_template',
summary_fields: { user_capabilities: { delete: true } },
},
});
workflowJobTemplate.simulate('change', {
target: {
id: 4,
name: 'Workflow Job Template 1',
url: '/templates/workflow_job_template/4',
type: 'workflow_job_template',
summary_fields: {
user_capabilities: {
delete: true,
},
},
},
});
wrapper.find('button[aria-label="Delete"]').prop('onClick')();
wrapper.update();
await act(async () => {
await wrapper
.find('button[aria-label="confirm delete"]')
.prop('onClick')();
});
expect(JobTemplatesAPI.destroy).toBeCalledWith(2);
expect(WorkflowJobTemplatesAPI.destroy).toBeCalledWith(4);
});
test('error is shown when template not successfully deleted from api', async () => {
JobTemplatesAPI.destroy.mockRejectedValue( JobTemplatesAPI.destroy.mockRejectedValue(
new Error({ new Error({
response: { response: {
@@ -215,21 +278,35 @@ describe('<TemplatesList />', () => {
}) })
); );
const wrapper = mountWithContexts(<TemplatesList />); const wrapper = mountWithContexts(<TemplatesList />);
wrapper.find('TemplatesList').setState({ await act(async () => {
templates: mockTemplates, await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
itemCount: 1, });
isInitialized: true, const checkBox = wrapper
isModalOpen: true, .find('TemplateListItem')
selected: mockTemplates.slice(0, 1), .at(1)
.find('input');
checkBox.simulate('change', {
target: {
id: 'a',
name: 'Job Template 2',
url: '/templates/job_template/2',
type: 'job_template',
summary_fields: { user_capabilities: { delete: true } },
},
});
wrapper.find('button[aria-label="Delete"]').prop('onClick')();
wrapper.update();
await act(async () => {
await wrapper
.find('button[aria-label="confirm delete"]')
.prop('onClick')();
}); });
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
await waitForElement( await waitForElement(
wrapper, wrapper,
'Modal', 'Modal',
el => el.props().isOpen === true && el.props().title === 'Error!' el => el.props().isOpen === true && el.props().title === 'Error!'
); );
done();
}); });
test('Calls API with jobtemplate__project id', async () => { test('Calls API with jobtemplate__project id', async () => {
const history = createMemoryHistory({ const history = createMemoryHistory({
@@ -252,11 +329,9 @@ describe('<TemplatesList />', () => {
}, },
} }
); );
await waitForElement( await act(async () => {
wrapper, await waitForElement(wrapper, 'ContentLoading', el => el.length === 1);
'TemplatesList', });
el => el.state('hasContentLoading') === true
);
expect(UnifiedJobTemplatesAPI.read).toBeCalledWith({ expect(UnifiedJobTemplatesAPI.read).toBeCalledWith({
jobtemplate__project: '6', jobtemplate__project: '6',
order_by: 'name', order_by: 'name',