UserPicker.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import React, { Component } from 'react';
  2. import Select from 'react-select';
  3. import PickerOption from './PickerOption';
  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.debouncedSearch = debounce(this.search, 300, {
  26. leading: true,
  27. trailing: false,
  28. });
  29. }
  30. search(query?: string) {
  31. const { toggleLoading, backendSrv } = this.props;
  32. toggleLoading(true);
  33. return backendSrv.get(`/api/users/search?perpage=10&page=1&query=${query}`).then(result => {
  34. const users = result.users.map(user => {
  35. return {
  36. id: user.id,
  37. label: `${user.login} - ${user.email}`,
  38. avatarUrl: user.avatarUrl,
  39. login: user.login,
  40. };
  41. });
  42. toggleLoading(false);
  43. return { options: users };
  44. });
  45. }
  46. render() {
  47. const AsyncComponent = this.state.creatable ? Select.AsyncCreatable : Select.Async;
  48. const { isLoading, handlePicked } = this.props;
  49. return (
  50. <div className="user-picker">
  51. <AsyncComponent
  52. valueKey="id"
  53. multi={false}
  54. labelKey="label"
  55. cache={false}
  56. isLoading={isLoading}
  57. loadOptions={this.debouncedSearch}
  58. loadingPlaceholder="Loading..."
  59. noResultsText="No users found"
  60. onChange={handlePicked}
  61. className="width-8 gf-form-input gf-form-input--form-dropdown"
  62. optionComponent={PickerOption}
  63. placeholder="Choose"
  64. />
  65. </div>
  66. );
  67. }
  68. }
  69. export default withPicker(UserPicker);