Updates files to pre lingUI upgrade work

This commit is contained in:
Alex Corey
2021-01-05 14:14:42 -05:00
parent 93160fa4fd
commit 0a88d42645
15 changed files with 819 additions and 933 deletions

View File

@@ -1,4 +1,4 @@
import React, { Fragment } from 'react'; import React, { Fragment, useState } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
@@ -17,95 +17,57 @@ const readTeams = async queryParams => TeamsAPI.read(queryParams);
const readTeamsOptions = async () => TeamsAPI.readOptions(); const readTeamsOptions = async () => TeamsAPI.readOptions();
class AddResourceRole extends React.Component { function AddResourceRole({ onSave, onClose, roles, i18n, resource }) {
constructor(props) { const [selectedResource, setSelectedResource] = useState(null);
super(props); const [selectedResourceRows, setSelectedResourceRows] = useState([]);
const [selectedRoleRows, setSelectedRoleRows] = useState([]);
this.state = { const [currentStepId, setCurrentStepId] = useState(1);
selectedResource: null, const [maxEnabledStep, setMaxEnabledStep] = useState(1);
selectedResourceRows: [],
selectedRoleRows: [],
currentStepId: 1,
maxEnabledStep: 1,
};
this.handleResourceCheckboxClick = this.handleResourceCheckboxClick.bind(
this
);
this.handleResourceSelect = this.handleResourceSelect.bind(this);
this.handleRoleCheckboxClick = this.handleRoleCheckboxClick.bind(this);
this.handleWizardNext = this.handleWizardNext.bind(this);
this.handleWizardSave = this.handleWizardSave.bind(this);
this.handleWizardGoToStep = this.handleWizardGoToStep.bind(this);
}
handleResourceCheckboxClick(user) {
const { selectedResourceRows, currentStepId } = this.state;
const handleResourceCheckboxClick = user => {
const selectedIndex = selectedResourceRows.findIndex( const selectedIndex = selectedResourceRows.findIndex(
selectedRow => selectedRow.id === user.id selectedRow => selectedRow.id === user.id
); );
if (selectedIndex > -1) { if (selectedIndex > -1) {
selectedResourceRows.splice(selectedIndex, 1); selectedResourceRows.splice(selectedIndex, 1);
const stateToUpdate = { selectedResourceRows };
if (selectedResourceRows.length === 0) { if (selectedResourceRows.length === 0) {
stateToUpdate.maxEnabledStep = currentStepId; setMaxEnabledStep(currentStepId);
} }
this.setState(stateToUpdate); setSelectedRoleRows(selectedResourceRows);
} else { } else {
this.setState(prevState => ({ setSelectedResourceRows([...selectedResourceRows, user]);
selectedResourceRows: [...prevState.selectedResourceRows, user],
}));
}
} }
};
handleRoleCheckboxClick(role) { const handleRoleCheckboxClick = role => {
const { selectedRoleRows } = this.state;
const selectedIndex = selectedRoleRows.findIndex( const selectedIndex = selectedRoleRows.findIndex(
selectedRow => selectedRow.id === role.id selectedRow => selectedRow.id === role.id
); );
if (selectedIndex > -1) { if (selectedIndex > -1) {
selectedRoleRows.splice(selectedIndex, 1); selectedRoleRows.splice(selectedIndex, 1);
this.setState({ selectedRoleRows }); setSelectedRoleRows(selectedRoleRows);
} else { } else {
this.setState(prevState => ({ setSelectedRoleRows([...selectedRoleRows, role]);
selectedRoleRows: [...prevState.selectedRoleRows, role],
}));
}
} }
};
handleResourceSelect(resourceType) { const handleResourceSelect = resourceType => {
this.setState({ setSelectedResource(resourceType);
selectedResource: resourceType, setSelectedResourceRows([]);
selectedResourceRows: [], setSelectedRoleRows([]);
selectedRoleRows: [], };
});
}
handleWizardNext(step) { const handleWizardNext = step => {
this.setState({ setCurrentStepId(step.id);
currentStepId: step.id, setMaxEnabledStep(step.id);
maxEnabledStep: step.id, };
});
}
handleWizardGoToStep(step) { const handleWizardGoToStep = step => {
this.setState({ setCurrentStepId(step.id);
currentStepId: step.id, };
});
}
async handleWizardSave() {
const { onSave } = this.props;
const {
selectedResourceRows,
selectedRoleRows,
selectedResource,
} = this.state;
const handleWizardSave = async () => {
try { try {
const roleRequests = []; const roleRequests = [];
@@ -134,17 +96,7 @@ class AddResourceRole extends React.Component {
} catch (err) { } catch (err) {
// TODO: handle this error // TODO: handle this error
} }
} };
render() {
const {
selectedResource,
selectedResourceRows,
selectedRoleRows,
currentStepId,
maxEnabledStep,
} = this.state;
const { onClose, roles, i18n, resource } = this.props;
// Object roles can be user only, so we remove them when // Object roles can be user only, so we remove them when
// showing role choices for team access // showing role choices for team access
@@ -172,7 +124,6 @@ class AddResourceRole extends React.Component {
key: 'last_name__icontains', key: 'last_name__icontains',
}, },
]; ];
const userSortColumns = [ const userSortColumns = [
{ {
name: i18n._(t`Username`), name: i18n._(t`Username`),
@@ -187,7 +138,6 @@ class AddResourceRole extends React.Component {
key: 'last_name', key: 'last_name',
}, },
]; ];
const teamSearchColumns = [ const teamSearchColumns = [
{ {
name: i18n._(t`Name`), name: i18n._(t`Name`),
@@ -235,22 +185,20 @@ class AddResourceRole extends React.Component {
t`Choose the type of resource that will be receiving new roles. For example, if you'd like to add new roles to a set of users please choose Users and click Next. You'll be able to select the specific resources in the next step.` t`Choose the type of resource that will be receiving new roles. For example, if you'd like to add new roles to a set of users please choose Users and click Next. You'll be able to select the specific resources in the next step.`
)} )}
</div> </div>
<SelectableCard <SelectableCard
isSelected={selectedResource === 'users'} isSelected={selectedResource === 'users'}
label={i18n._(t`Users`)} label={i18n._(t`Users`)}
dataCy="add-role-users"
ariaLabel={i18n._(t`Users`)} ariaLabel={i18n._(t`Users`)}
onClick={() => this.handleResourceSelect('users')} dataCy="add-role-users"
onClick={() => handleResourceSelect('users')}
/> />
{resource?.type === 'credential' && {resource?.type === 'credential' && !resource?.organization ? null : (
!resource?.organization ? null : (
<SelectableCard <SelectableCard
isSelected={selectedResource === 'teams'} isSelected={selectedResource === 'teams'}
label={i18n._(t`Teams`)} label={i18n._(t`Teams`)}
dataCy="add-role-teams"
ariaLabel={i18n._(t`Teams`)} ariaLabel={i18n._(t`Teams`)}
onClick={() => this.handleResourceSelect('teams')} dataCy="add-role-teams"
onClick={() => handleResourceSelect('teams')}
/> />
)} )}
</div> </div>
@@ -267,7 +215,7 @@ class AddResourceRole extends React.Component {
searchColumns={userSearchColumns} searchColumns={userSearchColumns}
sortColumns={userSortColumns} sortColumns={userSortColumns}
displayKey="username" displayKey="username"
onRowClick={this.handleResourceCheckboxClick} onRowClick={handleResourceCheckboxClick}
fetchItems={readUsers} fetchItems={readUsers}
fetchOptions={readUsersOptions} fetchOptions={readUsersOptions}
selectedLabel={i18n._(t`Selected`)} selectedLabel={i18n._(t`Selected`)}
@@ -279,7 +227,7 @@ class AddResourceRole extends React.Component {
<SelectResourceStep <SelectResourceStep
searchColumns={teamSearchColumns} searchColumns={teamSearchColumns}
sortColumns={teamSortColumns} sortColumns={teamSortColumns}
onRowClick={this.handleResourceCheckboxClick} onRowClick={handleResourceCheckboxClick}
fetchItems={readTeams} fetchItems={readTeams}
fetchOptions={readTeamsOptions} fetchOptions={readTeamsOptions}
selectedLabel={i18n._(t`Selected`)} selectedLabel={i18n._(t`Selected`)}
@@ -296,7 +244,7 @@ class AddResourceRole extends React.Component {
name: i18n._(t`Select Roles to Apply`), name: i18n._(t`Select Roles to Apply`),
component: ( component: (
<SelectRoleStep <SelectRoleStep
onRolesClick={this.handleRoleCheckboxClick} onRolesClick={handleRoleCheckboxClick}
roles={selectableRoles} roles={selectableRoles}
selectedListKey={selectedResource === 'users' ? 'username' : 'name'} selectedListKey={selectedResource === 'users' ? 'username' : 'name'}
selectedListLabel={i18n._(t`Selected`)} selectedListLabel={i18n._(t`Selected`)}
@@ -317,10 +265,10 @@ class AddResourceRole extends React.Component {
<Wizard <Wizard
style={{ overflow: 'scroll' }} style={{ overflow: 'scroll' }}
isOpen isOpen
onNext={this.handleWizardNext} onNext={handleWizardNext}
onClose={onClose} onClose={onClose}
onSave={this.handleWizardSave} onSave={handleWizardSave}
onGoToStep={this.handleWizardGoToStep} onGoToStep={step => handleWizardGoToStep(step)}
steps={steps} steps={steps}
title={wizardTitle} title={wizardTitle}
nextButtonText={currentStep.nextButtonText || undefined} nextButtonText={currentStep.nextButtonText || undefined}
@@ -328,7 +276,6 @@ class AddResourceRole extends React.Component {
cancelButtonText={i18n._(t`Cancel`)} cancelButtonText={i18n._(t`Cancel`)}
/> />
); );
}
} }
AddResourceRole.propTypes = { AddResourceRole.propTypes = {

View File

@@ -1,22 +1,46 @@
/* eslint-disable react/jsx-pascal-case */ /* eslint-disable react/jsx-pascal-case */
import React from 'react'; import React from 'react';
import { shallow } from 'enzyme'; import { shallow } from 'enzyme';
import { mountWithContexts } from '../../../testUtils/enzymeHelpers'; import { act } from 'react-dom/test-utils';
import {
mountWithContexts,
waitForElement,
} from '../../../testUtils/enzymeHelpers';
import AddResourceRole, { _AddResourceRole } from './AddResourceRole'; import AddResourceRole, { _AddResourceRole } from './AddResourceRole';
import { TeamsAPI, UsersAPI } from '../../api'; import { TeamsAPI, UsersAPI } from '../../api';
jest.mock('../../api'); jest.mock('../../api/models/Teams');
jest.mock('../../api/models/Users');
// TODO: Once error handling is functional in
// this component write tests for it
describe('<_AddResourceRole />', () => { describe('<_AddResourceRole />', () => {
UsersAPI.read.mockResolvedValue({ UsersAPI.read.mockResolvedValue({
data: { data: {
count: 2, count: 2,
results: [ results: [
{ id: 1, username: 'foo' }, { id: 1, username: 'foo', url: '' },
{ id: 2, username: 'bar' }, { id: 2, username: 'bar', url: '' },
], ],
}, },
}); });
UsersAPI.readOptions.mockResolvedValue({
data: { related: {}, actions: { GET: {} } },
});
TeamsAPI.read.mockResolvedValue({
data: {
count: 2,
results: [
{ id: 1, name: 'Team foo', url: '' },
{ id: 2, name: 'Team bar', url: '' },
],
},
});
TeamsAPI.readOptions.mockResolvedValue({
data: { related: {}, actions: { GET: {} } },
});
const roles = { const roles = {
admin_role: { admin_role: {
description: 'Can manage all aspects of the organization', description: 'Can manage all aspects of the organization',
@@ -39,191 +63,165 @@ describe('<_AddResourceRole />', () => {
/> />
); );
}); });
test('handleRoleCheckboxClick properly updates state', () => { test('should save properly', async () => {
const wrapper = shallow( let wrapper;
<_AddResourceRole act(() => {
onClose={() => {}} wrapper = mountWithContexts(
onSave={() => {}}
roles={roles}
i18n={{ _: val => val.toString() }}
/>
);
wrapper.setState({
selectedRoleRows: [
{
description: 'Can manage all aspects of the organization',
name: 'Admin',
id: 1,
},
],
});
wrapper.instance().handleRoleCheckboxClick({
description: 'Can manage all aspects of the organization',
name: 'Admin',
id: 1,
});
expect(wrapper.state('selectedRoleRows')).toEqual([]);
wrapper.instance().handleRoleCheckboxClick({
description: 'Can manage all aspects of the organization',
name: 'Admin',
id: 1,
});
expect(wrapper.state('selectedRoleRows')).toEqual([
{
description: 'Can manage all aspects of the organization',
name: 'Admin',
id: 1,
},
]);
});
test('handleResourceCheckboxClick properly updates state', () => {
const wrapper = shallow(
<_AddResourceRole
onClose={() => {}}
onSave={() => {}}
roles={roles}
i18n={{ _: val => val.toString() }}
/>
);
wrapper.setState({
selectedResourceRows: [
{
id: 1,
username: 'foobar',
},
],
});
wrapper.instance().handleResourceCheckboxClick({
id: 1,
username: 'foobar',
});
expect(wrapper.state('selectedResourceRows')).toEqual([]);
wrapper.instance().handleResourceCheckboxClick({
id: 1,
username: 'foobar',
});
expect(wrapper.state('selectedResourceRows')).toEqual([
{
id: 1,
username: 'foobar',
},
]);
});
test('clicking user/team cards updates state', () => {
const spy = jest.spyOn(_AddResourceRole.prototype, 'handleResourceSelect');
const wrapper = mountWithContexts(
<AddResourceRole onClose={() => {}} onSave={() => {}} roles={roles} />, <AddResourceRole onClose={() => {}} onSave={() => {}} roles={roles} />,
{ context: { network: { handleHttpError: () => {} } } } { context: { network: { handleHttpError: () => {} } } }
).find('AddResourceRole'); );
});
wrapper.update();
// Step 1
const selectableCardWrapper = wrapper.find('SelectableCard'); const selectableCardWrapper = wrapper.find('SelectableCard');
expect(selectableCardWrapper.length).toBe(2); expect(selectableCardWrapper.length).toBe(2);
selectableCardWrapper.first().simulate('click'); act(() => wrapper.find('SelectableCard[label="Users"]').prop('onClick')());
expect(spy).toHaveBeenCalledWith('users'); wrapper.update();
expect(wrapper.state('selectedResource')).toBe('users'); await act(async () =>
selectableCardWrapper.at(1).simulate('click'); wrapper.find('Button[type="submit"]').prop('onClick')()
expect(spy).toHaveBeenCalledWith('teams');
expect(wrapper.state('selectedResource')).toBe('teams');
});
test('handleResourceSelect clears out selected lists and sets selectedResource', () => {
const wrapper = shallow(
<_AddResourceRole
onClose={() => {}}
onSave={() => {}}
roles={roles}
i18n={{ _: val => val.toString() }}
/>
); );
wrapper.setState({ wrapper.update();
selectedResource: 'teams',
selectedResourceRows: [ // Step 2
{ await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0);
id: 1, act(() =>
username: 'foobar', wrapper.find('DataListCheck[name="foo"]').invoke('onChange')(true)
}, );
], wrapper.update();
selectedRoleRows: [ expect(wrapper.find('DataListCheck[name="foo"]').prop('checked')).toBe(
{ true
description: 'Can manage all aspects of the organization', );
id: 1, act(() => wrapper.find('Button[type="submit"]').prop('onClick')());
name: 'Admin', wrapper.update();
},
], // Step 3
act(() =>
wrapper.find('Checkbox[aria-label="Admin"]').invoke('onChange')(true)
);
wrapper.update();
expect(wrapper.find('Checkbox[aria-label="Admin"]').prop('isChecked')).toBe(
true
);
// Save
await act(async () =>
wrapper.find('Button[type="submit"]').prop('onClick')()
);
expect(UsersAPI.associateRole).toBeCalledWith(1, 1);
}); });
wrapper.instance().handleResourceSelect('users');
expect(wrapper.state()).toEqual({ test('should successfuly click user/team cards', async () => {
selectedResource: 'users', let wrapper;
selectedResourceRows: [], act(() => {
selectedRoleRows: [], wrapper = mountWithContexts(
currentStepId: 1, <AddResourceRole onClose={() => {}} onSave={() => {}} roles={roles} />,
maxEnabledStep: 1,
});
wrapper.instance().handleResourceSelect('teams');
expect(wrapper.state()).toEqual({
selectedResource: 'teams',
selectedResourceRows: [],
selectedRoleRows: [],
currentStepId: 1,
maxEnabledStep: 1,
});
});
test('handleWizardSave makes correct api calls, calls onSave when done', async () => {
const handleSave = jest.fn();
const wrapper = mountWithContexts(
<AddResourceRole onClose={() => {}} onSave={handleSave} roles={roles} />,
{ context: { network: { handleHttpError: () => {} } } } { context: { network: { handleHttpError: () => {} } } }
).find('AddResourceRole'); );
wrapper.setState({
selectedResource: 'users',
selectedResourceRows: [
{
id: 1,
username: 'foobar',
},
],
selectedRoleRows: [
{
description: 'Can manage all aspects of the organization',
id: 1,
name: 'Admin',
},
{
description: 'May run any executable resources in the organization',
id: 2,
name: 'Execute',
},
],
}); });
await wrapper.instance().handleWizardSave(); wrapper.update();
expect(UsersAPI.associateRole).toHaveBeenCalledTimes(2);
expect(handleSave).toHaveBeenCalled(); const selectableCardWrapper = wrapper.find('SelectableCard');
wrapper.setState({ expect(selectableCardWrapper.length).toBe(2);
selectedResource: 'teams', act(() => wrapper.find('SelectableCard[label="Users"]').prop('onClick')());
selectedResourceRows: [ wrapper.update();
{
id: 1, await waitForElement(
name: 'foobar', wrapper,
}, 'SelectableCard[label="Users"]',
], el => el.prop('isSelected') === true
selectedRoleRows: [ );
{ act(() => wrapper.find('SelectableCard[label="Teams"]').prop('onClick')());
description: 'Can manage all aspects of the organization', wrapper.update();
id: 1,
name: 'Admin', await waitForElement(
}, wrapper,
{ 'SelectableCard[label="Teams"]',
description: 'May run any executable resources in the organization', el => el.prop('isSelected') === true
id: 2, );
name: 'Execute',
},
],
}); });
await wrapper.instance().handleWizardSave();
expect(TeamsAPI.associateRole).toHaveBeenCalledTimes(2); test('should reset values with resource type changes', async () => {
expect(handleSave).toHaveBeenCalled(); let wrapper;
act(() => {
wrapper = mountWithContexts(
<AddResourceRole onClose={() => {}} onSave={() => {}} roles={roles} />,
{ context: { network: { handleHttpError: () => {} } } }
);
});
wrapper.update();
// Step 1
const selectableCardWrapper = wrapper.find('SelectableCard');
expect(selectableCardWrapper.length).toBe(2);
act(() => wrapper.find('SelectableCard[label="Users"]').prop('onClick')());
wrapper.update();
await act(async () =>
wrapper.find('Button[type="submit"]').prop('onClick')()
);
wrapper.update();
// Step 2
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0);
act(() =>
wrapper.find('DataListCheck[name="foo"]').invoke('onChange')(true)
);
wrapper.update();
expect(wrapper.find('DataListCheck[name="foo"]').prop('checked')).toBe(
true
);
act(() => wrapper.find('Button[type="submit"]').prop('onClick')());
wrapper.update();
// Step 3
act(() =>
wrapper.find('Checkbox[aria-label="Admin"]').invoke('onChange')(true)
);
wrapper.update();
expect(wrapper.find('Checkbox[aria-label="Admin"]').prop('isChecked')).toBe(
true
);
// Go back to step 1
act(() => {
wrapper
.find('WizardNavItem[content="Select a Resource Type"]')
.find('button')
.prop('onClick')({ id: 1 });
});
wrapper.update();
expect(
wrapper
.find('WizardNavItem[content="Select a Resource Type"]')
.prop('isCurrent')
).toBe(true);
// Go back to step 1 and this time select teams. Doing so should clear following steps
act(() => wrapper.find('SelectableCard[label="Teams"]').prop('onClick')());
wrapper.update();
await act(async () =>
wrapper.find('Button[type="submit"]').prop('onClick')()
);
wrapper.update();
// Make sure no teams have been selected
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0);
wrapper
.find('DataListCheck')
.map(item => expect(item.prop('checked')).toBe(false));
act(() => wrapper.find('Button[type="submit"]').prop('onClick')());
wrapper.update();
// Make sure that no roles have been selected
wrapper
.find('Checkbox')
.map(card => expect(card.prop('isChecked')).toBe(false));
// Make sure the save button is disabled
expect(wrapper.find('Button[type="submit"]').prop('isDisabled')).toBe(true);
}); });
test('should not display team as a choice in case credential does not have organization', () => { test('should not display team as a choice in case credential does not have organization', () => {
const spy = jest.spyOn(_AddResourceRole.prototype, 'handleResourceSelect');
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<AddResourceRole <AddResourceRole
onClose={() => {}} onClose={() => {}}
@@ -232,11 +230,13 @@ describe('<_AddResourceRole />', () => {
resource={{ type: 'credential', organization: null }} resource={{ type: 'credential', organization: null }}
/>, />,
{ context: { network: { handleHttpError: () => {} } } } { context: { network: { handleHttpError: () => {} } } }
).find('AddResourceRole'); );
const selectableCardWrapper = wrapper.find('SelectableCard');
expect(selectableCardWrapper.length).toBe(1); expect(wrapper.find('SelectableCard').length).toBe(1);
selectableCardWrapper.first().simulate('click'); wrapper.find('SelectableCard[label="Users"]').simulate('click');
expect(spy).toHaveBeenCalledWith('users'); wrapper.update();
expect(wrapper.state('selectedResource')).toBe('users'); expect(
wrapper.find('SelectableCard[label="Users"]').prop('isSelected')
).toBe(true);
}); });
}); });

View File

@@ -7,9 +7,7 @@ import { t } from '@lingui/macro';
import CheckboxCard from './CheckboxCard'; import CheckboxCard from './CheckboxCard';
import SelectedList from '../SelectedList'; import SelectedList from '../SelectedList';
class RolesStep extends React.Component { function RolesStep({
render() {
const {
onRolesClick, onRolesClick,
roles, roles,
selectedListKey, selectedListKey,
@@ -17,8 +15,7 @@ class RolesStep extends React.Component {
selectedResourceRows, selectedResourceRows,
selectedRoleRows, selectedRoleRows,
i18n, i18n,
} = this.props; }) {
return ( return (
<Fragment> <Fragment>
<div> <div>
@@ -59,7 +56,6 @@ class RolesStep extends React.Component {
</div> </div>
</Fragment> </Fragment>
); );
}
} }
RolesStep.propTypes = { RolesStep.propTypes = {

View File

@@ -12,20 +12,7 @@ import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { FormSelect, FormSelectOption } from '@patternfly/react-core'; import { FormSelect, FormSelectOption } from '@patternfly/react-core';
class AnsibleSelect extends React.Component { function AnsibleSelect({
constructor(props) {
super(props);
this.onSelectChange = this.onSelectChange.bind(this);
}
onSelectChange(val, event) {
const { onChange, name } = this.props;
event.target.name = name;
onChange(event, val);
}
render() {
const {
id, id,
data, data,
i18n, i18n,
@@ -34,13 +21,19 @@ class AnsibleSelect extends React.Component {
value, value,
className, className,
isDisabled, isDisabled,
} = this.props; onChange,
name,
}) {
const onSelectChange = (val, event) => {
event.target.name = name;
onChange(event, val);
};
return ( return (
<FormSelect <FormSelect
id={id} id={id}
value={value} value={value}
onChange={this.onSelectChange} onChange={onSelectChange}
onBlur={onBlur} onBlur={onBlur}
aria-label={i18n._(t`Select Input`)} aria-label={i18n._(t`Select Input`)}
validated={isValid ? 'default' : 'error'} validated={isValid ? 'default' : 'error'}
@@ -57,7 +50,6 @@ class AnsibleSelect extends React.Component {
))} ))}
</FormSelect> </FormSelect>
); );
}
} }
const Option = shape({ const Option = shape({

View File

@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { mountWithContexts } from '../../../testUtils/enzymeHelpers'; import { mountWithContexts } from '../../../testUtils/enzymeHelpers';
import AnsibleSelect, { _AnsibleSelect } from './AnsibleSelect'; import AnsibleSelect from './AnsibleSelect';
const mockData = [ const mockData = [
{ {
@@ -16,6 +16,7 @@ const mockData = [
]; ];
describe('<AnsibleSelect />', () => { describe('<AnsibleSelect />', () => {
const onChange = jest.fn();
test('initially renders succesfully', async () => { test('initially renders succesfully', async () => {
mountWithContexts( mountWithContexts(
<AnsibleSelect <AnsibleSelect
@@ -29,19 +30,18 @@ describe('<AnsibleSelect />', () => {
}); });
test('calls "onSelectChange" on dropdown select change', () => { test('calls "onSelectChange" on dropdown select change', () => {
const spy = jest.spyOn(_AnsibleSelect.prototype, 'onSelectChange');
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<AnsibleSelect <AnsibleSelect
id="bar" id="bar"
value="foo" value="foo"
name="bar" name="bar"
onChange={() => {}} onChange={onChange}
data={mockData} data={mockData}
/> />
); );
expect(spy).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
wrapper.find('select').simulate('change'); wrapper.find('select').simulate('change');
expect(spy).toHaveBeenCalled(); expect(onChange).toHaveBeenCalled();
}); });
test('Returns correct select options', () => { test('Returns correct select options', () => {

View File

@@ -31,10 +31,7 @@ const ToolbarItem = styled(PFToolbarItem)`
// TODO: Recommend renaming this component to avoid confusion // TODO: Recommend renaming this component to avoid confusion
// with ExpandingContainer // with ExpandingContainer
class ExpandCollapse extends React.Component { function ExpandCollapse({ isCompact, onCompact, onExpand, i18n }) {
render() {
const { isCompact, onCompact, onExpand, i18n } = this.props;
return ( return (
<Fragment> <Fragment>
<ToolbarItem> <ToolbarItem>
@@ -59,7 +56,6 @@ class ExpandCollapse extends React.Component {
</ToolbarItem> </ToolbarItem>
</Fragment> </Fragment>
); );
}
} }
ExpandCollapse.propTypes = { ExpandCollapse.propTypes = {

View File

@@ -7,27 +7,19 @@ import { t } from '@lingui/macro';
import AlertModal from '../AlertModal'; import AlertModal from '../AlertModal';
import { Role } from '../../types'; import { Role } from '../../types';
class DeleteRoleConfirmationModal extends React.Component { function DeleteRoleConfirmationModal({
static propTypes = { role,
role: Role.isRequired, username,
username: string, onCancel,
onCancel: func.isRequired, onConfirm,
onConfirm: func.isRequired, i18n,
}; }) {
const isTeamRole = () => {
static defaultProps = {
username: '',
};
isTeamRole() {
const { role } = this.props;
return typeof role.team_id !== 'undefined'; return typeof role.team_id !== 'undefined';
} };
render() {
const { role, username, onCancel, onConfirm, i18n } = this.props;
const title = i18n._( const title = i18n._(
t`Remove ${this.isTeamRole() ? i18n._(t`Team`) : i18n._(t`User`)} Access` t`Remove ${isTeamRole() ? i18n._(t`Team`) : i18n._(t`User`)} Access`
); );
return ( return (
<AlertModal <AlertModal
@@ -49,7 +41,7 @@ class DeleteRoleConfirmationModal extends React.Component {
</Button>, </Button>,
]} ]}
> >
{this.isTeamRole() ? ( {isTeamRole() ? (
<Fragment> <Fragment>
{i18n._( {i18n._(
t`Are you sure you want to remove ${role.name} access from ${role.team_name}? Doing so affects all members of the team.` t`Are you sure you want to remove ${role.name} access from ${role.team_name}? Doing so affects all members of the team.`
@@ -69,7 +61,17 @@ class DeleteRoleConfirmationModal extends React.Component {
)} )}
</AlertModal> </AlertModal>
); );
}
} }
DeleteRoleConfirmationModal.propTypes = {
role: Role.isRequired,
username: string,
onCancel: func.isRequired,
onConfirm: func.isRequired,
};
DeleteRoleConfirmationModal.defaultProps = {
username: '',
};
export default withI18n()(DeleteRoleConfirmationModal); export default withI18n()(DeleteRoleConfirmationModal);

View File

@@ -144,6 +144,7 @@ function ResourceAccessList({ i18n, apiModel, resource }) {
setDeletionRole(role); setDeletionRole(role);
setShowDeleteModal(true); setShowDeleteModal(true);
}} }}
i18n={i18n}
/> />
)} )}
/> />

View File

@@ -24,19 +24,13 @@ const DataListItemCells = styled(PFDataListItemCells)`
align-items: start; align-items: start;
`; `;
class ResourceAccessListItem extends React.Component { function ResourceAccessListItem({ accessRecord, onRoleDelete, i18n }) {
static propTypes = { ResourceAccessListItem.propTypes = {
accessRecord: AccessRecord.isRequired, accessRecord: AccessRecord.isRequired,
onRoleDelete: func.isRequired, onRoleDelete: func.isRequired,
}; };
constructor(props) { const getRoleLists = () => {
super(props);
this.renderChip = this.renderChip.bind(this);
}
getRoleLists() {
const { accessRecord } = this.props;
const teamRoles = []; const teamRoles = [];
const userRoles = []; const userRoles = [];
@@ -52,10 +46,9 @@ class ResourceAccessListItem extends React.Component {
accessRecord.summary_fields.direct_access.map(sort); accessRecord.summary_fields.direct_access.map(sort);
accessRecord.summary_fields.indirect_access.map(sort); accessRecord.summary_fields.indirect_access.map(sort);
return [teamRoles, userRoles]; return [teamRoles, userRoles];
} };
renderChip(role) { const renderChip = role => {
const { accessRecord, onRoleDelete } = this.props;
return ( return (
<Chip <Chip
key={role.id} key={role.id}
@@ -67,11 +60,9 @@ class ResourceAccessListItem extends React.Component {
{role.name} {role.name}
</Chip> </Chip>
); );
} };
render() { const [teamRoles, userRoles] = getRoleLists();
const { accessRecord, i18n } = this.props;
const [teamRoles, userRoles] = this.getRoleLists();
return ( return (
<DataListItem <DataListItem
@@ -117,7 +108,7 @@ class ResourceAccessListItem extends React.Component {
label={i18n._(t`User Roles`)} label={i18n._(t`User Roles`)}
value={ value={
<ChipGroup numChips={5} totalChips={userRoles.length}> <ChipGroup numChips={5} totalChips={userRoles.length}>
{userRoles.map(this.renderChip)} {userRoles.map(renderChip)}
</ChipGroup> </ChipGroup>
} }
/> />
@@ -127,7 +118,7 @@ class ResourceAccessListItem extends React.Component {
label={i18n._(t`Team Roles`)} label={i18n._(t`Team Roles`)}
value={ value={
<ChipGroup numChips={5} totalChips={teamRoles.length}> <ChipGroup numChips={5} totalChips={teamRoles.length}>
{teamRoles.map(this.renderChip)} {teamRoles.map(renderChip)}
</ChipGroup> </ChipGroup>
} }
/> />
@@ -139,7 +130,6 @@ class ResourceAccessListItem extends React.Component {
</DataListItemRow> </DataListItemRow>
</DataListItem> </DataListItem>
); );
}
} }
export default withI18n()(ResourceAccessListItem); export default withI18n()(ResourceAccessListItem);

View File

@@ -1,7 +1,7 @@
import React, { Fragment } from 'react'; import React, { Fragment, useState } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { withRouter } from 'react-router-dom'; import { useLocation, withRouter } from 'react-router-dom';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { import {
Button, Button,
@@ -31,15 +31,14 @@ const NoOptionDropdown = styled.div`
border-bottom-color: var(--pf-global--BorderColor--200); border-bottom-color: var(--pf-global--BorderColor--200);
`; `;
class Sort extends React.Component { function Sort({ columns, qsConfig, onSort, i18n }) {
constructor(props) { const location = useLocation();
super(props); const [isSortDropdownOpen, setIsSortDropdownOpen] = useState(false);
let sortKey; let sortKey;
let sortOrder; let sortOrder;
let isNumeric; let isNumeric;
const { qsConfig, location } = this.props;
const queryParams = parseQueryString(qsConfig, location.search); const queryParams = parseQueryString(qsConfig, location.search);
if (queryParams.order_by && queryParams.order_by.startsWith('-')) { if (queryParams.order_by && queryParams.order_by.startsWith('-')) {
sortKey = queryParams.order_by.substr(1); sortKey = queryParams.order_by.substr(1);
@@ -55,53 +54,30 @@ class Sort extends React.Component {
isNumeric = false; isNumeric = false;
} }
this.state = { const handleDropdownToggle = isOpen => {
isSortDropdownOpen: false, setIsSortDropdownOpen(isOpen);
sortKey,
sortOrder,
isNumeric,
}; };
this.handleDropdownToggle = this.handleDropdownToggle.bind(this); const handleDropdownSelect = ({ target }) => {
this.handleDropdownSelect = this.handleDropdownSelect.bind(this);
this.handleSort = this.handleSort.bind(this);
}
handleDropdownToggle(isSortDropdownOpen) {
this.setState({ isSortDropdownOpen });
}
handleDropdownSelect({ target }) {
const { columns, onSort, qsConfig } = this.props;
const { sortOrder } = this.state;
const { innerText } = target; const { innerText } = target;
const [{ key: sortKey }] = columns.filter(({ name }) => name === innerText); const [{ key }] = columns.filter(({ name }) => name === innerText);
sortKey = key;
let isNumeric; if (qsConfig.integerFields.find(field => field === key)) {
if (qsConfig.integerFields.find(field => field === sortKey)) {
isNumeric = true; isNumeric = true;
} else { } else {
isNumeric = false; isNumeric = false;
} }
this.setState({ isSortDropdownOpen: false, sortKey, isNumeric }); setIsSortDropdownOpen(false);
onSort(sortKey, sortOrder); onSort(sortKey, sortOrder);
} };
handleSort() { const handleSort = () => {
const { onSort } = this.props; onSort(sortKey, sortOrder === 'ascending' ? 'descending' : 'ascending');
const { sortKey, sortOrder } = this.state; };
const newSortOrder = sortOrder === 'ascending' ? 'descending' : 'ascending';
this.setState({ sortOrder: newSortOrder });
onSort(sortKey, newSortOrder);
}
render() {
const { up } = DropdownPosition; const { up } = DropdownPosition;
const { columns, i18n } = this.props;
const { isSortDropdownOpen, sortKey, sortOrder, isNumeric } = this.state;
const defaultSortedColumn = columns.find(({ key }) => key === sortKey); const defaultSortedColumn = columns.find(({ key }) => key === sortKey);
@@ -124,39 +100,34 @@ class Sort extends React.Component {
let SortIcon; let SortIcon;
if (isNumeric) { if (isNumeric) {
SortIcon = SortIcon =
sortOrder === 'ascending' sortOrder === 'ascending' ? SortNumericDownIcon : SortNumericDownAltIcon;
? SortNumericDownIcon
: SortNumericDownAltIcon;
} else { } else {
SortIcon = SortIcon =
sortOrder === 'ascending' ? SortAlphaDownIcon : SortAlphaDownAltIcon; sortOrder === 'ascending' ? SortAlphaDownIcon : SortAlphaDownAltIcon;
} }
return ( return (
<Fragment> <Fragment>
{sortedColumnName && ( {sortedColumnName && (
<InputGroup> <InputGroup>
{(sortDropdownItems.length > 0 && ( {(sortDropdownItems.length > 0 && (
<Dropdown <Dropdown
onToggle={this.handleDropdownToggle} onToggle={handleDropdownToggle}
onSelect={this.handleDropdownSelect} onSelect={handleDropdownSelect}
direction={up} direction={up}
isOpen={isSortDropdownOpen} isOpen={isSortDropdownOpen}
toggle={ toggle={
<DropdownToggle <DropdownToggle id="awx-sort" onToggle={handleDropdownToggle}>
id="awx-sort"
onToggle={this.handleDropdownToggle}
>
{sortedColumnName} {sortedColumnName}
</DropdownToggle> </DropdownToggle>
} }
dropdownItems={sortDropdownItems} dropdownItems={sortDropdownItems}
/> />
)) || <NoOptionDropdown>{sortedColumnName}</NoOptionDropdown>} )) || <NoOptionDropdown>{sortedColumnName}</NoOptionDropdown>}
<Button <Button
variant={ButtonVariant.control} variant={ButtonVariant.control}
aria-label={i18n._(t`Sort`)} aria-label={i18n._(t`Sort`)}
onClick={this.handleSort} onClick={handleSort}
> >
<SortIcon /> <SortIcon />
</Button> </Button>
@@ -164,7 +135,6 @@ class Sort extends React.Component {
)} )}
</Fragment> </Fragment>
); );
}
} }
Sort.propTypes = { Sort.propTypes = {

View File

@@ -1,5 +1,10 @@
import React from 'react'; import React from 'react';
import { mountWithContexts } from '../../../testUtils/enzymeHelpers'; import { act } from 'react-dom/test-utils';
import {
mountWithContexts,
waitForElement,
} from '../../../testUtils/enzymeHelpers';
import Sort from './Sort'; import Sort from './Sort';
describe('<Sort />', () => { describe('<Sort />', () => {
@@ -105,7 +110,7 @@ describe('<Sort />', () => {
expect(onSort).toHaveBeenCalledWith('foo', 'ascending'); expect(onSort).toHaveBeenCalledWith('foo', 'ascending');
}); });
test('Changing dropdown correctly passes back new sort key', () => { test('Changing dropdown correctly passes back new sort key', async () => {
const qsConfig = { const qsConfig = {
namespace: 'item', namespace: 'item',
defaultParams: { page: 1, page_size: 5, order_by: 'foo' }, defaultParams: { page: 1, page_size: 5, order_by: 'foo' },
@@ -131,44 +136,18 @@ describe('<Sort />', () => {
const wrapper = mountWithContexts( const wrapper = mountWithContexts(
<Sort qsConfig={qsConfig} columns={columns} onSort={onSort} /> <Sort qsConfig={qsConfig} columns={columns} onSort={onSort} />
).find('Sort'); );
act(() => wrapper.find('Dropdown').invoke('onToggle')(true));
wrapper.instance().handleDropdownSelect({ target: { innerText: 'Bar' } }); wrapper.update();
await waitForElement(wrapper, 'Dropdown', el => el.prop('isOpen') === true);
wrapper
.find('li')
.at(0)
.prop('onClick')({ target: { innerText: 'Bar' } });
wrapper.update();
expect(onSort).toBeCalledWith('bar', 'ascending'); expect(onSort).toBeCalledWith('bar', 'ascending');
}); });
test('Opening dropdown correctly updates state', () => {
const qsConfig = {
namespace: 'item',
defaultParams: { page: 1, page_size: 5, order_by: 'foo' },
integerFields: ['page', 'page_size'],
};
const columns = [
{
name: 'Foo',
key: 'foo',
},
{
name: 'Bar',
key: 'bar',
},
{
name: 'Bakery',
key: 'bakery',
},
];
const onSort = jest.fn();
const wrapper = mountWithContexts(
<Sort qsConfig={qsConfig} columns={columns} onSort={onSort} />
).find('Sort');
expect(wrapper.state('isSortDropdownOpen')).toEqual(false);
wrapper.instance().handleDropdownToggle(true);
expect(wrapper.state('isSortDropdownOpen')).toEqual(true);
});
test('It displays correct sort icon', () => { test('It displays correct sort icon', () => {
const forwardNumericIconSelector = 'SortNumericDownIcon'; const forwardNumericIconSelector = 'SortNumericDownIcon';
const reverseNumericIconSelector = 'SortNumericDownAltIcon'; const reverseNumericIconSelector = 'SortNumericDownAltIcon';

View File

@@ -1,6 +1,6 @@
import React, { Component, Fragment } from 'react'; import React, { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom'; import { withRouter } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { I18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import styled from 'styled-components'; import styled from 'styled-components';
import { import {
@@ -518,7 +518,7 @@ class JobOutput extends Component {
} }
render() { render() {
const { job, i18n } = this.props; const { job } = this.props;
const { const {
contentError, contentError,
@@ -596,6 +596,9 @@ class JobOutput extends Component {
</OutputWrapper> </OutputWrapper>
</CardBody> </CardBody>
{deletionError && ( {deletionError && (
<>
<I18n>
{({ i18n }) => (
<AlertModal <AlertModal
isOpen={deletionError} isOpen={deletionError}
variant="danger" variant="danger"
@@ -606,10 +609,13 @@ class JobOutput extends Component {
<ErrorDetail error={deletionError} /> <ErrorDetail error={deletionError} />
</AlertModal> </AlertModal>
)} )}
</I18n>
</>
)}
</Fragment> </Fragment>
); );
} }
} }
export { JobOutput as _JobOutput }; export { JobOutput as _JobOutput };
export default withI18n()(withRouter(JobOutput)); export default withRouter(JobOutput);

View File

@@ -310,7 +310,17 @@ function ProjectForm({ i18n, project, submitError, ...props }) {
const { summary_fields = {} } = project; const { summary_fields = {} } = project;
const [contentError, setContentError] = useState(null); const [contentError, setContentError] = useState(null);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [scmSubFormState, setScmSubFormState] = useState(null); const [scmSubFormState, setScmSubFormState] = useState({
scm_url: '',
scm_branch: '',
scm_refspec: '',
credential: '',
scm_clean: false,
scm_delete_on_update: false,
scm_update_on_launch: false,
allow_override: false,
scm_update_cache_timeout: 0,
});
const [scmTypeOptions, setScmTypeOptions] = useState(null); const [scmTypeOptions, setScmTypeOptions] = useState(null);
const [credentials, setCredentials] = useState({ const [credentials, setCredentials] = useState({
scm: { typeId: null, value: null }, scm: { typeId: null, value: null },

View File

@@ -6,8 +6,8 @@ import { SyncIcon } from '@patternfly/react-icons';
import { number } from 'prop-types'; import { number } from 'prop-types';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import useRequest, { useDismissableError } from '../../../util/useRequest'; import useRequest, { useDismissableError } from '../../../util/useRequest';
import AlertModal from '../../../components/AlertModal'; import AlertModal from '../../../components/AlertModal';
import ErrorDetail from '../../../components/ErrorDetail'; import ErrorDetail from '../../../components/ErrorDetail';
import { ProjectsAPI } from '../../../api'; import { ProjectsAPI } from '../../../api';

View File

@@ -27,16 +27,14 @@ const DataListAction = styled(_DataListAction)`
grid-template-columns: 40px; grid-template-columns: 40px;
`; `;
class TeamListItem extends React.Component { function TeamListItem({ team, isSelected, onSelect, detailUrl, i18n }) {
static propTypes = { TeamListItem.propTypes = {
team: Team.isRequired, team: Team.isRequired,
detailUrl: string.isRequired, detailUrl: string.isRequired,
isSelected: bool.isRequired, isSelected: bool.isRequired,
onSelect: func.isRequired, onSelect: func.isRequired,
}; };
render() {
const { team, isSelected, onSelect, detailUrl, i18n } = this.props;
const labelId = `check-action-${team.id}`; const labelId = `check-action-${team.id}`;
return ( return (
@@ -92,6 +90,5 @@ class TeamListItem extends React.Component {
</DataListItemRow> </DataListItemRow>
</DataListItem> </DataListItem>
); );
}
} }
export default withI18n()(TeamListItem); export default withI18n()(TeamListItem);