1
0
mirror of https://github.com/ansible/awx.git synced 2024-10-31 23:51:09 +03:00

215 templates list skeleton (#251)

* adding package-lock.json

* deleted unsured file

* Removes and unused file

* Fixes errant styling change

* Fixes an error and uses a prop that PF recognizes

* Updates PR to use API Modules

*  Fixes PR Issues

* Addes tests to Templates

* Addresses PR Issues

* Revert package-lock.json
This commit is contained in:
Alex Corey 2019-06-13 11:08:05 -04:00 committed by GitHub
parent ffcb655038
commit 19b41743de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 449 additions and 52 deletions

View File

@ -1,16 +1,12 @@
import React from 'react';
import Templates from '../../src/pages/Templates/Templates';
import { mountWithContexts } from '../enzymeHelpers';
import Templates from '../../src/pages/Templates';
describe('<Templates />', () => {
let pageWrapper;
let pageSections;
let title;
beforeEach(() => {
pageWrapper = mountWithContexts(<Templates />);
pageSections = pageWrapper.find('PageSection');
title = pageWrapper.find('Title');
});
afterEach(() => {
@ -19,11 +15,5 @@ describe('<Templates />', () => {
test('initially renders without crashing', () => {
expect(pageWrapper.length).toBe(1);
expect(pageSections.length).toBe(2);
expect(title.length).toBe(1);
expect(title.props().size).toBe('2xl');
pageSections.forEach(section => {
expect(section.props().variant).toBeDefined();
});
});
});

View File

@ -0,0 +1,11 @@
import React from 'react';
import { mountWithContexts } from '../../enzymeHelpers';
import Templates from '../../../src/pages/Templates/Templates';
describe('<Templates />', () => {
test('initially renders succesfully', () => {
mountWithContexts(
<Templates />
);
});
});

View File

@ -0,0 +1,100 @@
import React from 'react';
import { mountWithContexts } from '../../enzymeHelpers';
import TemplatesList, { _TemplatesList } from '../../../src/pages/Templates/TemplatesList';
jest.mock('../../../src/api');
const setDefaultState = (templatesList) => {
templatesList.setState({
itemCount: mockUnifiedJobTemplatesFromAPI.length,
isLoading: false,
isInitialized: true,
selected: [],
templates: mockUnifiedJobTemplatesFromAPI,
});
templatesList.update();
};
const mockUnifiedJobTemplatesFromAPI = [{
id: 1,
name: 'Template 1',
url: '/templates/job_template/1',
type: 'job_template',
summary_fields: {
inventory: {},
project: {},
}
},
{
id: 2,
name: 'Template 2',
url: '/templates/job_template/2',
type: 'job_template',
summary_fields: {
inventory: {},
project: {},
}
},
{
id: 3,
name: 'Template 3',
url: '/templates/job_template/3',
type: 'job_template',
summary_fields: {
inventory: {},
project: {},
}
}];
describe('<TemplatesList />', () => {
test('initially renders succesfully', () => {
mountWithContexts(
<TemplatesList
match={{ path: '/templates', url: '/templates' }}
location={{ search: '', pathname: '/templates' }}
/>
);
});
test('Templates are retrieved from the api and the components finishes loading', async (done) => {
const readTemplates = jest.spyOn(_TemplatesList.prototype, 'readUnifiedJobTemplates');
const wrapper = mountWithContexts(<TemplatesList />).find('TemplatesList');
expect(wrapper.state('isLoading')).toBe(true);
await expect(readTemplates).toHaveBeenCalled();
wrapper.update();
expect(wrapper.state('isLoading')).toBe(false);
done();
});
test('handleSelect is called when a template list item is selected', async () => {
const handleSelect = jest.spyOn(_TemplatesList.prototype, 'handleSelect');
const wrapper = mountWithContexts(<TemplatesList />);
const templatesList = wrapper.find('TemplatesList');
setDefaultState(templatesList);
expect(templatesList.state('isLoading')).toBe(false);
wrapper.find('DataListCheck#select-jobTemplate-1').props().onChange();
expect(handleSelect).toBeCalled();
templatesList.update();
expect(templatesList.state('selected').length).toBe(1);
});
test('handleSelectAll is called when a template list item is selected', async () => {
const handleSelectAll = jest.spyOn(_TemplatesList.prototype, 'handleSelectAll');
const wrapper = mountWithContexts(<TemplatesList />);
const templatesList = wrapper.find('TemplatesList');
setDefaultState(templatesList);
expect(templatesList.state('isLoading')).toBe(false);
wrapper.find('Checkbox#select-all').props().onChange(true);
expect(handleSelectAll).toBeCalled();
wrapper.update();
expect(templatesList.state('selected').length).toEqual(templatesList.state('templates')
.length);
});
});

View File

@ -0,0 +1,16 @@
import React from 'react';
import { mountWithContexts } from '../../../enzymeHelpers';
import TemplatesListItem from '../../../../src/pages/Templates/components/TemplateListItem';
describe('<TemplatesListItem />', () => {
test('initially render successfully', () => {
mountWithContexts(<TemplatesListItem
template={{
id: 1,
name: 'Template 1',
url: '/templates/job_template/1',
type: 'job_template'
}}
/>);
});
});

View File

@ -4,6 +4,7 @@ import Me from './models/Me';
import Organizations from './models/Organizations';
import Root from './models/Root';
import Teams from './models/Teams';
import UnifiedJobTemplates from './models/UnifiedJobTemplates';
import Users from './models/Users';
const ConfigAPI = new Config();
@ -12,6 +13,7 @@ const MeAPI = new Me();
const OrganizationsAPI = new Organizations();
const RootAPI = new Root();
const TeamsAPI = new Teams();
const UnifiedJobTemplatesAPI = new UnifiedJobTemplates();
const UsersAPI = new Users();
export {
@ -21,5 +23,6 @@ export {
OrganizationsAPI,
RootAPI,
TeamsAPI,
UnifiedJobTemplatesAPI,
UsersAPI
};

View File

@ -0,0 +1,10 @@
import Base from '../Base';
class UnifiedJobTemplates extends Base {
constructor (http) {
super(http);
this.baseUrl = '/api/v2/unified_job_templates/';
}
}
export default UnifiedJobTemplates;

View File

@ -3,26 +3,39 @@ import PropTypes from 'prop-types';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
Button,
ToolbarItem
Button as PFButton,
ToolbarItem as PFToolbarItem
} from '@patternfly/react-core';
import {
BarsIcon,
EqualsIcon,
} from '@patternfly/react-icons';
import styled from 'styled-components';
const ToolbarActiveStyle = {
backgroundColor: '#007bba',
color: 'white',
padding: '0 5px',
};
const Button = styled(PFButton)`
padding: 0;
margin: 0;
height: 30px;
width: 30px;
${props => (props.isActive ? `
background-color: #007bba;
--pf-c-button--m-plain--active--Color: white;
--pf-c-button--m-plain--focus--Color: white;`
: null)};
`;
const ToolbarItem = styled(PFToolbarItem)`
& :not(:last-child) {
margin-right: 20px;
}
`;
class ExpandCollapse extends React.Component {
render () {
const {
isCompact,
onCompact,
onExpand,
isCompact,
i18n
} = this.props;
@ -33,7 +46,7 @@ class ExpandCollapse extends React.Component {
variant="plain"
aria-label={i18n._(t`Collapse`)}
onClick={onCompact}
style={isCompact ? ToolbarActiveStyle : null}
isActive={isCompact}
>
<BarsIcon />
</Button>
@ -43,7 +56,7 @@ class ExpandCollapse extends React.Component {
variant="plain"
aria-label={i18n._(t`Expand`)}
onClick={onExpand}
style={!isCompact ? ToolbarActiveStyle : null}
isActive={!isCompact}
>
<EqualsIcon />
</Button>
@ -56,9 +69,11 @@ class ExpandCollapse extends React.Component {
ExpandCollapse.propTypes = {
onCompact: PropTypes.func.isRequired,
onExpand: PropTypes.func.isRequired,
isCompact: PropTypes.bool.isRequired
isCompact: PropTypes.bool
};
ExpandCollapse.defaultProps = {};
ExpandCollapse.defaultProps = {
isCompact: true
};
export default withI18n()(ExpandCollapse);

View File

@ -44,7 +44,7 @@ import SystemSettings from './pages/SystemSettings';
import UISettings from './pages/UISettings';
import License from './pages/License';
import Teams from './pages/Teams';
import Templates from './pages/Templates';
import Templates from './pages/Templates/Templates';
import Users from './pages/Users';
// eslint-disable-next-line import/prefer-default-export

View File

@ -1,28 +0,0 @@
import React, { Component, Fragment } from 'react';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
PageSection,
PageSectionVariants,
Title,
} from '@patternfly/react-core';
class Templates extends Component {
render () {
const { i18n } = this.props;
const { light, medium } = PageSectionVariants;
return (
<Fragment>
<PageSection variant={light} className="pf-m-condensed">
<Title size="2xl">
{i18n._(t`Templates`)}
</Title>
</PageSection>
<PageSection variant={medium} />
</Fragment>
);
}
}
export default withI18n()(Templates);

View File

@ -0,0 +1,63 @@
import React, { Component, Fragment } from 'react';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { Route, withRouter, Switch } from 'react-router-dom';
import { NetworkProvider } from '../../contexts/Network';
import { withRootDialog } from '../../contexts/RootDialog';
import Breadcrumbs from '../../components/Breadcrumbs/Breadcrumbs';
import TemplatesList from './TemplatesList';
class Templates extends Component {
constructor (props) {
super(props);
const { i18n } = this.props;
this.state = {
breadcrumbConfig: {
'/templates': i18n._(t`Templates`)
}
};
}
render () {
const { match, history, setRootDialogMessage, i18n } = this.props;
const { breadcrumbConfig } = this.state;
return (
<Fragment>
<Breadcrumbs breadcrumbConfig={breadcrumbConfig} />
<Switch>
<Route
path={`${match.path}/:templateType/:id`}
render={({ match: newRouteMatch }) => (
<NetworkProvider
handle404={() => {
history.replace('/templates');
setRootDialogMessage({
title: '404',
bodyText: (
<Fragment>
{i18n._(t`Cannot find template with ID`)}
<strong>{` ${newRouteMatch.params.id}`}</strong>
</Fragment>
),
variant: 'warning'
});
}}
/>
)}
/>
<Route
path={`${match.path}`}
render={() => (
<TemplatesList />
)}
/>
</Switch>
</Fragment>
);
}
}
export { Templates as _Templates };
export default withI18n()(withRootDialog(withRouter(Templates)));

View File

@ -0,0 +1,149 @@
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
Card,
PageSection,
PageSectionVariants,
} from '@patternfly/react-core';
import { withNetwork } from '../../contexts/Network';
import { UnifiedJobTemplatesAPI } from '../../api';
import { getQSConfig, parseNamespacedQueryString } from '../../util/qs';
import DatalistToolbar from '../../components/DataListToolbar';
import PaginatedDataList from '../../components/PaginatedDataList';
import TemplateListItem from './components/TemplateListItem';
// The type value in const QS_CONFIG below does not have a space between job_template and
// workflow_job_template so the params sent to the API match what the api expects.
const QS_CONFIG = getQSConfig('template', {
page: 1,
page_size: 5,
order_by: 'name',
type: 'job_template,workflow_job_template'
});
class TemplatesList extends Component {
constructor (props) {
super(props);
this.state = {
error: null,
isLoading: true,
isInitialized: false,
selected: [],
templates: [],
};
this.readUnifiedJobTemplates = this.readUnifiedJobTemplates.bind(this);
this.handleSelectAll = this.handleSelectAll.bind(this);
this.handleSelect = this.handleSelect.bind(this);
}
componentDidMount () {
this.readUnifiedJobTemplates();
}
componentDidUpdate (prevProps) {
const { location } = this.props;
if (location !== prevProps.location) {
this.readUnifiedJobTemplates();
}
}
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 {
this.setState({ selected: selected.concat(template) });
}
}
async readUnifiedJobTemplates () {
const { handleHttpError, location } = this.props;
this.setState({ error: false, isLoading: true });
const params = parseNamespacedQueryString(QS_CONFIG, location.search);
try {
const { data } = await UnifiedJobTemplatesAPI.read(params);
const { count, results } = data;
const stateToUpdate = {
itemCount: count,
templates: results,
selected: [],
isInitialized: true,
isLoading: false,
};
this.setState(stateToUpdate);
} catch (err) {
handleHttpError(err) || this.setState({ error: true, isLoading: false });
}
}
render () {
const {
error,
isInitialized,
isLoading,
templates,
itemCount,
selected,
} = this.state;
const {
match,
i18n
} = this.props;
const isAllSelected = selected.length === templates.length;
const { medium } = PageSectionVariants;
return (
<PageSection variant={medium}>
<Card>
{isInitialized && (
<PaginatedDataList
items={templates}
itemCount={itemCount}
itemName={i18n._(t`Template`)}
qsConfig={QS_CONFIG}
toolbarColumns={[
{ name: i18n._(t`Name`), key: 'name', isSortable: true },
{ name: i18n._(t`Modified`), key: 'modified', isSortable: true, isNumeric: true },
{ name: i18n._(t`Created`), key: 'created', isSortable: true, isNumeric: true },
]}
renderToolbar={(props) => (
<DatalistToolbar
{...props}
showSelectAll
showExpandCollapse
isAllSelected={isAllSelected}
onSelectAll={this.handleSelectAll}
/>
)}
renderItem={(template) => (
<TemplateListItem
key={template.id}
value={template.name}
template={template}
detailUrl={`${match.url}/${template.type}/${template.id}`}
onSelect={() => this.handleSelect(template)}
isSelected={selected.some(row => row.id === template.id)}
/>
)}
/>
)}
{isLoading ? <div>loading....</div> : ''}
{error ? <div>error</div> : '' }
</Card>
</PageSection>
);
}
}
export { TemplatesList as _TemplatesList };
export default withI18n()(withNetwork(withRouter(TemplatesList)));

View File

@ -0,0 +1,61 @@
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import {
DataListItem,
DataListItemRow,
DataListItemCells,
DataListCheck,
DataListCell as PFDataListCell,
} from '@patternfly/react-core';
import styled from 'styled-components';
import { toTitleCase } from '../../../util/strings';
import VerticalSeparator from '../../../components/VerticalSeparator';
const DataListCell = styled(PFDataListCell)`
display: flex;
align-items: center;
@media screen and (min-width: 768px) {
padding-bottom: 0;
}
`;
class TemplateListItem extends Component {
render () {
const {
template,
isSelected,
onSelect,
} = this.props;
return (
<DataListItem
aria-labelledby={`check-action-${template.id}`}
css="--pf-c-data-list__expandable-content--BoxShadow: none;"
>
<DataListItemRow>
<DataListCheck
id={`select-jobTemplate-${template.id}`}
checked={isSelected}
onChange={onSelect}
aria-labelledby={`check-action-${template.id}`}
/>
<DataListItemCells dataListCells={[
<DataListCell key="divider">
<VerticalSeparator />
<span>
<Link to="/home">
<b>{template.name}</b>
</Link>
</span>
</DataListCell>,
<DataListCell key="type">{toTitleCase(template.type)}</DataListCell>
]}
/>
</DataListItemRow>
</DataListItem>
);
}
}
export { TemplateListItem as _TemplateListItem };
export default TemplateListItem;

View File

@ -14,3 +14,10 @@ export function getArticle (str) {
export function ucFirst (str) {
return `${str[0].toUpperCase()}${str.substr(1)}`;
}
export const toTitleCase = (type) => type
.toLowerCase()
.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');