UserPicker.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. value?: string;
  12. }
  13. export interface User {
  14. id: number;
  15. label: string;
  16. avatarUrl: string;
  17. login: string;
  18. }
  19. class UserPicker extends Component<IProps, any> {
  20. debouncedSearch: any;
  21. backendSrv: any;
  22. constructor(props) {
  23. super(props);
  24. this.state = {};
  25. this.search = this.search.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, value } = this.props;
  50. return (
  51. <div className="user-picker">
  52. <AsyncComponent
  53. valueKey="id"
  54. multi={false}
  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-12 gf-form-input gf-form-input--form-dropdown"
  63. optionComponent={PickerOption}
  64. placeholder="Choose"
  65. value={value}
  66. autosize={true}
  67. />
  68. </div>
  69. );
  70. }
  71. }
  72. export default withPicker(UserPicker);