Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SDESK-4908] Paginate results in contacts selection in Event Form #1407

Merged
merged 1 commit into from
Jan 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions client/actions/contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as selectors from '../selectors';
* @param {string} contactType - Limit the query to a particular contact type
* @returns {Array<Object>} Returns an array of contacts found
*/
const getContacts = (searchText, searchFields = [], contactType = '') => (
const getContacts = (searchText, searchFields = [], contactType = '', page = 1) => (
(dispatch, getState, {api}) => {
const bool = {
must: [],
Expand All @@ -24,6 +24,7 @@ const getContacts = (searchText, searchFields = [], contactType = '') => (
default_field: 'first_name',
fields: searchFields,
query: searchText + '*',
default_operator: 'AND',
},
});
}
Expand All @@ -32,14 +33,21 @@ const getContacts = (searchText, searchFields = [], contactType = '') => (
bool.must.push({term: {contact_type: contactType}});
}

dispatch({type: 'LOADING_CONTACTS'});

return api('contacts').query({
source: {query: {bool: bool}},
sort: '[("first_name", 1)]',
max_results: 200,
page: page,
})
.then(
(data) => dispatch(
self.receiveContacts(
get(data, '_items', [])
get(data, '_items', []),
get(data, '_meta.total'),
get(data, '_meta.page')

)
)
);
Expand Down Expand Up @@ -160,12 +168,16 @@ const addContact = (newContact) => ({
* @param {Array<Object>} contacts - The contacts to add to the store
* @returns {Array<Object>} Returns an array of the contacts provided
*/
const receiveContacts = (contacts) => (
const receiveContacts = (contacts, total, page) => (
(dispatch) => {
if (get(contacts, 'length', 0) > 0) {
dispatch({
type: 'RECEIVE_CONTACTS',
payload: contacts,
payload: {
contacts,
total,
page,
},
});
}
return Promise.resolve(contacts);
Expand Down
15 changes: 12 additions & 3 deletions client/actions/tests/contacts_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ describe('actions.contacts', () => {
default_field: 'first_name',
fields: [],
query: 'bob*',
default_operator: 'AND',
},
}],
should: [
Expand All @@ -50,10 +51,12 @@ describe('actions.contacts', () => {
},
},
sort: '[("first_name", 1)]',
max_results: 200,
page: 1,
}]);

expect(contactsApi.receiveContacts.callCount).toBe(1);
expect(contactsApi.receiveContacts.args[0]).toEqual([data.contacts.contacts]);
expect(contactsApi.receiveContacts.args[0][0]).toEqual(data.contacts.contacts);
done();
})
.catch(done.fail);
Expand All @@ -72,6 +75,7 @@ describe('actions.contacts', () => {
default_field: 'first_name',
fields: ['organisation'],
query: 'bob*',
default_operator: 'AND',
},
}],
should: [
Expand All @@ -82,10 +86,12 @@ describe('actions.contacts', () => {
},
},
sort: '[("first_name", 1)]',
max_results: 200,
page: 1,
}]);

expect(contactsApi.receiveContacts.callCount).toBe(1);
expect(contactsApi.receiveContacts.args[0]).toEqual([data.contacts.contacts]);
expect(contactsApi.receiveContacts.args[0][0]).toEqual(data.contacts.contacts);
done();
})
.catch(done.fail);
Expand All @@ -104,6 +110,7 @@ describe('actions.contacts', () => {
default_field: 'first_name',
fields: [],
query: 'bob*',
default_operator: 'AND',
},
}, {
term: {contact_type: 'stringer'},
Expand All @@ -116,10 +123,12 @@ describe('actions.contacts', () => {
},
},
sort: '[("first_name", 1)]',
max_results: 200,
page: 1,
}]);

expect(contactsApi.receiveContacts.callCount).toBe(1);
expect(contactsApi.receiveContacts.args[0]).toEqual([data.contacts.contacts]);
expect(contactsApi.receiveContacts.args[0][0]).toEqual(data.contacts.contacts);
done();
})
.catch(done.fail);
Expand Down
3 changes: 0 additions & 3 deletions client/components/Contacts/ContactField.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {get} from 'lodash';
import * as selectors from '../../selectors';
import {ContactEditor, SelectSearchContactsField, ContactsPreviewList} from './index';
import * as actions from '../../actions';
import {CONTACTS} from '../../constants';
import {gettext} from '../../utils/index';


Expand Down Expand Up @@ -154,7 +153,6 @@ ContactFieldComponent.propTypes = {
PropTypes.arrayOf(PropTypes.string),
PropTypes.string,
]),
searchContacts: PropTypes.func,
fetchContacts: PropTypes.func,
contacts: PropTypes.array,
privileges: PropTypes.object,
Expand All @@ -174,7 +172,6 @@ const mapStateToProps = (state) => ({
});

const mapDispatchToProps = (dispatch) => ({
searchContacts: (text) => dispatch(actions.contacts.getContacts(text, CONTACTS.SEARCH_FIELDS)),
addContact: (newContact) => dispatch(actions.contacts.addContact(newContact)),
fetchContacts: (ids) => dispatch(actions.contacts.fetchContactsByIds(ids)),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import classNames from 'classnames';
import {get} from 'lodash';

import * as actions from '../../../actions';
import {contactsLoading, contactsTotal, contactsPage} from '../../../selectors/general';
import {CONTACTS} from '../../../constants';

import {uiUtils, onEventCapture, gettext} from '../../../utils';
Expand All @@ -26,6 +27,8 @@ export class SelectListPopupComponent extends React.Component {
activeOptionIndex: -1,
openFilterList: false,
filteredList: [],
options: [],
searchText: '',
};

this.dom = {
Expand All @@ -38,6 +41,13 @@ export class SelectListPopupComponent extends React.Component {
this.onAdd = this.onAdd.bind(this);
this.openSearchList = this.openSearchList.bind(this);
this.filterSearchResults = this.filterSearchResults.bind(this);
this.handleScroll = this.handleScroll.bind(this);
}

componentWillReceiveProps(nextProps) {
if (nextProps.page < this.props.page && this.dom.listItems) {
this.dom.listItems.scrollTop = 0;
}
}

onKeyDown(event) {
Expand Down Expand Up @@ -80,6 +90,21 @@ export class SelectListPopupComponent extends React.Component {
uiUtils.scrollListItemIfNeeded(this.state.activeOptionIndex, this.dom.listItems);
}

handleScroll(event) {
if (this.props.loading) {
return;
}

const node = event.target;
const {total, page} = this.props;

if (node && total > get(this.state.options, 'length', 0)) {
if (node.scrollTop + node.offsetHeight + 100 >= node.scrollHeight) {
this.getSearchResult(this.state.searchText, page + 1);
}
}
}

onAdd(event) {
this.closeSearchList();
this.dom.searchField.resetSearch();
Expand Down Expand Up @@ -110,10 +135,15 @@ export class SelectListPopupComponent extends React.Component {

const valueNoCase = (val || '').toLowerCase();

if (valueNoCase === this.state.searchText) {
return;
}

this.getSearchResult(valueNoCase);
this.setState({
search: true,
openFilterList: true,
searchText: valueNoCase,
});
}

Expand All @@ -137,16 +167,20 @@ export class SelectListPopupComponent extends React.Component {
filteredList: null,
search: false,
openFilterList: false,
options: [],
searchText: '',
});
}
}

getSearchResult(text) {
this.props.searchContacts(text, this.props.contactType)
getSearchResult(text, page = 1) {
this.props.searchContacts(text, this.props.contactType, page)
.then((contacts) => {
const allContacts = page <= 1 ? contacts : [...this.state.options, ...contacts];

this.setState({
options: contacts,
filteredList: contacts.filter(
options: allContacts,
filteredList: allContacts.filter(
(contact) => !this.props.value.find((contactId) => contactId === contact._id)
),
});
Expand All @@ -164,6 +198,7 @@ export class SelectListPopupComponent extends React.Component {
readOnly={this.props.readOnly}
placeholder={this.props.placeholder || gettext('Search for a contact')}
autoComplete={false}
name="searchFieldInput"
/>
{this.state.openFilterList && (
<Popup
Expand All @@ -174,9 +209,12 @@ export class SelectListPopupComponent extends React.Component {
noPadding={true}
onPopupOpen={this.props.onPopupOpen}
onPopupClose={this.props.onPopupClose}
ignoreOnClickElement="searchFieldInput"
>
<div className="Select__popup__wrapper">
<ul className="Select__popup__list" ref={(node) => this.dom.listItems = node}>
<ul className="Select__popup__list"
ref={(node) => this.dom.listItems = node}
onScroll={this.handleScroll} >
{get(this.state, 'filteredList.length', 0) > 0 &&
this.state.filteredList.map((opt, index) => (
<li
Expand Down Expand Up @@ -230,17 +268,26 @@ SelectListPopupComponent.propTypes = {
contactType: PropTypes.string,
minLength: PropTypes.number,
placeholder: PropTypes.string,
page: PropTypes.number,
loading: PropTypes.bool,
total: PropTypes.number,
};

SelectListPopupComponent.defaultProps = {minLength: 1};

const mapStateToProps = (state) => ({
loading: contactsLoading(state),
total: contactsTotal(state),
page: contactsPage(state),
});

const mapDispatchToProps = (dispatch) => ({
searchContacts: (text, contactType) => dispatch(
actions.contacts.getContacts(text, CONTACTS.SEARCH_FIELDS, contactType)
searchContacts: (text, contactType, page) => dispatch(
actions.contacts.getContacts(text, CONTACTS.SEARCH_FIELDS, contactType, page)
),
});

export const SelectListPopup = connect(
null,
mapStateToProps,
mapDispatchToProps
)(SelectListPopupComponent);
2 changes: 2 additions & 0 deletions client/components/UI/SearchField/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export default class SearchField extends React.Component {
onFocus={this.props.onFocus}
disabled={this.props.readOnly}
autoComplete={this.props.autoComplete ? 'on' : 'off'}
name={this.props.name}
/>
);
}
Expand All @@ -90,6 +91,7 @@ SearchField.propTypes = {
readOnly: PropTypes.bool,
placeholder: PropTypes.string,
autoComplete: PropTypes.bool,
name: PropTypes.string,
};

SearchField.defaultProps = {autoComplete: true};
20 changes: 19 additions & 1 deletion client/reducers/contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,31 @@ import {uniqBy} from 'lodash';
const initialState = {contacts: []};

const contacts = (state = initialState, action) => {
let newState;

switch (action.type) {
case 'RECEIVE_CONTACTS':
return {contacts: uniqBy([...action.payload, ...state.contacts], '_id')};
newState = {
contacts: uniqBy([...action.payload.contacts, ...state.contacts], '_id'),
loading: false,
};

if (action.payload.total || action.payload.page) {
newState.total = action.payload.total;
newState.page = action.payload.page;
}

return newState;

case 'ADD_CONTACT':
return {contacts: uniqBy([action.payload, ...state.contacts], '_id')};

case 'LOADING_CONTACTS':
return {
...state,
loading: true,
};

default:
return state;
}
Expand Down
3 changes: 3 additions & 0 deletions client/selectors/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ export const currentUserId = createSelector(
export const files = (state) => get(state, 'files.files');

export const contacts = (state) => get(state, 'contacts.contacts') || [];
export const contactsLoading = (state) => get(state, 'contacts.loading', false);
export const contactsTotal = (state) => get(state, 'contacts.total', 0);
export const contactsPage = (state) => get(state, 'contacts.page', 1);

export const contactsById = createSelector(
[contacts],
Expand Down