convert OrganizationList to use PaginatedDataList (#192)

* convert Org list to use PaginatedDataList

* add ToolbarAddButton, ToolbarDeleteButton

* pass full org into OrganizationListItem
This commit is contained in:
Keith Grant 2019-05-07 09:51:50 -04:00 committed by GitHub
parent a011896cc0
commit e7ec1c6ef8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 693 additions and 525 deletions

View File

@ -179,47 +179,24 @@ describe('<DataListToolbar />', () => {
expect(upAlphaIcon.length).toBe(1);
});
test('trash can button triggers correct function', () => {
test('should render additionalControls', () => {
const columns = [{ name: 'Name', key: 'name', isSortable: true }];
const onOpenDeleteModal = jest.fn();
const openDeleteModalButton = 'button[aria-label="Delete"]';
const onSearch = jest.fn();
const onSort = jest.fn();
const onSelectAll = jest.fn();
toolbar = mountWithContexts(
<DataListToolbar
columns={columns}
onOpenDeleteModal={onOpenDeleteModal}
showDelete
disableDelete={false}
/>
);
toolbar.find(openDeleteModalButton).simulate('click');
expect(onOpenDeleteModal).toHaveBeenCalled();
});
test('Tooltip says "Select a row to delete" when trash can icon is disabled', () => {
toolbar = mountWithContexts(
<DataListToolbar
columns={[{ name: 'Name', key: 'name', isSortable: true }]}
showDelete
deleteTooltip="Select a row to delete"
onSearch={onSearch}
onSort={onSort}
onSelectAll={onSelectAll}
additionalControls={[<button key="1" id="test" type="button">click</button>]}
/>
);
const toolTip = toolbar.find('.pf-c-tooltip__content');
toolTip.simulate('mouseover');
expect(toolTip.text()).toBe('Select a row to delete');
});
test('Delete Org tooltip says "Delete" when trash can icon is enabled', () => {
toolbar = mountWithContexts(
<DataListToolbar
columns={[{ name: 'Name', key: 'name', isSortable: true }]}
showDelete
deleteTooltip="Delete"
/>
);
const toolTip = toolbar.find('.pf-c-tooltip__content');
toolTip.simulate('mouseover');
expect(toolTip.text()).toBe('Delete');
const button = toolbar.find('#test');
expect(button).toHaveLength(1);
expect(button.text()).toEqual('click');
});
});

View File

@ -0,0 +1,76 @@
import React from 'react';
import { mountWithContexts } from '../../enzymeHelpers';
import { ToolbarDeleteButton } from '../../../src/components/PaginatedDataList';
const itemA = {
id: 1,
name: 'Foo',
summary_fields: { user_capabilities: { delete: true } },
};
const itemB = {
id: 1,
name: 'Foo',
summary_fields: { user_capabilities: { delete: false } },
};
describe('<ToolbarDeleteButton />', () => {
test('should render button', () => {
const wrapper = mountWithContexts(
<ToolbarDeleteButton
onDelete={() => {}}
itemsToDelete={[]}
/>
);
expect(wrapper.find('button')).toHaveLength(1);
expect(wrapper.find('ToolbarDeleteButton')).toMatchSnapshot();
});
test('should open confirmation modal', () => {
const wrapper = mountWithContexts(
<ToolbarDeleteButton
onDelete={() => {}}
itemsToDelete={[itemA]}
/>
);
wrapper.find('button').simulate('click');
expect(wrapper.find('ToolbarDeleteButton').state('isModalOpen'))
.toBe(true);
wrapper.update();
expect(wrapper.find('Modal')).toHaveLength(1);
});
test('should invoke onDelete prop', () => {
const onDelete = jest.fn();
const wrapper = mountWithContexts(
<ToolbarDeleteButton
onDelete={onDelete}
itemsToDelete={[itemA]}
/>
);
wrapper.find('ToolbarDeleteButton').setState({ isModalOpen: true });
wrapper.find('button.pf-m-danger').simulate('click');
expect(onDelete).toHaveBeenCalled();
expect(wrapper.find('ToolbarDeleteButton').state('isModalOpen')).toBe(false);
});
test('should disable button when no delete permissions', () => {
const wrapper = mountWithContexts(
<ToolbarDeleteButton
onDelete={() => {}}
itemsToDelete={[itemB]}
/>
);
expect(wrapper.find('button[disabled]')).toHaveLength(1);
});
test('should render tooltip', () => {
const wrapper = mountWithContexts(
<ToolbarDeleteButton
onDelete={() => {}}
itemsToDelete={[itemA]}
/>
);
expect(wrapper.find('Tooltip')).toHaveLength(1);
expect(wrapper.find('Tooltip').prop('content')).toEqual('Delete');
});
});

View File

@ -1,8 +1,8 @@
import React from 'react';
import { createMemoryHistory } from 'history';
import { mountWithContexts } from '../enzymeHelpers';
import { sleep } from '../testUtils';
import PaginatedDataList from '../../src/components/PaginatedDataList';
import { mountWithContexts } from '../../enzymeHelpers';
import { sleep } from '../../testUtils';
import PaginatedDataList from '../../../src/components/PaginatedDataList';
const mockData = [
{ id: 1, name: 'one', url: '/org/team/1' },

View File

@ -0,0 +1,25 @@
import React from 'react';
import { mountWithContexts } from '../../enzymeHelpers';
import { ToolbarAddButton } from '../../../src/components/PaginatedDataList';
describe('<ToolbarAddButton />', () => {
test('should render button', () => {
const onClick = jest.fn();
const wrapper = mountWithContexts(
<ToolbarAddButton onClick={onClick} />
);
const button = wrapper.find('button');
expect(button).toHaveLength(1);
button.simulate('click');
expect(onClick).toHaveBeenCalled();
});
test('should render link', () => {
const wrapper = mountWithContexts(
<ToolbarAddButton linkTo="/foo" />
);
const link = wrapper.find('Link');
expect(link).toHaveLength(1);
expect(link.prop('to')).toBe('/foo');
});
});

View File

@ -0,0 +1,168 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<ToolbarDeleteButton /> should render button 1`] = `
<ToolbarDeleteButton
itemName="item"
itemsToDelete={Array []}
onDelete={[Function]}
>
<I18n
update={true}
withHash={true}
>
<Tooltip
appendTo={[Function]}
className={null}
content="Select a row to delete"
enableFlip={true}
entryDelay={500}
exitDelay={500}
maxWidth="18.75rem"
position="left"
trigger="mouseenter focus"
zIndex={9999}
>
<Tippy
animateFill={false}
appendTo={[Function]}
content={
<div
className="pf-c-tooltip"
role="tooltip"
>
<TooltipArrow
className={null}
/>
<TooltipContent
className={null}
>
Select a row to delete
</TooltipContent>
</div>
}
delay={
Array [
500,
500,
]
}
distance={15}
flip={true}
lazy={true}
maxWidth="18.75rem"
onCreate={[Function]}
performance={true}
placement="left"
popperOptions={
Object {
"modifiers": Object {
"hide": Object {
"enabled": true,
},
"preventOverflow": Object {
"enabled": true,
},
},
}
}
theme="pf-tippy"
trigger="mouseenter focus"
zIndex={9999}
>
<Button
aria-label="Delete"
className="awx-ToolBarBtn"
component="button"
isActive={false}
isBlock={false}
isDisabled={true}
isFocus={false}
isHover={false}
onClick={[Function]}
type="button"
variant="plain"
>
<button
aria-disabled={null}
aria-label="Delete"
className="pf-c-button pf-m-plain pf-m-disabled awx-ToolBarBtn"
disabled={true}
onClick={[Function]}
tabIndex={null}
type="button"
>
<TrashAltIcon
className="awx-ToolBarTrashCanIcon"
color="currentColor"
size="sm"
title={null}
>
<svg
aria-hidden={true}
aria-labelledby={null}
className="awx-ToolBarTrashCanIcon"
fill="currentColor"
height="1em"
role="img"
style={
Object {
"verticalAlign": "-0.125em",
}
}
viewBox="0 0 448 512"
width="1em"
>
<path
d="M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z"
transform=""
/>
</svg>
</TrashAltIcon>
</button>
</Button>
<Portal
containerInfo={
<div>
<div
class="pf-c-tooltip"
role="tooltip"
>
<div
class="pf-c-tooltip__arrow"
/>
<div
class="pf-c-tooltip__content"
>
Select a row to delete
</div>
</div>
</div>
}
>
<div
className="pf-c-tooltip"
role="tooltip"
>
<TooltipArrow
className={null}
>
<div
className="pf-c-tooltip__arrow"
/>
</TooltipArrow>
<TooltipContent
className={null}
>
<div
className="pf-c-tooltip__content"
>
Select a row to delete
</div>
</TooltipContent>
</div>
</Portal>
</Tippy>
</Tooltip>
</I18n>
</ToolbarDeleteButton>
`;

View File

@ -9,7 +9,19 @@ describe('<OrganizationListItem />', () => {
mountWithContexts(
<I18nProvider>
<MemoryRouter initialEntries={['/organizations']} initialIndex={0}>
<OrganizationListItem />
<OrganizationListItem
organization={{
id: 1,
name: 'Org',
summary_fields: { related_field_counts: {
users: 1,
teams: 1,
} }
}}
detailUrl="/organization/1"
isSelected
onSelect={() => {}}
/>
</MemoryRouter>
</I18nProvider>
);

View File

@ -109,8 +109,9 @@ exports[`<OrganizationNotifications /> initially renders succesfully 1`] = `
>
<Route>
<PaginatedDataList
additionalControls={null}
additionalControls={Array []}
history={"/history/"}
isAllSelected={false}
itemCount={2}
itemName="notification"
itemNamePlural=""
@ -146,6 +147,7 @@ exports[`<OrganizationNotifications /> initially renders succesfully 1`] = `
"url": "",
}
}
onSelectAll={null}
queryParams={
Object {
"order_by": "name",
@ -154,6 +156,7 @@ exports[`<OrganizationNotifications /> initially renders succesfully 1`] = `
}
}
renderItem={[Function]}
showSelectAll={false}
toolbarColumns={
Array [
Object {
@ -181,9 +184,7 @@ exports[`<OrganizationNotifications /> initially renders succesfully 1`] = `
withHash={true}
>
<DataListToolbar
add={null}
addBtnToolTipContent="Add"
addUrl={null}
additionalControls={Array []}
columns={
Array [
Object {
@ -205,19 +206,14 @@ exports[`<OrganizationNotifications /> initially renders succesfully 1`] = `
},
]
}
deleteTooltip="Delete"
disableDelete={true}
isAllSelected={false}
isCompact={false}
noLeftMargin={false}
onCompact={null}
onExpand={null}
onOpenDeleteModal={null}
onSearch={[Function]}
onSelectAll={null}
onSort={[Function]}
showAdd={false}
showDelete={false}
showSelectAll={false}
sortOrder="ascending"
sortedColumnKey="name"
@ -919,20 +915,8 @@ exports[`<OrganizationNotifications /> initially renders succesfully 1`] = `
</Toolbar>
</div>
</LevelItem>
<LevelItem
style={
Object {
"display": "flex",
}
}
>
<div
style={
Object {
"display": "flex",
}
}
/>
<LevelItem>
<div />
</LevelItem>
</div>
</Level>

View File

@ -5,9 +5,11 @@ import OrganizationsList, { _OrganizationsList } from '../../../../src/pages/Org
const mockAPIOrgsList = {
data: {
count: 3,
results: [{
name: 'Organization 0',
id: 1,
url: '/organizations/1',
summary_fields: {
related_field_counts: {
teams: 3,
@ -21,6 +23,7 @@ const mockAPIOrgsList = {
{
name: 'Organization 1',
id: 2,
url: '/organizations/2',
summary_fields: {
related_field_counts: {
teams: 2,
@ -34,6 +37,7 @@ const mockAPIOrgsList = {
{
name: 'Organization 2',
id: 3,
url: '/organizations/3',
summary_fields: {
related_field_counts: {
teams: 5,
@ -50,7 +54,7 @@ const mockAPIOrgsList = {
warningMsg: 'message'
};
describe('<_OrganizationsList />', () => {
describe('<OrganizationsList />', () => {
let wrapper;
let api;
@ -67,75 +71,42 @@ describe('<_OrganizationsList />', () => {
);
});
test('Puts 1 selected Org in state when onSelect is called.', () => {
test('Puts 1 selected Org in state when handleSelect is called.', () => {
wrapper = mountWithContexts(
<OrganizationsList />
).find('OrganizationsList');
wrapper.setState({
results: mockAPIOrgsList.data.results
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true
});
wrapper.update();
expect(wrapper.state('selected').length).toBe(0);
wrapper.instance().onSelect(mockAPIOrgsList.data.results.slice(0, 1));
wrapper.instance().handleSelect(mockAPIOrgsList.data.results.slice(0, 1));
expect(wrapper.state('selected').length).toBe(1);
});
test('Puts all Orgs in state when onSelectAll is called.', () => {
wrapper = mountWithContexts(
<OrganizationsList />
).find('OrganizationsList');
wrapper.setState(
mockAPIOrgsList.data
);
expect(wrapper.state('selected').length).toBe(0);
wrapper.instance().onSelectAll(true);
expect(wrapper.find('OrganizationsList').state().selected.length).toEqual(wrapper.state().results.length);
});
test('selected is > 0 when close modal button is clicked.', () => {
test('Puts all Orgs in state when handleSelectAll is called.', () => {
wrapper = mountWithContexts(
<OrganizationsList />
);
wrapper.find('OrganizationsList').setState({
results: mockAPIOrgsList.data.results,
isModalOpen: mockAPIOrgsList.isModalOpen,
selected: mockAPIOrgsList.data.results
const list = wrapper.find('OrganizationsList');
list.setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true
});
const component = wrapper.find('OrganizationsList');
wrapper.find('DataListToolbar').prop('onOpenDeleteModal')();
expect(list.state('selected').length).toBe(0);
list.instance().handleSelectAll(true);
wrapper.update();
const button = wrapper.find('ModalBoxCloseButton');
button.prop('onClose')();
wrapper.update();
expect(component.state('isModalOpen')).toBe(false);
expect(component.state('selected').length).toBeGreaterThan(0);
wrapper.unmount();
});
test('selected is > 0 when cancel modal button is clicked.', () => {
wrapper = mountWithContexts(
<OrganizationsList />
);
wrapper.find('OrganizationsList').setState({
results: mockAPIOrgsList.data.results,
isModalOpen: mockAPIOrgsList.isModalOpen,
selected: mockAPIOrgsList.data.results
});
const component = wrapper.find('OrganizationsList');
wrapper.find('DataListToolbar').prop('onOpenDeleteModal')();
wrapper.update();
const button = wrapper.find('ModalBoxFooter').find('button').at(1);
button.prop('onClick')();
wrapper.update();
expect(component.state('isModalOpen')).toBe(false);
expect(component.state('selected').length).toBeGreaterThan(0);
wrapper.unmount();
expect(list.state('selected').length)
.toEqual(list.state('organizations').length);
});
test('api is called to delete Orgs for each org in selected.', () => {
const fetchOrganizations = jest.fn(() => wrapper.find('OrganizationsList').setState({
results: []
organizations: []
}));
wrapper = mountWithContexts(
<OrganizationsList
@ -146,15 +117,13 @@ describe('<_OrganizationsList />', () => {
);
const component = wrapper.find('OrganizationsList');
wrapper.find('OrganizationsList').setState({
results: mockAPIOrgsList.data.results,
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
isModalOpen: mockAPIOrgsList.isModalOpen,
selected: mockAPIOrgsList.data.results
});
wrapper.find('DataListToolbar').prop('onOpenDeleteModal')();
wrapper.update();
const button = wrapper.find('ModalBoxFooter').find('button').at(0);
button.simulate('click');
wrapper.update();
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
expect(api.destroyOrganization).toHaveBeenCalledTimes(component.state('selected').length);
});
@ -167,7 +136,9 @@ describe('<_OrganizationsList />', () => {
}
);
wrapper.find('OrganizationsList').setState({
results: mockAPIOrgsList.data.results,
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
selected: mockAPIOrgsList.data.results.slice(0, 1)
});
const component = wrapper.find('OrganizationsList');
@ -193,27 +164,6 @@ describe('<_OrganizationsList />', () => {
expect(history.location.search).toBe('?order_by=modified&page=1&page_size=5');
});
test('onSort sends the correct information to fetchOrganizations', () => {
const history = createMemoryHistory({
initialEntries: ['organizations?order_by=name&page=1&page_size=5'],
});
const fetchOrganizations = jest.spyOn(_OrganizationsList.prototype, 'fetchOrganizations');
wrapper = mountWithContexts(
<OrganizationsList />, {
context: {
router: { history }
}
}
);
const component = wrapper.find('OrganizationsList');
component.instance().onSort('modified', 'ascending');
expect(fetchOrganizations).toBeCalledWith({
page: 1,
page_size: 5,
order_by: 'modified'
});
});
test('error is thrown when org not successfully deleted from api', async () => {
const history = createMemoryHistory({
initialEntries: ['organizations?order_by=name&page=1&page_size=5'],
@ -227,7 +177,9 @@ describe('<_OrganizationsList />', () => {
}
);
await wrapper.setState({
results: mockAPIOrgsList.data.results,
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
selected: [...mockAPIOrgsList.data.results].push({
name: 'Organization 6',
id: 'a',

View File

@ -1,24 +1,15 @@
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { I18n, i18nMark } from '@lingui/react';
import { I18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
Button,
Checkbox,
Level,
LevelItem,
Toolbar,
ToolbarGroup,
ToolbarItem,
Tooltip,
} from '@patternfly/react-core';
import {
TrashAltIcon,
PlusIcon,
} from '@patternfly/react-icons';
import {
Link
} from 'react-router-dom';
import ExpandCollapse from '../ExpandCollapse';
import Search from '../Search';
@ -28,12 +19,8 @@ import VerticalSeparator from '../VerticalSeparator';
class DataListToolbar extends React.Component {
render () {
const {
add,
addBtnToolTipContent,
addUrl,
columns,
deleteTooltip,
disableDelete,
showSelectAll,
isAllSelected,
isCompact,
noLeftMargin,
@ -41,18 +28,12 @@ class DataListToolbar extends React.Component {
onSearch,
onCompact,
onExpand,
onOpenDeleteModal,
onSelectAll,
showAdd,
showDelete,
showSelectAll,
sortOrder,
sortedColumnKey,
additionalControls,
} = this.props;
const deleteIconStyling = disableDelete ? 'awx-ToolBarBtn awx-ToolBarBtn--disabled'
: 'awx-ToolBarBtn';
const showExpandCollapse = (onCompact && onExpand);
return (
<I18n>
@ -96,9 +77,9 @@ class DataListToolbar extends React.Component {
/>
</ToolbarItem>
</ToolbarGroup>
{ (showExpandCollapse || showDelete || addUrl || add) && (
{ (showExpandCollapse || additionalControls.length) ? (
<VerticalSeparator />
)}
) : null}
{showExpandCollapse && (
<Fragment>
<ToolbarGroup>
@ -108,50 +89,15 @@ class DataListToolbar extends React.Component {
onExpand={onExpand}
/>
</ToolbarGroup>
{ (showDelete || addUrl || add) && (
{ additionalControls && (
<VerticalSeparator />
)}
</Fragment>
)}
</Toolbar>
</LevelItem>
<LevelItem style={{ display: 'flex' }}>
{showDelete && (
<Tooltip
content={deleteTooltip}
position="top"
>
<div
className={deleteIconStyling}
>
<Button
variant="plain"
aria-label={i18n._(t`Delete`)}
onClick={onOpenDeleteModal}
isDisabled={disableDelete}
>
<TrashAltIcon className="awx-ToolBarTrashCanIcon" />
</Button>
</div>
</Tooltip>
)}
{showAdd && addUrl && (
<Link to={addUrl}>
<Tooltip
content={addBtnToolTipContent}
>
<Button
variant="primary"
aria-label={i18n._(t`Add`)}
>
<PlusIcon />
</Button>
</Tooltip>
</Link>
)}
{showAdd && add && (
<Fragment>{add}</Fragment>
)}
<LevelItem>
{additionalControls}
</LevelItem>
</Level>
</div>
@ -162,48 +108,34 @@ class DataListToolbar extends React.Component {
}
DataListToolbar.propTypes = {
add: PropTypes.node,
addBtnToolTipContent: PropTypes.string,
addUrl: PropTypes.string,
columns: PropTypes.arrayOf(PropTypes.object).isRequired,
deleteTooltip: PropTypes.node,
disableDelete: PropTypes.bool,
showSelectAll: PropTypes.bool,
isAllSelected: PropTypes.bool,
isCompact: PropTypes.bool,
noLeftMargin: PropTypes.bool,
onCompact: PropTypes.func,
onExpand: PropTypes.func,
onOpenDeleteModal: PropTypes.func,
onSearch: PropTypes.func,
onSelectAll: PropTypes.func,
onSort: PropTypes.func,
showAdd: PropTypes.bool,
showDelete: PropTypes.bool,
showSelectAll: PropTypes.bool,
sortOrder: PropTypes.string,
sortedColumnKey: PropTypes.string,
additionalControls: PropTypes.arrayOf(PropTypes.node),
};
DataListToolbar.defaultProps = {
add: null,
addBtnToolTipContent: i18nMark('Add'),
addUrl: null,
deleteTooltip: i18nMark('Delete'),
disableDelete: true,
showSelectAll: false,
isAllSelected: false,
isCompact: false,
noLeftMargin: false,
onCompact: null,
onExpand: null,
onOpenDeleteModal: null,
onSearch: null,
onSelectAll: null,
onSort: null,
showAdd: false,
showDelete: false,
showSelectAll: false,
sortOrder: 'ascending',
sortedColumnKey: 'name',
additionalControls: [],
};
export default DataListToolbar;

View File

@ -81,32 +81,34 @@
font-size: 18px;
}
.awx-ToolBarBtn{
.awx-ToolBarBtn {
width: 30px;
display: flex;
justify-content: center;
margin-right: 20px;
border-radius: 3px;
&[disabled] {
cursor: not-allowed;
}
}
.awx-ToolBarBtn:hover{
.awx-ToolBarBtn:hover {
.awx-ToolBarTrashCanIcon {
color:white;
color: white;
}
background-color:#d9534f;
}
.awx-ToolBarBtn--disabled:hover{
.awx-ToolBarBtn[disabled]:hover {
.awx-ToolBarTrashCanIcon {
color: #d2d2d2;
}
background-color:white;
cursor: not-allowed;
background-color: white;
}
.pf-l-toolbar >div{
.pf-l-toolbar > div {
&:last-child{
display:none;
}
}

View File

@ -1,5 +1,5 @@
import React, { Fragment } from 'react';
import PropTypes, { arrayOf, shape, string, bool } from 'prop-types';
import PropTypes, { arrayOf, shape, string, bool, node } from 'prop-types';
import {
DataList,
DataListItem,
@ -99,6 +99,9 @@ class PaginatedDataList extends React.Component {
additionalControls,
itemName,
itemNamePlural,
showSelectAll,
isAllSelected,
onSelectAll,
} = this.props;
const { error } = this.state;
const [orderBy, sortOrder] = this.getSortOrder();
@ -146,8 +149,10 @@ class PaginatedDataList extends React.Component {
columns={toolbarColumns}
onSearch={() => { }}
onSort={this.handleSort}
showAdd={!!additionalControls}
add={additionalControls}
showSelectAll={showSelectAll}
isAllSelected={isAllSelected}
onSelectAll={onSelectAll}
additionalControls={additionalControls}
/>
<DataList aria-label={i18n._(t`${ucFirst(pluralize(itemName))} List`)}>
{items.map(item => (renderItem ? renderItem(item) : (
@ -216,7 +221,10 @@ PaginatedDataList.propTypes = {
key: string.isRequired,
isSortable: bool,
})),
additionalControls: PropTypes.node,
additionalControls: arrayOf(node),
showSelectAll: PropTypes.bool,
isAllSelected: PropTypes.bool,
onSelectAll: PropTypes.func,
};
PaginatedDataList.defaultProps = {
@ -224,9 +232,12 @@ PaginatedDataList.defaultProps = {
toolbarColumns: [
{ name: i18nMark('Name'), key: 'name', isSortable: true },
],
additionalControls: null,
additionalControls: [],
itemName: 'item',
itemNamePlural: '',
showSelectAll: false,
isAllSelected: false,
onSelectAll: null,
};
export { PaginatedDataList as _PaginatedDataList };

View File

@ -0,0 +1,53 @@
import React from 'react';
import { string, func } from 'prop-types';
import { Link } from 'react-router-dom';
import { Button } from '@patternfly/react-core';
import { PlusIcon } from '@patternfly/react-icons';
import { I18n } from '@lingui/react';
import { t } from '@lingui/macro';
function ToolbarAddButton ({ linkTo, onClick }) {
if (!linkTo && !onClick) {
throw new Error('ToolbarAddButton requires either `linkTo` or `onClick` prop');
}
if (linkTo) {
// TODO: This should only be a <Link> (no <Button>) but CSS is off
return (
<I18n>
{({ i18n }) => (
<Link to={linkTo} className="pf-c-button pf-m-primary">
<Button
variant="primary"
aria-label={i18n._(t`Add`)}
>
<PlusIcon />
</Button>
</Link>
)}
</I18n>
);
}
return (
<I18n>
{({ i18n }) => (
<Button
variant="primary"
aria-label={i18n._(t`Add`)}
onClick={onClick}
>
<PlusIcon />
</Button>
)}
</I18n>
);
}
ToolbarAddButton.propTypes = {
linkTo: string,
onClick: func,
};
ToolbarAddButton.defaultProps = {
linkTo: null,
onClick: null
};
export default ToolbarAddButton;

View File

@ -0,0 +1,162 @@
import React, { Fragment } from 'react';
import { func, bool, number, string, arrayOf, shape } from 'prop-types';
import { Button, Tooltip } from '@patternfly/react-core';
import { TrashAltIcon } from '@patternfly/react-icons';
import { I18n, i18nMark } from '@lingui/react';
import { Trans, t } from '@lingui/macro';
import AlertModal from '../AlertModal';
import { pluralize } from '../../util/strings';
const ItemToDelete = shape({
id: number.isRequired,
name: string.isRequired,
summary_fields: shape({
user_capabilities: shape({
delete: bool.isRequired,
}).isRequired,
}).isRequired,
});
function cannotDelete (item) {
return !item.summary_fields.user_capabilities.delete;
}
class ToolbarDeleteButton extends React.Component {
static propTypes = {
onDelete: func.isRequired,
itemsToDelete: arrayOf(ItemToDelete).isRequired,
itemName: string,
};
static defaultProps = {
itemName: 'item',
};
constructor (props) {
super(props);
this.state = {
isModalOpen: false,
};
this.handleConfirmDelete = this.handleConfirmDelete.bind(this);
this.handleCancelDelete = this.handleCancelDelete.bind(this);
this.handleDelete = this.handleDelete.bind(this);
}
handleConfirmDelete () {
this.setState({ isModalOpen: true });
}
handleCancelDelete () {
this.setState({ isModalOpen: false, });
}
handleDelete () {
const { onDelete } = this.props;
onDelete();
this.setState({ isModalOpen: false });
}
renderTooltip () {
const { itemsToDelete, itemName } = this.props;
if (itemsToDelete.some(cannotDelete)) {
return (
<div>
<Trans>
You dont have permission to delete the following
{' '}
{pluralize(itemName)}
:
</Trans>
{itemsToDelete
.filter(cannotDelete)
.map(item => (
<div key={item.id}>
{item.name}
</div>
))
}
</div>
);
}
if (itemsToDelete.length) {
return i18nMark('Delete');
}
return i18nMark('Select a row to delete');
}
render () {
const { itemsToDelete, itemName } = this.props;
const { isModalOpen } = this.state;
const isDisabled = itemsToDelete.length === 0
|| itemsToDelete.some(cannotDelete);
return (
<I18n>
{({ i18n }) => (
<Fragment>
<Tooltip
content={this.renderTooltip()}
position="left"
>
<Button
className="awx-ToolBarBtn"
variant="plain"
aria-label={i18n._(t`Delete`)}
onClick={this.handleConfirmDelete}
isDisabled={isDisabled}
>
<TrashAltIcon className="awx-ToolBarTrashCanIcon" />
</Button>
</Tooltip>
{ isModalOpen && (
<AlertModal
variant="danger"
title={itemsToDelete === 1
? i18n._(t`Delete ${itemName}`)
: i18n._(t`Delete ${pluralize(itemName)}`)
}
isOpen={isModalOpen}
onClose={this.handleCancelDelete}
actions={[
<Button
key="delete"
variant="danger"
aria-label={i18n._(t`confirm delete`)}
onClick={this.handleDelete}
>
{i18n._(t`Delete`)}
</Button>,
<Button
key="cancel"
variant="secondary"
aria-label={i18n._(t`cancel delete`)}
onClick={this.handleCancelDelete}
>
{i18n._(t`Cancel`)}
</Button>
]}
>
{i18n._(t`Are you sure you want to delete:`)}
<br />
{itemsToDelete.map((item) => (
<span key={item.id}>
<strong>
{item.name}
</strong>
<br />
</span>
))}
<br />
</AlertModal>
)}
</Fragment>
)}
</I18n>
);
}
}
export default ToolbarDeleteButton;

View File

@ -1,3 +1,5 @@
import PaginatedDataList from './PaginatedDataList';
export default PaginatedDataList;
export { default as ToolbarDeleteButton } from './ToolbarDeleteButton';
export { default as ToolbarAddButton } from './ToolbarAddButton';

View File

@ -1,4 +1,5 @@
import React from 'react';
import { string, bool, func } from 'prop-types';
import { Trans } from '@lingui/macro';
import {
Badge,
@ -13,24 +14,29 @@ import {
} from 'react-router-dom';
import VerticalSeparator from '../../../components/VerticalSeparator';
import { Organization } from '../../../types';
class OrganizationListItem extends React.Component {
static propTypes = {
organization: Organization.isRequired,
detailUrl: string.isRequired,
isSelected: bool.isRequired,
onSelect: func.isRequired
}
render () {
const {
itemId,
name,
memberCount,
teamCount,
organization,
isSelected,
onSelect,
detailUrl,
} = this.props;
const labelId = `check-action-${itemId}`;
const labelId = `check-action-${organization.id}`;
return (
<DataListItem key={itemId} aria-labelledby={labelId}>
<DataListItem key={organization.id} aria-labelledby={labelId}>
<DataListItemRow>
<DataListCheck
id={`select-organization-${itemId}`}
id={`select-organization-${organization.id}`}
checked={isSelected}
onChange={onSelect}
aria-labelledby={labelId}
@ -44,7 +50,7 @@ class OrganizationListItem extends React.Component {
<Link
to={`${detailUrl}`}
>
<b>{name}</b>
<b>{organization.name}</b>
</Link>
</span>
</DataListCell>,
@ -52,13 +58,13 @@ class OrganizationListItem extends React.Component {
<span className="awx-c-list-group">
<Trans>Members</Trans>
<Badge className="awx-c-list-group--badge" isRead>
{memberCount}
{organization.summary_fields.related_field_counts.users}
</Badge>
</span>
<span className="awx-c-list-group">
<Trans>Teams</Trans>
<Badge className="awx-c-list-group--badge" isRead>
{teamCount}
{organization.summary_fields.related_field_counts.teams}
</Badge>
</span>
</DataListCell>

View File

@ -1,10 +1,7 @@
import React, { Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import { I18n, i18nMark } from '@lingui/react';
import { t } from '@lingui/macro';
import { Button } from '@patternfly/react-core';
import { PlusIcon } from '@patternfly/react-icons';
import PaginatedDataList from '../../../../components/PaginatedDataList';
import { i18nMark } from '@lingui/react';
import PaginatedDataList, { ToolbarAddButton } from '../../../../components/PaginatedDataList';
import OrganizationAccessItem from '../../components/OrganizationAccessItem';
import DeleteRoleConfirmationModal from '../../components/DeleteRoleConfirmationModal';
import AddResourceRole from '../../../../components/AddRole/AddResourceRole';
@ -184,19 +181,9 @@ class OrganizationAccess extends React.Component {
{ name: i18nMark('Username'), key: 'username', isSortable: true },
{ name: i18nMark('Last Name'), key: 'last_name', isSortable: true },
]}
additionalControls={canEdit ? (
<I18n>
{({ i18n }) => (
<Button
variant="primary"
aria-label={i18n._(t`Add Access Role`)}
onClick={this.toggleAddModal}
>
<PlusIcon />
</Button>
)}
</I18n>
) : null}
additionalControls={canEdit ? [
<ToolbarAddButton key="add" onClick={this.toggleAddModal} />
] : null}
renderItem={accessRecord => (
<OrganizationAccessItem
key={accessRecord.id}

View File

@ -50,7 +50,7 @@ class OrganizationTeams extends React.Component {
async readOrganizationTeamsList () {
const { api, handleHttpError, id } = this.props;
const params = this.getQueryParams();
this.setState({ isLoading: true });
this.setState({ isLoading: true, error: null });
try {
const {
data: { count = 0, results = [] },

View File

@ -1,38 +1,19 @@
import React, {
Component,
Fragment
} from 'react';
import {
withRouter
} from 'react-router-dom';
import { I18n, i18nMark } from '@lingui/react';
import { Trans, t } from '@lingui/macro';
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { i18nMark } from '@lingui/react';
import {
Card,
EmptyState,
EmptyStateIcon,
EmptyStateBody,
PageSection,
PageSectionVariants,
Title,
Button
} from '@patternfly/react-core';
import { CubesIcon } from '@patternfly/react-icons';
import { withNetwork } from '../../../contexts/Network';
import DataListToolbar from '../../../components/DataListToolbar';
import PaginatedDataList, {
ToolbarDeleteButton,
ToolbarAddButton
} from '../../../components/PaginatedDataList';
import OrganizationListItem from '../components/OrganizationListItem';
import Pagination from '../../../components/Pagination';
import AlertModal from '../../../components/AlertModal';
import {
encodeQueryString,
parseQueryString,
} from '../../../util/qs';
import { encodeQueryString, parseQueryString } from '../../../util/qs';
const COLUMNS = [
{ name: i18nMark('Name'), key: 'name', isSortable: true },
@ -40,7 +21,7 @@ const COLUMNS = [
{ name: i18nMark('Created'), key: 'created', isSortable: true, isNumeric: true },
];
const DEFAULT_PARAMS = {
const DEFAULT_QUERY_PARAMS = {
page: 1,
page_size: 5,
order_by: 'name',
@ -50,115 +31,60 @@ class OrganizationsList extends Component {
constructor (props) {
super(props);
const { page, page_size } = this.getQueryParams();
this.state = {
page,
page_size,
sortedColumnKey: 'name',
sortOrder: 'ascending',
count: null,
error: null,
loading: true,
results: [],
isLoading: true,
isInitialized: false,
organizations: [],
selected: [],
isModalOpen: false,
};
this.onSearch = this.onSearch.bind(this);
this.getQueryParams = this.getQueryParams.bind(this);
this.onSort = this.onSort.bind(this);
this.onSetPage = this.onSetPage.bind(this);
this.onSelectAll = this.onSelectAll.bind(this);
this.onSelect = this.onSelect.bind(this);
this.handleSelectAll = this.handleSelectAll.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.updateUrl = this.updateUrl.bind(this);
this.fetchOptionsOrganizations = this.fetchOptionsOrganizations.bind(this);
this.fetchOrganizations = this.fetchOrganizations.bind(this);
this.handleOrgDelete = this.handleOrgDelete.bind(this);
this.handleOpenOrgDeleteModal = this.handleOpenOrgDeleteModal.bind(this);
this.handleClearOrgDeleteModal = this.handleClearOrgDeleteModal.bind(this);
}
componentDidMount () {
const queryParams = this.getQueryParams();
this.fetchOptionsOrganizations();
this.fetchOrganizations(queryParams);
this.fetchOrganizations();
}
onSearch () {
const { sortedColumnKey, sortOrder } = this.state;
this.onSort(sortedColumnKey, sortOrder);
}
onSort (sortedColumnKey, sortOrder) {
const { page_size } = this.state;
let order_by = sortedColumnKey;
if (sortOrder === 'descending') {
order_by = `-${order_by}`;
componentDidUpdate (prevProps) {
const { location } = this.props;
if (location !== prevProps.location) {
this.fetchOrganizations();
}
const queryParams = this.getQueryParams({ order_by, page_size });
this.fetchOrganizations(queryParams);
}
onSetPage (pageNumber, pageSize) {
const page = parseInt(pageNumber, 10);
const page_size = parseInt(pageSize, 10);
const queryParams = this.getQueryParams({ page, page_size });
this.fetchOrganizations(queryParams);
}
onSelectAll (isSelected) {
const { results } = this.state;
const selected = isSelected ? results : [];
handleSelectAll (isSelected) {
const { organizations } = this.state;
const selected = isSelected ? [...organizations] : [];
this.setState({ selected });
}
onSelect (row) {
handleSelect (row) {
const { selected } = this.state;
const isSelected = selected.some(s => s.id === row.id);
if (isSelected) {
if (selected.some(s => s.id === row.id)) {
this.setState({ selected: selected.filter(s => s.id !== row.id) });
} else {
this.setState({ selected: selected.concat(row) });
}
}
getQueryParams (overrides = {}) {
getQueryParams () {
const { location } = this.props;
const { search } = location;
const searchParams = parseQueryString(location.search.substring(1));
const searchParams = parseQueryString(search.substring(1));
return Object.assign({}, DEFAULT_PARAMS, searchParams, overrides);
}
handleClearOrgDeleteModal () {
this.setState({
isModalOpen: false,
});
}
handleOpenOrgDeleteModal () {
const { selected } = this.state;
const warningTitle = selected.length > 1 ? i18nMark('Delete Organization') : i18nMark('Delete Organizations');
const warningMsg = i18nMark('Are you sure you want to delete:');
this.setState({
isModalOpen: true,
warningTitle,
warningMsg,
loading: false
});
return {
...DEFAULT_QUERY_PARAMS,
...searchParams,
};
}
async handleOrgDelete () {
@ -169,7 +95,6 @@ class OrganizationsList extends Component {
try {
await Promise.all(selected.map((org) => api.destroyOrganization(org.id)));
this.setState({
isModalOpen: false,
selected: []
});
} catch (err) {
@ -192,50 +117,27 @@ class OrganizationsList extends Component {
}
}
async fetchOrganizations (queryParams) {
async fetchOrganizations () {
const { api, handleHttpError } = this.props;
const { page, page_size, order_by } = queryParams;
const params = this.getQueryParams();
let sortOrder = 'ascending';
let sortedColumnKey = order_by;
if (order_by.startsWith('-')) {
sortOrder = 'descending';
sortedColumnKey = order_by.substring(1);
}
this.setState({ error: false, loading: true });
this.setState({ error: false, isLoading: true });
try {
const { data } = await api.getOrganizations(queryParams);
const { data } = await api.getOrganizations(params);
const { count, results } = data;
const pageCount = Math.ceil(count / page_size);
const stateToUpdate = {
count,
page,
pageCount,
page_size,
sortOrder,
sortedColumnKey,
results,
itemCount: count,
organizations: results,
selected: [],
loading: false
isLoading: false,
isInitialized: true,
};
// This is in place to track whether or not the initial request
// return any results. If it did not, we show the empty state.
// This will become problematic once search is in play because
// the first load may have query params (think bookmarked search)
if (typeof noInitialResults === 'undefined') {
stateToUpdate.noInitialResults = results.length === 0;
}
this.setState(stateToUpdate);
this.updateUrl(queryParams);
} catch (err) {
handleHttpError(err) || this.setState({ error: true, loading: false });
handleHttpError(err) || this.setState({ error: true, isLoading: false });
}
}
@ -254,7 +156,7 @@ class OrganizationsList extends Component {
} catch (err) {
this.setState({ error: true });
} finally {
this.setState({ loading: false });
this.setState({ isLoading: false });
}
}
@ -264,139 +166,56 @@ class OrganizationsList extends Component {
} = PageSectionVariants;
const {
canAdd,
count,
itemCount,
error,
loading,
noInitialResults,
page,
pageCount,
page_size,
isLoading,
isInitialized,
selected,
sortedColumnKey,
sortOrder,
results,
isModalOpen,
warningTitle,
warningMsg,
organizations,
} = this.state;
const { match } = this.props;
let deleteToolTipContent;
if (selected.some(row => !row.summary_fields.user_capabilities.delete)) {
deleteToolTipContent = (
<div>
<Trans>
You dont have permission to delete the following Organizations:
</Trans>
{selected
.filter(row => !row.summary_fields.user_capabilities.delete)
.map(row => (
<div key={row.id}>
{row.name}
</div>
))
}
</div>
);
} else if (selected.length === 0) {
deleteToolTipContent = i18nMark('Select a row to delete');
} else {
deleteToolTipContent = i18nMark('Delete');
}
const disableDelete = (
selected.length === 0
|| selected.some(row => !row.summary_fields.user_capabilities.delete)
);
const isAllSelected = selected.length === organizations.length;
return (
<I18n>
{({ i18n }) => (
<PageSection variant={medium}>
<Card>
{ isModalOpen && (
<AlertModal
variant="danger"
title={warningTitle}
isOpen={isModalOpen}
onClose={this.handleClearOrgDeleteModal}
actions={[
<Button variant="danger" key="delete" aria-label="confirm-delete" onClick={this.handleOrgDelete}>{i18n._(t`Delete`)}</Button>,
<Button variant="secondary" key="cancel" aria-label="cancel-delete" onClick={this.handleClearOrgDeleteModal}>{i18n._(t`Cancel`)}</Button>
]}
>
{warningMsg}
<br />
{selected.map((org) => (
<span key={org.id}>
<strong>
{org.name}
</strong>
<br />
</span>
))}
<br />
</AlertModal>
<PageSection variant={medium}>
<Card>
{isInitialized && (
<PaginatedDataList
items={organizations}
itemCount={itemCount}
itemName="organization"
queryParams={this.getQueryParams()}
toolbarColumns={COLUMNS}
showSelectAll
isAllSelected={isAllSelected}
onSelectAll={this.handleSelectAll}
additionalControls={[
<ToolbarDeleteButton
key="delete"
onDelete={this.handleOrgDelete}
itemsToDelete={selected}
itemName="Organization"
/>,
canAdd
? <ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
: null,
]}
renderItem={(o) => (
<OrganizationListItem
key={o.id}
organization={o}
detailUrl={`${match.url}/${o.id}`}
isSelected={selected.some(row => row.id === o.id)}
onSelect={() => this.handleSelect(o)}
/>
)}
{noInitialResults && (
<EmptyState>
<EmptyStateIcon icon={CubesIcon} />
<Title size="lg">
<Trans>No Organizations Found</Trans>
</Title>
<EmptyStateBody>
<Trans>Please add an organization to populate this list</Trans>
</EmptyStateBody>
</EmptyState>
) || (
<Fragment>
<DataListToolbar
addUrl={`${match.url}/add`}
addBtnToolTipContent={i18nMark('Add Organization')}
isAllSelected={selected.length === results.length}
sortedColumnKey={sortedColumnKey}
sortOrder={sortOrder}
columns={COLUMNS}
onSearch={this.onSearch}
onSort={this.onSort}
onSelectAll={this.onSelectAll}
onOpenDeleteModal={this.handleOpenOrgDeleteModal}
disableDelete={disableDelete}
deleteTooltip={deleteToolTipContent}
showDelete
showSelectAll
showAdd={canAdd}
/>
<ul className="pf-c-data-list" aria-label={i18n._(t`Organizations List`)}>
{ results.map(o => (
<OrganizationListItem
key={o.id}
itemId={o.id}
name={o.name}
detailUrl={`${match.url}/${o.id}`}
memberCount={o.summary_fields.related_field_counts.users}
teamCount={o.summary_fields.related_field_counts.teams}
isSelected={selected.some(row => row.id === o.id)}
onSelect={() => this.onSelect(o)}
/>
))}
</ul>
<Pagination
count={count}
page={page}
pageCount={pageCount}
page_size={page_size}
onSetPage={this.onSetPage}
/>
{ loading ? <div>loading...</div> : '' }
{ error ? <div>error</div> : '' }
</Fragment>
)}
</Card>
</PageSection>
)}
</I18n>
/>
)}
{ isLoading ? <div>loading...</div> : '' }
{ error ? <div>error</div> : '' }
</Card>
</PageSection>
);
}
}