user_picker.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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.debouncedSearchUsers = _.debounce(this.searchUsers, 500, {'leading': true, 'trailing': false});
  19. this.resetUserSegment();
  20. }
  21. resetUserSegment() {
  22. this.userId = null;
  23. const userSegment = this.uiSegmentSrv.newSegment({
  24. value: 'Choose',
  25. selectMode: true,
  26. fake: true,
  27. cssClass: 'gf-size-auto'
  28. });
  29. if (!this.userSegment) {
  30. this.userSegment = userSegment;
  31. } else {
  32. this.userSegment.value = userSegment.value;
  33. this.userSegment.html = userSegment.html;
  34. this.userSegment.value = userSegment.value;
  35. }
  36. }
  37. searchUsers(query: string) {
  38. return Promise.resolve(this.backendSrv.get('/api/users/search?perpage=10&page=1&query=' + query).then(result => {
  39. return _.map(result.users, this.userKey.bind(this));
  40. }));
  41. }
  42. onChange() {
  43. this.userLogin = this.userSegment.value.split(' - ')[0];
  44. this.backendSrv.get('/api/users/search?perpage=10&page=1&query=' + this.userLogin)
  45. .then(result => {
  46. if (!result) {
  47. return;
  48. }
  49. result.users.forEach(u => {
  50. if (u.login === this.userLogin) {
  51. this.userId = u.id;
  52. }
  53. });
  54. });
  55. }
  56. userIdChanged(newVal) {
  57. if (!newVal) {
  58. this.resetUserSegment();
  59. }
  60. }
  61. private userKey(user: User) {
  62. return this.uiSegmentSrv.newSegment(user.login + ' - ' + user.email);
  63. }
  64. }
  65. export interface User {
  66. id: number;
  67. name: string;
  68. login: string;
  69. email: string;
  70. }
  71. export function userPicker() {
  72. return {
  73. restrict: 'E',
  74. template: template,
  75. controller: UserPickerCtrl,
  76. bindToController: true,
  77. controllerAs: 'ctrl',
  78. scope: {
  79. userId: '=',
  80. },
  81. link: function(scope, elem, attrs, ctrl) {
  82. scope.$watch("ctrl.userId", (newVal, oldVal) => {
  83. ctrl.userIdChanged(newVal);
  84. });
  85. }
  86. };
  87. }
  88. coreModule.directive('userPicker', userPicker);