UserPicker.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React, { Component } from 'react';
  2. import AsyncSelect from 'react-select/lib/Async';
  3. import PickerOption from './PickerOption';
  4. import { debounce } from 'lodash';
  5. import { getBackendSrv } from 'app/core/services/backend_srv';
  6. import { User } from 'app/types';
  7. import ResetStyles from './ResetStyles';
  8. import IndicatorsContainer from './IndicatorsContainer';
  9. import NoOptionsMessage from './NoOptionsMessage';
  10. export interface Props {
  11. onSelected: (user: User) => void;
  12. className?: string;
  13. }
  14. export interface State {
  15. isLoading: boolean;
  16. }
  17. export class UserPicker extends Component<Props, State> {
  18. debouncedSearch: any;
  19. constructor(props) {
  20. super(props);
  21. this.state = { isLoading: false };
  22. this.search = this.search.bind(this);
  23. this.debouncedSearch = debounce(this.search, 300, {
  24. leading: true,
  25. trailing: true,
  26. });
  27. }
  28. search(query?: string) {
  29. const backendSrv = getBackendSrv();
  30. this.setState({ isLoading: true });
  31. return backendSrv
  32. .get(`/api/org/users?query=${query}&limit=10`)
  33. .then(result => {
  34. return result.map(user => ({
  35. id: user.userId,
  36. label: `${user.login} - ${user.email}`,
  37. avatarUrl: user.avatarUrl,
  38. login: user.login,
  39. }));
  40. })
  41. .finally(() => {
  42. this.setState({ isLoading: false });
  43. });
  44. }
  45. render() {
  46. const { className, onSelected } = this.props;
  47. const { isLoading } = this.state;
  48. return (
  49. <div className="user-picker">
  50. <AsyncSelect
  51. classNamePrefix={`gf-form-select-box`}
  52. isMulti={false}
  53. isLoading={isLoading}
  54. defaultOptions={true}
  55. loadOptions={this.debouncedSearch}
  56. onChange={onSelected}
  57. className={`gf-form-input gf-form-input--form-dropdown ${className || ''}`}
  58. styles={ResetStyles}
  59. components={{
  60. Option: PickerOption,
  61. IndicatorsContainer,
  62. NoOptionsMessage,
  63. }}
  64. placeholder="Select user"
  65. loadingMessage={() => 'Loading...'}
  66. noOptionsMessage={() => 'No users found'}
  67. getOptionValue={i => i.id}
  68. getOptionLabel={i => i.label}
  69. />
  70. </div>
  71. );
  72. }
  73. }