users_select.js 25.5 KB
Newer Older
1
/* eslint-disable func-names, space-before-function-paren, one-var, no-var, prefer-rest-params, wrap-iife, quotes, max-len, one-var-declaration-per-line, vars-on-top, prefer-arrow-callback, consistent-return, comma-dangle, object-shorthand, no-shadow, no-unused-vars, no-else-return, no-self-compare, prefer-template, no-unused-expressions, no-lonely-if, yoda, prefer-spread, no-void, camelcase, no-param-reassign */
2
/* global Issuable */
3
/* global emitSidebarEvent */
4 5

import $ from 'jquery';
6
import _ from 'underscore';
7
import axios from './lib/utils/axios_utils';
8
import ModalStore from './boards/stores/modal_store';
9

10 11
// TODO: remove eventHub hack after code splitting refactor
window.emitSidebarEvent = window.emitSidebarEvent || $.noop;
12

13
function UsersSelect(currentUser, els, options = {}) {
14 15 16 17 18 19 20 21 22 23 24 25 26
  var $els;
  this.users = this.users.bind(this);
  this.user = this.user.bind(this);
  this.usersPath = "/autocomplete/users.json";
  this.userPath = "/autocomplete/users/:id.json";
  if (currentUser != null) {
    if (typeof currentUser === 'object') {
      this.currentUser = currentUser;
    } else {
      this.currentUser = JSON.parse(currentUser);
    }
  }

27 28
  const { handleClick } = options;

29 30 31 32 33 34 35 36 37 38 39
  $els = $(els);

  if (!els) {
    $els = $('.js-user-search');
  }

  $els.each((function(_this) {
    return function(i, dropdown) {
      var options = {};
      var $block, $collapsedSidebar, $dropdown, $loading, $selectbox, $value, abilityName, assignTo, assigneeTemplate, collapsedAssigneeTemplate, defaultLabel, defaultNullUser, firstUser, issueURL, selectedId, selectedIdDefault, showAnyUser, showNullUser, showMenuAbove;
      $dropdown = $(dropdown);
Jacob Schatz's avatar
Jacob Schatz committed
40 41 42 43 44 45 46
      options.projectId = $dropdown.data('projectId');
      options.groupId = $dropdown.data('groupId');
      options.showCurrentUser = $dropdown.data('currentUser');
      options.todoFilter = $dropdown.data('todoFilter');
      options.todoStateFilter = $dropdown.data('todoStateFilter');
      showNullUser = $dropdown.data('nullUser');
      defaultNullUser = $dropdown.data('nullUserDefault');
47
      showMenuAbove = $dropdown.data('showMenuAbove');
Jacob Schatz's avatar
Jacob Schatz committed
48 49 50 51
      showAnyUser = $dropdown.data('anyUser');
      firstUser = $dropdown.data('firstUser');
      options.authorId = $dropdown.data('authorId');
      defaultLabel = $dropdown.data('defaultLabel');
52 53 54
      issueURL = $dropdown.data('issueUpdate');
      $selectbox = $dropdown.closest('.selectbox');
      $block = $selectbox.closest('.block');
Jacob Schatz's avatar
Jacob Schatz committed
55
      abilityName = $dropdown.data('abilityName');
56 57 58 59
      $value = $block.find('.value');
      $collapsedSidebar = $block.find('.sidebar-collapsed-user');
      $loading = $block.find('.block-loading').fadeOut();
      selectedIdDefault = (defaultNullUser && showNullUser) ? 0 : null;
Clement Ho's avatar
Clement Ho committed
60 61 62 63 64
      selectedId = $dropdown.data('selected');

      if (selectedId === undefined) {
        selectedId = selectedIdDefault;
      }
65 66 67

      const assignYourself = function () {
        const unassignedSelected = $dropdown.closest('.selectbox')
Jacob Schatz's avatar
Jacob Schatz committed
68
          .find(`input[name='${$dropdown.data('fieldName')}'][value=0]`);
69 70 71

        if (unassignedSelected) {
          unassignedSelected.remove();
72
        }
Phil Hughes's avatar
Phil Hughes committed
73

74 75 76
        // Save current selected user to the DOM
        const input = document.createElement('input');
        input.type = 'hidden';
Jacob Schatz's avatar
Jacob Schatz committed
77
        input.name = $dropdown.data('fieldName');
78 79 80 81 82

        const currentUserInfo = $dropdown.data('currentUserInfo');

        if (currentUserInfo) {
          input.value = currentUserInfo.id;
83
          input.dataset.meta = _.escape(currentUserInfo.name);
84 85 86
        } else if (_this.currentUser) {
          input.value = _this.currentUser.id;
        }
Phil Hughes's avatar
Phil Hughes committed
87

88 89 90 91 92 93 94 95 96
        if ($selectbox) {
          $dropdown.parent().before(input);
        } else {
          $dropdown.after(input);
        }
      };

      if ($block[0]) {
        $block[0].addEventListener('assignYourself', assignYourself);
Phil Hughes's avatar
Phil Hughes committed
97 98
      }

99 100
      const getSelectedUserInputs = function() {
        return $selectbox
Jacob Schatz's avatar
Jacob Schatz committed
101
          .find(`input[name="${$dropdown.data('fieldName')}"]`);
102 103 104 105 106 107 108 109 110
      };

      const getSelected = function() {
        return getSelectedUserInputs()
          .map((index, input) => parseInt(input.value, 10))
          .get();
      };

      const checkMaxSelect = function() {
Jacob Schatz's avatar
Jacob Schatz committed
111
        const maxSelect = $dropdown.data('maxSelect');
112 113 114 115 116 117
        if (maxSelect) {
          const selected = getSelected();

          if (selected.length > maxSelect) {
            const firstSelectedId = selected[0];
            const firstSelected = $dropdown.closest('.selectbox')
Jacob Schatz's avatar
Jacob Schatz committed
118
              .find(`input[name='${$dropdown.data('fieldName')}'][value=${firstSelectedId}]`);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

            firstSelected.remove();
            emitSidebarEvent('sidebar.removeAssignee', {
              id: firstSelectedId,
            });
          }
        }
      };

      const getMultiSelectDropdownTitle = function(selectedUser, isSelected) {
        const selectedUsers = getSelected()
          .filter(u => u !== 0);

        const firstUser = getSelectedUserInputs()
          .map((index, input) => ({
            name: input.dataset.meta,
            value: parseInt(input.value, 10),
          }))
          .filter(u => u.id !== 0)
          .get(0);

        if (selectedUsers.length === 0) {
          return 'Unassigned';
        } else if (selectedUsers.length === 1) {
          return firstUser.name;
        } else if (isSelected) {
          const otherSelected = selectedUsers.filter(s => s !== selectedUser.id);
          return `${selectedUser.name} + ${otherSelected.length} more`;
        } else {
          return `${firstUser.name} + ${selectedUsers.length - 1} more`;
        }
      };
151

152 153 154
      $('.assign-to-me-link').on('click', (e) => {
        e.preventDefault();
        $(e.currentTarget).hide();
155

156 157 158
        if ($dropdown.data('multiSelect')) {
          assignYourself();
          checkMaxSelect();
159

160 161 162
          const currentUserInfo = $dropdown.data('currentUserInfo');
          $dropdown.find('.dropdown-toggle-text').text(getMultiSelectDropdownTitle(currentUserInfo)).removeClass('is-default');
        } else {
Jacob Schatz's avatar
Jacob Schatz committed
163
          const $input = $(`input[name="${$dropdown.data('fieldName')}"]`);
164 165 166 167 168
          $input.val(gon.current_user_id);
          selectedId = $input.val();
          $dropdown.find('.dropdown-toggle-text').text(gon.current_user_fullname).removeClass('is-default');
        }
      });
169

170 171 172 173
      $block.on('click', '.js-assign-yourself', (e) => {
        e.preventDefault();
        return assignTo(_this.currentUser.id);
      });
174

175 176 177 178 179 180 181 182
      assignTo = function(selected) {
        var data;
        data = {};
        data[abilityName] = {};
        data[abilityName].assignee_id = selected != null ? selected : null;
        $loading.removeClass('hidden').fadeIn();
        $dropdown.trigger('loading.gl.dropdown');

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        return axios.put(issueURL, data)
          .then(({ data }) => {
            var user;
            $dropdown.trigger('loaded.gl.dropdown');
            $loading.fadeOut();
            if (data.assignee) {
              user = {
                name: data.assignee.name,
                username: data.assignee.username,
                avatar: data.assignee.avatar_url
              };
            } else {
              user = {
                name: 'Unassigned',
                username: '',
                avatar: ''
              };
            }
            $value.html(assigneeTemplate(user));
            $collapsedSidebar.attr('title', _.escape(user.name)).tooltip('fixTitle');
            return $collapsedSidebar.html(collapsedAssigneeTemplate(user));
          });
205 206 207 208 209 210 211 212 213 214 215 216 217
      };
      collapsedAssigneeTemplate = _.template('<% if( avatar ) { %> <a class="author_link" href="/<%- username %>"> <img width="24" class="avatar avatar-inline s24" alt="" src="<%- avatar %>"> </a> <% } else { %> <i class="fa fa-user"></i> <% } %>');
      assigneeTemplate = _.template('<% if (username) { %> <a class="author_link bold" href="/<%- username %>"> <% if( avatar ) { %> <img width="32" class="avatar avatar-inline s32" alt="" src="<%- avatar %>"> <% } %> <span class="author"><%- name %></span> <span class="username"> @<%- username %> </span> </a> <% } else { %> <span class="no-value assign-yourself"> No assignee - <a href="#" class="js-assign-yourself"> assign yourself </a> </span> <% } %>');
      return $dropdown.glDropdown({
        showMenuAbove: showMenuAbove,
        data: function(term, callback) {
          return _this.users(term, options, function(users) {
            // GitLabDropdownFilter returns this.instance
            // GitLabDropdownRemote returns this.options.instance
            const glDropdown = this.instance || this.options.instance;
            glDropdown.options.processData(term, users, callback);
          }.bind(this));
        },
Clement Ho's avatar
Clement Ho committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        processData: function(term, data, callback) {
          let users = data;

          // Only show assigned user list when there is no search term
          if ($dropdown.hasClass('js-multiselect') && term.length === 0) {
            const selectedInputs = getSelectedUserInputs();

            // Potential duplicate entries when dealing with issue board
            // because issue board is also managed by vue
            const selectedUsers = _.uniq(selectedInputs, false, a => a.value)
              .filter((input) => {
                const userId = parseInt(input.value, 10);
                const inUsersArray = users.find(u => u.id === userId);

                return !inUsersArray && userId !== 0;
              })
              .map((input) => {
                const userId = parseInt(input.value, 10);
                const { avatarUrl, avatar_url, name, username } = input.dataset;
                return {
                  avatar_url: avatarUrl || avatar_url,
                  id: userId,
                  name,
                  username,
                };
              });

            users = data.concat(selectedUsers);
          }

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
          let anyUser;
          let index;
          let j;
          let len;
          let name;
          let obj;
          let showDivider;
          if (term.length === 0) {
            showDivider = 0;
            if (firstUser) {
              // Move current user to the front of the list
              for (index = j = 0, len = users.length; j < len; index = (j += 1)) {
                obj = users[index];
                if (obj.username === firstUser) {
                  users.splice(index, 1);
                  users.unshift(obj);
                  break;
                }
Clement Ho's avatar
Clement Ho committed
266 267
              }
            }
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            if (showNullUser) {
              showDivider += 1;
              users.unshift({
                beforeDivider: true,
                name: 'Unassigned',
                id: 0
              });
            }
            if (showAnyUser) {
              showDivider += 1;
              name = showAnyUser;
              if (name === true) {
                name = 'Any User';
              }
              anyUser = {
                beforeDivider: true,
                name: name,
                id: null
              };
              users.unshift(anyUser);
288
            }
289

290 291
            if (showDivider) {
              users.splice(showDivider, 0, 'divider');
292
            }
293

294 295
            if ($dropdown.hasClass('js-multiselect')) {
              const selected = getSelected().filter(i => i !== 0);
296

297
              if (selected.length > 0) {
Jacob Schatz's avatar
Jacob Schatz committed
298
                if ($dropdown.data('dropdownHeader')) {
299
                  showDivider += 1;
300
                  users.splice(showDivider, 0, {
Jacob Schatz's avatar
Jacob Schatz committed
301
                    header: $dropdown.data('dropdownHeader'),
302 303 304
                  });
                }

305 306 307
                const selectedUsers = users
                  .filter(u => selected.indexOf(u.id) !== -1)
                  .sort((a, b) => a.name > b.name);
308

309
                users = users.filter(u => selected.indexOf(u.id) === -1);
310

311 312 313 314
                selectedUsers.forEach((selectedUser) => {
                  showDivider += 1;
                  users.splice(showDivider, 0, selectedUser);
                });
315

316 317 318 319
                users.splice(showDivider + 1, 0, 'divider');
              }
            }
          }
320

321 322 323 324 325 326 327 328 329 330 331
          callback(users);
          if (showMenuAbove) {
            $dropdown.data('glDropdown').positionMenuAbove();
          }
        },
        filterable: true,
        filterRemote: true,
        search: {
          fields: ['name', 'username']
        },
        selectable: true,
Jacob Schatz's avatar
Jacob Schatz committed
332
        fieldName: $dropdown.data('fieldName'),
333 334 335 336 337 338 339 340 341 342 343
        toggleLabel: function(selected, el, glDropdown) {
          const inputValue = glDropdown.filterInput.val();

          if (this.multiSelect && inputValue === '') {
            // Remove non-users from the fullData array
            const users = glDropdown.filteredFullData();
            const callback = glDropdown.parseData.bind(glDropdown);

            // Update the data model
            this.processData(inputValue, users, callback);
          }
344

345 346 347
          if (this.multiSelect) {
            return getMultiSelectDropdownTitle(selected, $(el).hasClass('is-active'));
          }
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
          if (selected && 'id' in selected && $(el).hasClass('is-active')) {
            $dropdown.find('.dropdown-toggle-text').removeClass('is-default');
            if (selected.text) {
              return selected.text;
            } else {
              return selected.name;
            }
          } else {
            $dropdown.find('.dropdown-toggle-text').addClass('is-default');
            return defaultLabel;
          }
        },
        defaultLabel: defaultLabel,
        hidden: function(e) {
          if ($dropdown.hasClass('js-multiselect')) {
            emitSidebarEvent('sidebar.saveAssignees');
          }
366

Jacob Schatz's avatar
Jacob Schatz committed
367
          if (!$dropdown.data('alwaysShowSelectbox')) {
368
            $selectbox.hide();
369

370 371 372 373 374 375 376 377
            // Recalculate where .value is because vue might have changed it
            $block = $selectbox.closest('.block');
            $value = $block.find('.value');
            // display:block overrides the hide-collapse rule
            $value.css('display', '');
          }
        },
        multiSelect: $dropdown.hasClass('js-multiselect'),
Jacob Schatz's avatar
Jacob Schatz committed
378
        inputMeta: $dropdown.data('inputMeta'),
379 380 381 382 383 384 385
        clicked: function(options) {
          const { $el, e, isMarking } = options;
          const user = options.selectedObj;

          if ($dropdown.hasClass('js-multiselect')) {
            const isActive = $el.hasClass('is-active');
            const previouslySelected = $dropdown.closest('.selectbox')
Jacob Schatz's avatar
Jacob Schatz committed
386
                .find("input[name='" + ($dropdown.data('fieldName')) + "'][value!=0]");
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

            // Enables support for limiting the number of users selected
            // Automatically removes the first on the list if more users are selected
            checkMaxSelect();

            if (user.beforeDivider && user.name.toLowerCase() === 'unassigned') {
              // Unassigned selected
              previouslySelected.each((index, element) => {
                const id = parseInt(element.value, 10);
                element.remove();
              });
              emitSidebarEvent('sidebar.removeAllAssignees');
            } else if (isActive) {
              // user selected
              emitSidebarEvent('sidebar.addAssignee', user);
402

403 404
              // Remove unassigned selection (if it was previously selected)
              const unassignedSelected = $dropdown.closest('.selectbox')
Jacob Schatz's avatar
Jacob Schatz committed
405
                .find("input[name='" + ($dropdown.data('fieldName')) + "'][value=0]");
406

407 408 409 410 411 412
              if (unassignedSelected) {
                unassignedSelected.remove();
              }
            } else {
              if (previouslySelected.length === 0) {
              // Select unassigned because there is no more selected users
Jacob Schatz's avatar
Jacob Schatz committed
413
                this.addInput($dropdown.data('fieldName'), 0, {});
414 415
              }

416 417 418
              // User unselected
              emitSidebarEvent('sidebar.removeAssignee', user);
            }
419

420 421 422 423 424 425
            if (getSelected().find(u => u === gon.current_user_id)) {
              $('.assign-to-me-link').hide();
            } else {
              $('.assign-to-me-link').show();
            }
          }
426

427
          var isIssueIndex, isMRIndex, page, selected;
428
          page = $('body').attr('data-page');
429 430 431 432
          isIssueIndex = page === 'projects:issues:index';
          isMRIndex = (page === page && page === 'projects:merge_requests:index');
          if ($dropdown.hasClass('js-filter-bulk-update') || $dropdown.hasClass('js-issuable-form-dropdown')) {
            e.preventDefault();
433

434 435
            const isSelecting = (user.id !== selectedId);
            selectedId = isSelecting ? user.id : selectedIdDefault;
436

437 438 439 440 441 442 443 444
            if (selectedId === gon.current_user_id) {
              $('.assign-to-me-link').hide();
            } else {
              $('.assign-to-me-link').show();
            }
            return;
          }
          if ($el.closest('.add-issues-modal').length) {
445
            ModalStore.store.filter[$dropdown.data('fieldName')] = user.id;
446 447 448
          } else if (handleClick) {
            e.preventDefault();
            handleClick(user, isMarking);
449 450 451 452 453
          } else if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
            return Issuable.filterResults($dropdown.closest('form'));
          } else if ($dropdown.hasClass('js-filter-submit')) {
            return $dropdown.closest('form').submit();
          } else if (!$dropdown.hasClass('js-multiselect')) {
Jacob Schatz's avatar
Jacob Schatz committed
454
            selected = $dropdown.closest('.selectbox').find("input[name='" + ($dropdown.data('fieldName')) + "']").val();
455 456
            return assignTo(selected);
          }
Clement Ho's avatar
Clement Ho committed
457

Clement Ho's avatar
Clement Ho committed
458 459 460
          // Automatically close dropdown after assignee is selected
          // since CE has no multiple assignees
          // EE does not have a max-select
Jacob Schatz's avatar
Jacob Schatz committed
461 462
          if ($dropdown.data('maxSelect') &&
              getSelected().length === $dropdown.data('maxSelect')) {
Clement Ho's avatar
Clement Ho committed
463
            // Close the dropdown
Clement Ho's avatar
Clement Ho committed
464
            $dropdown.dropdown('toggle');
Clement Ho's avatar
Clement Ho committed
465
          }
466 467 468 469 470 471
        },
        id: function (user) {
          return user.id;
        },
        opened: function(e) {
          const $el = $(e.currentTarget);
Clement Ho's avatar
Clement Ho committed
472 473
          const selected = getSelected();
          if ($dropdown.hasClass('js-issue-board-sidebar') && selected.length === 0) {
Jacob Schatz's avatar
Jacob Schatz committed
474
            this.addInput($dropdown.data('fieldName'), 0, {});
475 476
          }
          $el.find('.is-active').removeClass('is-active');
Clement Ho's avatar
Clement Ho committed
477

478 479 480
          function highlightSelected(id) {
            $el.find(`li[data-user-id="${id}"] .dropdown-menu-user-link`).addClass('is-active');
          }
Clement Ho's avatar
Clement Ho committed
481

Clement Ho's avatar
Clement Ho committed
482
          if (selected.length > 0) {
483
            getSelected().forEach(selectedId => highlightSelected(selectedId));
Clement Ho's avatar
Clement Ho committed
484 485
          } else if ($dropdown.hasClass('js-issue-board-sidebar')) {
            highlightSelected(0);
486 487 488 489
          } else {
            highlightSelected(selectedId);
          }
        },
Jacob Schatz's avatar
Jacob Schatz committed
490
        updateLabel: $dropdown.data('dropdownTitle'),
491 492 493
        renderRow: function(user) {
          var avatar, img, listClosingTags, listWithName, listWithUserName, username;
          username = user.username ? "@" + user.username : "";
494
          avatar = user.avatar_url ? user.avatar_url : gon.default_avatar_url;
495

Clement Ho's avatar
Clement Ho committed
496
          let selected = false;
497

498
          if (this.multiSelect) {
Clement Ho's avatar
Clement Ho committed
499 500
            selected = getSelected().find(u => user.id === u);

501 502
            const fieldName = this.fieldName;
            const field = $dropdown.closest('.selectbox').find("input[name='" + fieldName + "'][value='" + user.id + "']");
503

504 505 506
            if (field.length) {
              selected = true;
            }
Clement Ho's avatar
Clement Ho committed
507 508
          } else {
            selected = user.id === selectedId;
509
          }
510

511 512
          img = "";
          if (user.beforeDivider != null) {
513
            `<li><a href='#' class='${selected === true ? 'is-active' : ''}'>${_.escape(user.name)}</a></li>`;
514
          } else {
515
            img = "<img src='" + avatar + "' class='avatar avatar-inline' width='32' />";
516
          }
517

518 519 520 521 522
          return `
            <li data-user-id=${user.id}>
              <a href='#' class='dropdown-menu-user-link ${selected === true ? 'is-active' : ''}'>
                ${img}
                <strong class='dropdown-menu-user-full-name'>
523
                  ${_.escape(user.name)}
524 525 526 527 528 529 530 531 532 533 534 535 536 537
                </strong>
                ${username ? `<span class='dropdown-menu-user-username'>${username}</span>` : ''}
              </a>
            </li>
          `;
        }
      });
    };
  })(this));
  $('.ajax-users-select').each((function(_this) {
    return function(i, select) {
      var firstUser, showAnyUser, showEmailUser, showNullUser;
      var options = {};
      options.skipLdap = $(select).hasClass('skip_ldap');
Jacob Schatz's avatar
Jacob Schatz committed
538 539 540 541 542 543 544 545 546
      options.projectId = $(select).data('projectId');
      options.groupId = $(select).data('groupId');
      options.showCurrentUser = $(select).data('currentUser');
      options.authorId = $(select).data('authorId');
      options.skipUsers = $(select).data('skipUsers');
      showNullUser = $(select).data('nullUser');
      showAnyUser = $(select).data('anyUser');
      showEmailUser = $(select).data('emailUser');
      firstUser = $(select).data('firstUser');
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
      return $(select).select2({
        placeholder: "Search for a user",
        multiple: $(select).hasClass('multiselect'),
        minimumInputLength: 0,
        query: function(query) {
          return _this.users(query.term, options, function(users) {
            var anyUser, data, emailUser, index, j, len, name, nullUser, obj, ref;
            data = {
              results: users
            };
            if (query.term.length === 0) {
              if (firstUser) {
                // Move current user to the front of the list
                ref = data.results;
                for (index = j = 0, len = ref.length; j < len; index = (j += 1)) {
                  obj = ref[index];
                  if (obj.username === firstUser) {
                    data.results.splice(index, 1);
                    data.results.unshift(obj);
                    break;
                  }
568 569
                }
              }
570 571 572 573 574 575 576 577 578 579 580
              if (showNullUser) {
                nullUser = {
                  name: 'Unassigned',
                  id: 0
                };
                data.results.unshift(nullUser);
              }
              if (showAnyUser) {
                name = showAnyUser;
                if (name === true) {
                  name = 'Any User';
Fatih Acet's avatar
Fatih Acet committed
581
                }
582 583 584 585 586
                anyUser = {
                  name: name,
                  id: null
                };
                data.results.unshift(anyUser);
Fatih Acet's avatar
Fatih Acet committed
587 588
              }
            }
589 590 591
            if (showEmailUser && data.results.length === 0 && query.term.match(/^[^@]+@[^@]+$/)) {
              var trimmed = query.term.trim();
              emailUser = {
592
                name: "Invite \"" + query.term + "\" by email",
593
                username: trimmed,
594 595
                id: trimmed,
                invite: true
596 597
              };
              data.results.unshift(emailUser);
Fatih Acet's avatar
Fatih Acet committed
598
            }
599
            return query.callback(data);
Fatih Acet's avatar
Fatih Acet committed
600 601
          });
        },
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        initSelection: function() {
          var args;
          args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
          return _this.initSelection.apply(_this, args);
        },
        formatResult: function() {
          var args;
          args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
          return _this.formatResult.apply(_this, args);
        },
        formatSelection: function() {
          var args;
          args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
          return _this.formatSelection.apply(_this, args);
        },
        dropdownCssClass: "ajax-users-dropdown",
        // we do not want to escape markup since we are displaying html in results
        escapeMarkup: function(m) {
          return m;
        }
Fatih Acet's avatar
Fatih Acet committed
622 623
      });
    };
624 625 626 627 628 629 630 631 632
  })(this));
}

UsersSelect.prototype.initSelection = function(element, callback) {
  var id, nullUser;
  id = $(element).val();
  if (id === "0") {
    nullUser = {
      name: 'Unassigned'
Fatih Acet's avatar
Fatih Acet committed
633
    };
634 635 636 637 638 639 640 641 642 643 644 645 646
    return callback(nullUser);
  } else if (id !== "") {
    return this.user(id, callback);
  }
};

UsersSelect.prototype.formatResult = function(user) {
  var avatar;
  if (user.avatar_url) {
    avatar = user.avatar_url;
  } else {
    avatar = gon.default_avatar_url;
  }
647
  return "<div class='user-result " + (!user.username ? 'no-username' : void 0) + "'> <div class='user-image'><img class='avatar avatar-inline s32' src='" + avatar + "'></div> <div class='user-name dropdown-menu-user-full-name'>" + _.escape(user.name) + "</div> <div class='user-username dropdown-menu-user-username'>" + (!user.invite ? "@" + _.escape(user.username) : "") + "</div> </div>";
648 649 650
};

UsersSelect.prototype.formatSelection = function(user) {
651
  return _.escape(user.name);
652 653 654 655 656 657 658 659 660 661
};

UsersSelect.prototype.user = function(user_id, callback) {
  if (!/^\d+$/.test(user_id)) {
    return false;
  }

  var url;
  url = this.buildUrl(this.userPath);
  url = url.replace(':id', user_id);
662 663 664 665
  return axios.get(url)
    .then(({ data }) => {
      callback(data);
    });
666 667 668 669 670
};

// Return users list. Filtered by query
// Only active users retrieved
UsersSelect.prototype.users = function(query, options, callback) {
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
  const url = this.buildUrl(this.usersPath);
  const params = {
    search: query,
    active: true,
    project_id: options.projectId || null,
    group_id: options.groupId || null,
    skip_ldap: options.skipLdap || null,
    todo_filter: options.todoFilter || null,
    todo_state_filter: options.todoStateFilter || null,
    current_user: options.showCurrentUser || null,
    author_id: options.authorId || null,
    skip_users: options.skipUsers || null
  };
  return axios.get(url, { params })
    .then(({ data }) => {
      callback(data);
    });
688 689 690 691 692 693 694 695 696 697
};

UsersSelect.prototype.buildUrl = function(url) {
  if (gon.relative_url_root != null) {
    url = gon.relative_url_root.replace(/\/$/, '') + url;
  }
  return url;
};

export default UsersSelect;