users_select.js 15.1 KB
Newer Older
F
Fatih Acet 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(function() {
  var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    slice = [].slice;

  this.UsersSelect = (function() {
    function UsersSelect(currentUser) {
      this.users = bind(this.users, this);
      this.user = bind(this.user, this);
      this.usersPath = "/autocomplete/users.json";
      this.userPath = "/autocomplete/users/:id.json";
      if (currentUser != null) {
        this.currentUser = JSON.parse(currentUser);
      }
      $('.js-user-search').each((function(_this) {
        return function(i, dropdown) {
16
          var options = {};
F
Fatih Acet 已提交
17 18
          var $block, $collapsedSidebar, $dropdown, $loading, $selectbox, $value, abilityName, assignTo, assigneeTemplate, collapsedAssigneeTemplate, defaultLabel, firstUser, issueURL, selectedId, showAnyUser, showNullUser;
          $dropdown = $(dropdown);
19 20
          options.projectId = $dropdown.data('project-id');
          options.showCurrentUser = $dropdown.data('current-user');
F
Fatih Acet 已提交
21 22 23
          showNullUser = $dropdown.data('null-user');
          showAnyUser = $dropdown.data('any-user');
          firstUser = $dropdown.data('first-user');
24
          options.authorId = $dropdown.data('author-id');
F
Fatih Acet 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
          selectedId = $dropdown.data('selected');
          defaultLabel = $dropdown.data('default-label');
          issueURL = $dropdown.data('issueUpdate');
          $selectbox = $dropdown.closest('.selectbox');
          $block = $selectbox.closest('.block');
          abilityName = $dropdown.data('ability-name');
          $value = $block.find('.value');
          $collapsedSidebar = $block.find('.sidebar-collapsed-user');
          $loading = $block.find('.block-loading').fadeOut();
          $block.on('click', '.js-assign-yourself', function(e) {
            e.preventDefault();
            return assignTo(_this.currentUser.id);
          });
          assignTo = function(selected) {
            var data;
            data = {};
            data[abilityName] = {};
            data[abilityName].assignee_id = selected != null ? selected : null;
            $loading.fadeIn();
            $dropdown.trigger('loading.gl.dropdown');
            return $.ajax({
              type: 'PUT',
              dataType: 'json',
              url: issueURL,
              data: data
            }).done(function(data) {
              var user;
              $dropdown.trigger('loaded.gl.dropdown');
              $loading.fadeOut();
              $selectbox.hide();
              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', user.name).tooltip('fixTitle');
              return $collapsedSidebar.html(collapsedAssigneeTemplate(user));
            });
          };
          collapsedAssigneeTemplate = _.template('<% if( avatar ) { %> <a class="author_link" href="/u/<%- 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="/u/<%- 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({
            data: function(term, callback) {
              var isAuthorFilter;
              isAuthorFilter = $('.js-author-search');
79
              return _this.users(term, options, function(users) {
F
Fatih Acet 已提交
80 81 82 83
                var anyUser, index, j, len, name, obj, showDivider;
                if (term.length === 0) {
                  showDivider = 0;
                  if (firstUser) {
84
                    // Move current user to the front of the list
F
Fatih Acet 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
                    for (index = j = 0, len = users.length; j < len; index = ++j) {
                      obj = users[index];
                      if (obj.username === firstUser) {
                        users.splice(index, 1);
                        users.unshift(obj);
                        break;
                      }
                    }
                  }
                  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);
                  }
                }
                if (showDivider) {
                  users.splice(showDivider, 0, "divider");
                }
119
                // Send the data back
F
Fatih Acet 已提交
120 121 122 123 124 125 126 127 128 129
                return callback(users);
              });
            },
            filterable: true,
            filterRemote: true,
            search: {
              fields: ['name', 'username']
            },
            selectable: true,
            fieldName: $dropdown.data('field-name'),
130 131
            toggleLabel: function(selected, el) {
              if (selected && 'id' in selected && $(el).hasClass('is-active')) {
F
Fatih Acet 已提交
132 133 134 135 136 137 138 139 140
                if (selected.text) {
                  return selected.text;
                } else {
                  return selected.name;
                }
              } else {
                return defaultLabel;
              }
            },
141
            defaultLabel: defaultLabel,
F
Fatih Acet 已提交
142 143 144
            inputId: 'issue_assignee_id',
            hidden: function(e) {
              $selectbox.hide();
145
              // display:block overrides the hide-collapse rule
F
Fatih Acet 已提交
146 147
              return $value.css('display', '');
            },
P
Phil Hughes 已提交
148
            clicked: function(user, $el, e) {
F
Fatih Acet 已提交
149 150 151 152
              var isIssueIndex, isMRIndex, page, selected;
              page = $('body').data('page');
              isIssueIndex = page === 'projects:issues:index';
              isMRIndex = (page === page && page === 'projects:merge_requests:index');
153 154 155
              if ($dropdown.hasClass('js-filter-bulk-update') || $dropdown.hasClass('js-issuable-form-dropdown')) {
                e.preventDefault();
                selectedId = user.id;
F
Fatih Acet 已提交
156 157
                return;
              }
P
Phil Hughes 已提交
158
              if (page === 'projects:boards:show') {
P
Phil Hughes 已提交
159
                selectedId = user.id;
160 161
                gl.issueBoards.BoardsStore.state.filters[$dropdown.data('field-name')] = user.id;
                gl.issueBoards.BoardsStore.updateFiltersUrl();
P
Phil Hughes 已提交
162
                e.preventDefault();
P
Phil Hughes 已提交
163
              } else if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
F
Fatih Acet 已提交
164 165 166 167 168 169 170 171 172
                selectedId = user.id;
                return Issuable.filterResults($dropdown.closest('form'));
              } else if ($dropdown.hasClass('js-filter-submit')) {
                return $dropdown.closest('form').submit();
              } else {
                selected = $dropdown.closest('.selectbox').find("input[name='" + ($dropdown.data('field-name')) + "']").val();
                return assignTo(selected);
              }
            },
173 174 175
            id: function (user) {
              return user.id;
            },
F
Fatih Acet 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188
            renderRow: function(user) {
              var avatar, img, listClosingTags, listWithName, listWithUserName, selected, username;
              username = user.username ? "@" + user.username : "";
              avatar = user.avatar_url ? user.avatar_url : false;
              selected = user.id === selectedId ? "is-active" : "";
              img = "";
              if (user.beforeDivider != null) {
                "<li> <a href='#' class='" + selected + "'> " + user.name + " </a> </li>";
              } else {
                if (avatar) {
                  img = "<img src='" + avatar + "' class='avatar avatar-inline' width='30' />";
                }
              }
189
              // split into three parts so we can remove the username section if nessesary
F
Fatih Acet 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203
              listWithName = "<li> <a href='#' class='dropdown-menu-user-link " + selected + "'> " + img + " <strong class='dropdown-menu-user-full-name'> " + user.name + " </strong>";
              listWithUserName = "<span class='dropdown-menu-user-username'> " + username + " </span>";
              listClosingTags = "</a> </li>";
              if (username === '') {
                listWithUserName = '';
              }
              return listWithName + listWithUserName + listClosingTags;
            }
          });
        };
      })(this));
      $('.ajax-users-select').each((function(_this) {
        return function(i, select) {
          var firstUser, showAnyUser, showEmailUser, showNullUser;
204 205 206 207 208 209 210 211
          var options = {};
          options.skipLdap = $(select).hasClass('skip_ldap');
          options.projectId = $(select).data('project-id');
          options.groupId = $(select).data('group-id');
          options.showCurrentUser = $(select).data('current-user');
          options.pushCodeToProtectedBranches = $(select).data('push-code-to-protected-branches');
          options.authorId = $(select).data('author-id');
          options.skipUsers = $(select).data('skip-users');
F
Fatih Acet 已提交
212 213 214 215 216 217 218 219 220
          showNullUser = $(select).data('null-user');
          showAnyUser = $(select).data('any-user');
          showEmailUser = $(select).data('email-user');
          firstUser = $(select).data('first-user');
          return $(select).select2({
            placeholder: "Search for a user",
            multiple: $(select).hasClass('multiselect'),
            minimumInputLength: 0,
            query: function(query) {
221
              return _this.users(query.term, options, function(users) {
F
Fatih Acet 已提交
222 223 224 225 226 227
                var anyUser, data, emailUser, index, j, len, name, nullUser, obj, ref;
                data = {
                  results: users
                };
                if (query.term.length === 0) {
                  if (firstUser) {
228
                    // Move current user to the front of the list
F
Fatih Acet 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
                    ref = data.results;
                    for (index = j = 0, len = ref.length; j < len; index = ++j) {
                      obj = ref[index];
                      if (obj.username === firstUser) {
                        data.results.splice(index, 1);
                        data.results.unshift(obj);
                        break;
                      }
                    }
                  }
                  if (showNullUser) {
                    nullUser = {
                      name: 'Unassigned',
                      id: 0
                    };
                    data.results.unshift(nullUser);
                  }
                  if (showAnyUser) {
                    name = showAnyUser;
                    if (name === true) {
                      name = 'Any User';
                    }
                    anyUser = {
                      name: name,
                      id: null
                    };
                    data.results.unshift(anyUser);
                  }
                }
                if (showEmailUser && data.results.length === 0 && query.term.match(/^[^@]+@[^@]+$/)) {
                  emailUser = {
                    name: "Invite \"" + query.term + "\"",
                    username: query.term,
                    id: query.term
                  };
                  data.results.unshift(emailUser);
                }
                return query.callback(data);
              });
            },
            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",
285
            // we do not want to escape markup since we are displaying html in results
F
Fatih Acet 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            escapeMarkup: function(m) {
              return m;
            }
          });
        };
      })(this));
    }

    UsersSelect.prototype.initSelection = function(element, callback) {
      var id, nullUser;
      id = $(element).val();
      if (id === "0") {
        nullUser = {
          name: 'Unassigned'
        };
        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;
      }
      return "<div class='user-result " + (!user.username ? 'no-username' : void 0) + "'> <div class='user-image'><img class='avatar s24' src='" + avatar + "'></div> <div class='user-name'>" + user.name + "</div> <div class='user-username'>" + (user.username || "") + "</div> </div>";
    };

    UsersSelect.prototype.formatSelection = function(user) {
      return user.name;
    };

    UsersSelect.prototype.user = function(user_id, callback) {
      var url;
      url = this.buildUrl(this.userPath);
      url = url.replace(':id', user_id);
      return $.ajax({
        url: url,
        dataType: "json"
      }).done(function(user) {
        return callback(user);
      });
    };

333 334
    // Return users list. Filtered by query
    // Only active users retrieved
335
    UsersSelect.prototype.users = function(query, options, callback) {
F
Fatih Acet 已提交
336 337 338 339 340 341 342 343
      var url;
      url = this.buildUrl(this.usersPath);
      return $.ajax({
        url: url,
        data: {
          search: query,
          per_page: 20,
          active: true,
344 345 346 347 348 349 350
          project_id: options.projectId || null,
          group_id: options.groupId || null,
          skip_ldap: options.skipLdap || null,
          current_user: options.showCurrentUser || null,
          push_code_to_protected_branches: options.pushCodeToProtectedBranches || null,
          author_id: options.authorId || null,
          skip_users: options.skipUsers || null
F
Fatih Acet 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        },
        dataType: "json"
      }).done(function(users) {
        return callback(users);
      });
    };

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

    return UsersSelect;

  })();

}).call(this);