UserPicker.tsx 2.0 KB

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