UserPicker.tsx 2.0 KB

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