user_picker.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import coreModule from 'app/core/core_module';
  2. import appEvents from 'app/core/app_events';
  3. import _ from 'lodash';
  4. const template = `
  5. <div class="dropdown">
  6. <metric-segment segment="ctrl.userSegment"
  7. get-options="ctrl.debouncedSearchUsers($query)"
  8. on-change="ctrl.onChange()"></metric-segment>
  9. </div>
  10. `;
  11. export class UserPickerCtrl {
  12. userSegment: any;
  13. userLogin: string;
  14. userId: number;
  15. debouncedSearchUsers: any;
  16. /** @ngInject */
  17. constructor(private backendSrv, private $scope, $sce, private uiSegmentSrv) {
  18. this.userSegment = this.uiSegmentSrv.newSegment({value: 'Choose User', selectMode: true});
  19. this.debouncedSearchUsers = _.debounce(this.searchUsers, 500, {'leading': true, 'trailing': false});
  20. }
  21. searchUsers(query: string) {
  22. return Promise.resolve(this.backendSrv.get('/api/users/search?perpage=10&page=1&query=' + query).then(result => {
  23. return _.map(result.users, this.userKey.bind(this));
  24. }));
  25. }
  26. onChange() {
  27. this.userLogin = this.userSegment.value.split(' - ')[0];
  28. console.log(this.userLogin);
  29. this.backendSrv.get('/api/users/search?perpage=10&page=1&query=' + this.userLogin)
  30. .then(result => {
  31. if (!result) {
  32. return;
  33. }
  34. result.users.forEach(u => {
  35. if (u.login === this.userLogin) {
  36. this.userId = u.id;
  37. }
  38. });
  39. });
  40. }
  41. private userKey(user: User) {
  42. return this.uiSegmentSrv.newSegment(user.login + ' - ' + user.email);
  43. }
  44. }
  45. export interface User {
  46. id: number;
  47. name: string;
  48. login: string;
  49. email: string;
  50. }
  51. export function userPicker() {
  52. return {
  53. restrict: 'E',
  54. template: template,
  55. controller: UserPickerCtrl,
  56. bindToController: true,
  57. controllerAs: 'ctrl',
  58. scope: {
  59. userLogin: '=',
  60. userId: '=',
  61. }
  62. };
  63. }
  64. coreModule.directive('userPicker', userPicker);