UserPicker.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React, { Component } from 'react';
  2. import Select from 'react-select';
  3. import UserPickerOption from './UserPickerOption';
  4. import withPicker from './withPicker';
  5. import { debounce } from 'lodash';
  6. export interface IProps {
  7. backendSrv: any;
  8. isLoading: boolean;
  9. toggleLoading: any;
  10. userPicked: (user) => void;
  11. }
  12. export interface User {
  13. id: number;
  14. name: string;
  15. login: string;
  16. email: string;
  17. }
  18. class UserPicker extends Component<IProps, any> {
  19. debouncedSearchUsers: any;
  20. backendSrv: any;
  21. constructor(props) {
  22. super(props);
  23. this.state = {};
  24. this.searchUsers = this.searchUsers.bind(this);
  25. this.handleChange = this.handleChange.bind(this);
  26. this.debouncedSearchUsers = debounce(this.searchUsers, 300, {
  27. leading: true,
  28. trailing: false,
  29. });
  30. }
  31. handleChange(user) {
  32. const { userPicked } = this.props;
  33. userPicked(user);
  34. }
  35. searchUsers(query) {
  36. const { toggleLoading, backendSrv } = this.props;
  37. toggleLoading(true);
  38. return backendSrv.get(`/api/users/search?perpage=10&page=1&query=${query}`).then(result => {
  39. const users = result.users.map(user => {
  40. return {
  41. id: user.id,
  42. label: `${user.login} - ${user.email}`,
  43. avatarUrl: user.avatarUrl,
  44. };
  45. });
  46. toggleLoading(false);
  47. return { options: users };
  48. });
  49. }
  50. render() {
  51. const AsyncComponent = this.state.creatable ? Select.AsyncCreatable : Select.Async;
  52. return (
  53. <div className="user-picker">
  54. <AsyncComponent
  55. valueKey="id"
  56. multi={this.state.multi}
  57. labelKey="label"
  58. cache={false}
  59. isLoading={this.props.isLoading}
  60. loadOptions={this.debouncedSearchUsers}
  61. loadingPlaceholder="Loading..."
  62. noResultsText="No users found"
  63. onChange={this.handleChange}
  64. className="width-8 gf-form-input gf-form-input--form-dropdown"
  65. optionComponent={UserPickerOption}
  66. placeholder="Choose"
  67. />
  68. </div>
  69. );
  70. }
  71. }
  72. export default withPicker(UserPicker);