File size: 2,152 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import PropTypes from 'prop-types';
import { useState } from 'react';
import useUsersQuery from 'calypso/data/users/use-users-query';
import SwitcherShell from './switcher-shell';
import './style.scss';
const AuthorSelector = ( {
allowSingleUser = false,
children,
exclude,
ignoreContext,
onSelect,
popoverPosition = 'bottom left',
siteId,
transformAuthor,
} ) => {
const [ search, setSearch ] = useState( '' );
const [ prevSiteId, setPrevSiteId ] = useState( null );
if ( siteId && siteId !== prevSiteId ) {
setPrevSiteId( siteId );
if ( search !== '' ) {
setSearch( '' );
}
}
const fetchOptions = { number: 50, authors_only: 1 };
const trimmedSearch = search.trim?.();
if ( trimmedSearch ) {
fetchOptions.number = 20; // make search a little faster
fetchOptions.search = `*${ trimmedSearch }*`;
fetchOptions.search_columns = [ 'user_login', 'display_name' ];
}
const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useUsersQuery(
siteId,
fetchOptions
);
const users =
data?.users.filter( ( user ) => {
if ( typeof exclude === 'function' ) {
return ! exclude( user );
}
if ( Array.isArray( exclude ) ) {
return ! exclude.includes( user.ID );
}
return true;
} ) ?? [];
const listKey = [ 'authors', siteId, search ].join( '-' );
return (
<SwitcherShell
allowSingleUser={ allowSingleUser }
fetchNextPage={ fetchNextPage }
hasNextPage={ hasNextPage }
ignoreContext={ ignoreContext }
isFetchingNextPage={ isFetchingNextPage }
isLoading={ isLoading }
listKey={ listKey }
onSelect={ onSelect }
popoverPosition={ popoverPosition }
search={ search }
siteId={ siteId }
transformAuthor={ transformAuthor }
updateSearch={ setSearch }
users={ users }
>
{ children }
</SwitcherShell>
);
};
AuthorSelector.propTypes = {
allowSingleUser: PropTypes.bool,
exclude: PropTypes.oneOfType( [ PropTypes.arrayOf( PropTypes.number ), PropTypes.func ] ),
onSelect: PropTypes.func,
popoverPosition: PropTypes.string,
siteId: PropTypes.number.isRequired,
transformAuthor: PropTypes.func,
};
export default AuthorSelector;
|