UserPicker.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import React, { Component } from 'react';
  2. import { debounce } from 'lodash';
  3. import Select from 'react-select';
  4. import UserPickerOption from './UserPickerOption';
  5. export interface IProps {
  6. backendSrv: any;
  7. teamId: string;
  8. refreshList: any;
  9. }
  10. export interface User {
  11. id: number;
  12. name: string;
  13. login: string;
  14. email: string;
  15. }
  16. class UserPicker extends Component<IProps, any> {
  17. debouncedSearchUsers: any;
  18. backendSrv: any;
  19. teamId: string;
  20. refreshList: any;
  21. constructor(props) {
  22. super(props);
  23. this.backendSrv = this.props.backendSrv;
  24. this.teamId = this.props.teamId;
  25. this.refreshList = this.props.refreshList;
  26. this.searchUsers = this.searchUsers.bind(this);
  27. this.handleChange = this.handleChange.bind(this);
  28. this.addUser = this.addUser.bind(this);
  29. this.toggleLoading = this.toggleLoading.bind(this);
  30. this.debouncedSearchUsers = debounce(this.searchUsers, 300, {
  31. leading: true,
  32. trailing: false,
  33. });
  34. this.state = {
  35. multi: false,
  36. isLoading: false,
  37. };
  38. }
  39. handleChange(user) {
  40. this.addUser(user.id);
  41. }
  42. toggleLoading(isLoading) {
  43. this.setState(prevState => {
  44. return {
  45. ...prevState,
  46. isLoading: isLoading,
  47. };
  48. });
  49. }
  50. addUser(userId) {
  51. this.toggleLoading(true);
  52. this.backendSrv.post(`/api/teams/${this.teamId}/members`, { userId: userId }).then(() => {
  53. this.refreshList();
  54. this.toggleLoading(false);
  55. });
  56. }
  57. searchUsers(query) {
  58. this.toggleLoading(true);
  59. return this.backendSrv.get(`/api/users/search?perpage=10&page=1&query=${query}`).then(result => {
  60. const users = result.users.map(user => {
  61. return {
  62. id: user.id,
  63. label: `${user.login} - ${user.email}`,
  64. avatarUrl: user.avatarUrl,
  65. };
  66. });
  67. this.toggleLoading(false);
  68. return { options: users };
  69. });
  70. }
  71. render() {
  72. const AsyncComponent = this.state.creatable ? Select.AsyncCreatable : Select.Async;
  73. return (
  74. <div className="user-picker">
  75. <AsyncComponent
  76. valueKey="id"
  77. multi={this.state.multi}
  78. labelKey="label"
  79. cache={false}
  80. isLoading={this.state.isLoading}
  81. loadOptions={this.debouncedSearchUsers}
  82. loadingPlaceholder="Loading..."
  83. noResultsText="No users found"
  84. onChange={this.handleChange}
  85. className="width-8 gf-form-input gf-form-input--form-dropdown"
  86. optionComponent={UserPickerOption}
  87. placeholder="Choose"
  88. />
  89. </div>
  90. );
  91. }
  92. }
  93. export default UserPicker;