gl_dropdown.js 28.5 KB
Newer Older
1
/* eslint-disable func-names, space-before-function-paren, no-var, one-var, one-var-declaration-per-line, prefer-rest-params, max-len, vars-on-top, wrap-iife, no-unused-vars, quotes, no-shadow, no-cond-assign, prefer-arrow-callback, no-return-assign, no-else-return, camelcase, comma-dangle, no-lonely-if, guard-for-in, no-restricted-syntax, consistent-return, prefer-template, no-param-reassign, no-loop-func, no-mixed-operators */
2 3 4
/* global fuzzaldrinPlus */
/* global Turbolinks */

Fatih Acet's avatar
Fatih Acet committed
5 6
(function() {
  var GitLabDropdown, GitLabDropdownFilter, GitLabDropdownRemote,
7
    bind = function(fn, me) { return function() { return fn.apply(me, arguments); }; },
8
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i += 1) { if (i in this && this[i] === item) return i; } return -1; };
Fatih Acet's avatar
Fatih Acet committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

  GitLabDropdownFilter = (function() {
    var ARROW_KEY_CODES, BLUR_KEYCODES, HAS_VALUE_CLASS;

    BLUR_KEYCODES = [27, 40];

    ARROW_KEY_CODES = [38, 40];

    HAS_VALUE_CLASS = "has-value";

    function GitLabDropdownFilter(input, options) {
      var $clearButton, $inputContainer, ref, timeout;
      this.input = input;
      this.options = options;
      this.filterInputBlur = (ref = this.options.filterInputBlur) != null ? ref : true;
      $inputContainer = this.input.parent();
      $clearButton = $inputContainer.find('.js-dropdown-input-clear');
      $clearButton.on('click', (function(_this) {
27
        // Clear click
Fatih Acet's avatar
Fatih Acet committed
28 29 30
        return function(e) {
          e.preventDefault();
          e.stopPropagation();
31
          return _this.input.val('').trigger('input').focus();
Fatih Acet's avatar
Fatih Acet committed
32 33
        };
      })(this));
34
      // Key events
Fatih Acet's avatar
Fatih Acet committed
35
      timeout = "";
36 37 38
      this.input
        .on('keydown', function (e) {
          var keyCode = e.which;
39
          if (keyCode === 13 && !options.elIsInput) {
40
            e.preventDefault();
41 42
          }
        })
Phil Hughes's avatar
Phil Hughes committed
43
        .on('input', function() {
44
          if (this.input.val() !== "" && !$inputContainer.hasClass(HAS_VALUE_CLASS)) {
Fatih Acet's avatar
Fatih Acet committed
45
            $inputContainer.addClass(HAS_VALUE_CLASS);
46
          } else if (this.input.val() === "" && $inputContainer.hasClass(HAS_VALUE_CLASS)) {
Fatih Acet's avatar
Fatih Acet committed
47 48
            $inputContainer.removeClass(HAS_VALUE_CLASS);
          }
49
          // Only filter asynchronously only if option remote is set
50
          if (this.options.remote) {
Fatih Acet's avatar
Fatih Acet committed
51 52
            clearTimeout(timeout);
            return timeout = setTimeout(function() {
53 54
              return this.options.query(this.input.val(), function(data) {
                return this.options.callback(data);
55 56
              }.bind(this));
            }.bind(this), 250);
Fatih Acet's avatar
Fatih Acet committed
57
          } else {
58
            return this.filter(this.input.val());
Fatih Acet's avatar
Fatih Acet committed
59
          }
60
        }.bind(this));
Fatih Acet's avatar
Fatih Acet committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    }

    GitLabDropdownFilter.prototype.shouldBlur = function(keyCode) {
      return BLUR_KEYCODES.indexOf(keyCode) >= 0;
    };

    GitLabDropdownFilter.prototype.filter = function(search_text) {
      var data, elements, group, key, results, tmp;
      if (this.options.onFilter) {
        this.options.onFilter(search_text);
      }
      data = this.options.data();
      if ((data != null) && !this.options.filterByText) {
        results = data;
        if (search_text !== '') {
76 77 78 79 80
          // When data is an array of objects therefore [object Array] e.g.
          // [
          //   { prop: 'foo' },
          //   { prop: 'baz' }
          // ]
Fatih Acet's avatar
Fatih Acet committed
81 82 83 84 85
          if (_.isArray(data)) {
            results = fuzzaldrinPlus.filter(data, search_text, {
              key: this.options.keys
            });
          } else {
86 87 88 89 90 91 92 93 94 95 96
            // If data is grouped therefore an [object Object]. e.g.
            // {
            //   groupName1: [
            //     { prop: 'foo' },
            //     { prop: 'baz' }
            //   ],
            //   groupName2: [
            //     { prop: 'abc' },
            //     { prop: 'def' }
            //   ]
            // }
Fatih Acet's avatar
Fatih Acet committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            if (gl.utils.isObject(data)) {
              results = {};
              for (key in data) {
                group = data[key];
                tmp = fuzzaldrinPlus.filter(group, search_text, {
                  key: this.options.keys
                });
                if (tmp.length) {
                  results[key] = tmp.map(function(item) {
                    return item;
                  });
                }
              }
            }
          }
        }
        return this.options.callback(results);
      } else {
        elements = this.options.elements();
        if (search_text) {
          return elements.each(function() {
            var $el, matches;
            $el = $(this);
            matches = fuzzaldrinPlus.match($el.text().trim(), search_text);
            if (!$el.is('.dropdown-header')) {
              if (matches.length) {
Luke Bennett's avatar
Luke Bennett committed
123
                return $el.show().removeClass('option-hidden');
Fatih Acet's avatar
Fatih Acet committed
124
              } else {
Luke Bennett's avatar
Luke Bennett committed
125
                return $el.hide().addClass('option-hidden');
Fatih Acet's avatar
Fatih Acet committed
126 127 128 129
              }
            }
          });
        } else {
130
          return elements.show().removeClass('option-hidden');
Fatih Acet's avatar
Fatih Acet committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        }
      }
    };

    return GitLabDropdownFilter;
  })();

  GitLabDropdownRemote = (function() {
    function GitLabDropdownRemote(dataEndpoint, options) {
      this.dataEndpoint = dataEndpoint;
      this.options = options;
    }

    GitLabDropdownRemote.prototype.execute = function() {
      if (typeof this.dataEndpoint === "string") {
        return this.fetchData();
      } else if (typeof this.dataEndpoint === "function") {
        if (this.options.beforeSend) {
          this.options.beforeSend();
        }
        return this.dataEndpoint("", (function(_this) {
152
          // Fetch the data by calling the data funcfion
Fatih Acet's avatar
Fatih Acet committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
          return function(data) {
            if (_this.options.success) {
              _this.options.success(data);
            }
            if (_this.options.beforeSend) {
              return _this.options.beforeSend();
            }
          };
        })(this));
      }
    };

    GitLabDropdownRemote.prototype.fetchData = function() {
      return $.ajax({
        url: this.dataEndpoint,
        dataType: this.options.dataType,
        beforeSend: (function(_this) {
          return function() {
            if (_this.options.beforeSend) {
              return _this.options.beforeSend();
            }
          };
        })(this),
        success: (function(_this) {
          return function(data) {
            if (_this.options.success) {
              return _this.options.success(data);
            }
          };
        })(this)
      });
184
    // Fetch the data through ajax if the data is a string
Fatih Acet's avatar
Fatih Acet committed
185 186 187 188 189 190
    };

    return GitLabDropdownRemote;
  })();

  GitLabDropdown = (function() {
191
    var ACTIVE_CLASS, FILTER_INPUT, INDETERMINATE_CLASS, LOADING_CLASS, PAGE_TWO_CLASS, NON_SELECTABLE_CLASSES, SELECTABLE_CLASSES, CURSOR_SELECT_SCROLL_PADDING, currentIndex;
Fatih Acet's avatar
Fatih Acet committed
192 193 194 195 196 197 198 199 200 201 202

    LOADING_CLASS = "is-loading";

    PAGE_TWO_CLASS = "is-page-two";

    ACTIVE_CLASS = "is-active";

    INDETERMINATE_CLASS = "is-indeterminate";

    currentIndex = -1;

203
    NON_SELECTABLE_CLASSES = '.divider, .separator, .dropdown-header, .dropdown-menu-empty-link';
204

205
    SELECTABLE_CLASSES = ".dropdown-content li:not(" + NON_SELECTABLE_CLASSES + ", .option-hidden)";
206

207
    CURSOR_SELECT_SCROLL_PADDING = 5;
208

Fatih Acet's avatar
Fatih Acet committed
209 210 211
    FILTER_INPUT = '.dropdown-input .dropdown-input-field';

    function GitLabDropdown(el1, options) {
212
      var searchFields, selector, self;
Fatih Acet's avatar
Fatih Acet committed
213 214 215 216 217 218 219 220 221
      this.el = el1;
      this.options = options;
      this.updateLabel = bind(this.updateLabel, this);
      this.hidden = bind(this.hidden, this);
      this.opened = bind(this.opened, this);
      this.shouldPropagate = bind(this.shouldPropagate, this);
      self = this;
      selector = $(this.el).data("target");
      this.dropdown = selector != null ? $(selector) : $(this.el).parent();
222
      // Set Defaults
223
      this.filterInput = this.options.filterInput || this.getElement(FILTER_INPUT);
224
      this.highlight = !!this.options.highlight;
225 226 227
      this.filterInputBlur = this.options.filterInputBlur != null
        ? this.options.filterInputBlur
        : true;
228
      // If no input is passed create a default one
Fatih Acet's avatar
Fatih Acet committed
229
      self = this;
230
      // If selector was passed
Fatih Acet's avatar
Fatih Acet committed
231 232 233 234 235
      if (_.isString(this.filterInput)) {
        this.filterInput = this.getElement(this.filterInput);
      }
      searchFields = this.options.search ? this.options.search.fields : [];
      if (this.options.data) {
236 237
        // If we provided data
        // data could be an array of objects or a group of arrays
Fatih Acet's avatar
Fatih Acet committed
238 239
        if (_.isObject(this.options.data) && !_.isFunction(this.options.data)) {
          this.fullData = this.options.data;
Luke Bennett's avatar
Luke Bennett committed
240
          currentIndex = -1;
Fatih Acet's avatar
Fatih Acet committed
241
          this.parseData(this.options.data);
242
          this.focusTextInput();
Fatih Acet's avatar
Fatih Acet committed
243 244 245 246 247 248 249 250
        } else {
          this.remote = new GitLabDropdownRemote(this.options.data, {
            dataType: this.options.dataType,
            beforeSend: this.toggleLoading.bind(this),
            success: (function(_this) {
              return function(data) {
                _this.fullData = data;
                _this.parseData(_this.fullData);
251
                _this.focusTextInput();
252
                if (_this.options.filterable && _this.filter && _this.filter.input && _this.filter.input.val().trim() !== '') {
253
                  return _this.filter.input.trigger('input');
Fatih Acet's avatar
Fatih Acet committed
254 255
                }
              };
256
            // Remote data
Fatih Acet's avatar
Fatih Acet committed
257 258 259 260
            })(this)
          });
        }
      }
261
      // Init filterable
Fatih Acet's avatar
Fatih Acet committed
262 263
      if (this.options.filterable) {
        this.filter = new GitLabDropdownFilter(this.filterInput, {
264
          elIsInput: $(this.el).is('input'),
Fatih Acet's avatar
Fatih Acet committed
265 266 267 268 269 270 271 272
          filterInputBlur: this.filterInputBlur,
          filterByText: this.options.filterByText,
          onFilter: this.options.onFilter,
          remote: this.options.filterRemote,
          query: this.options.data,
          keys: searchFields,
          elements: (function(_this) {
            return function() {
Luke Bennett's avatar
Luke Bennett committed
273
              selector = '.dropdown-content li:not(' + NON_SELECTABLE_CLASSES + ')';
Fatih Acet's avatar
Fatih Acet committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
              if (_this.dropdown.find('.dropdown-toggle-page').length) {
                selector = ".dropdown-page-one " + selector;
              }
              return $(selector);
            };
          })(this),
          data: (function(_this) {
            return function() {
              return _this.fullData;
            };
          })(this),
          callback: (function(_this) {
            return function(data) {
              _this.parseData(data);
              if (_this.filterInput.val() !== '') {
Luke Bennett's avatar
Luke Bennett committed
289
                selector = SELECTABLE_CLASSES;
Fatih Acet's avatar
Fatih Acet committed
290 291 292
                if (_this.dropdown.find('.dropdown-toggle-page').length) {
                  selector = ".dropdown-page-one " + selector;
                }
293 294 295 296 297 298
                if ($(_this.el).is('input')) {
                  currentIndex = -1;
                } else {
                  $(selector, _this.dropdown).first().find('a').addClass('is-focused');
                  currentIndex = 0;
                }
Fatih Acet's avatar
Fatih Acet committed
299 300 301 302 303
              }
            };
          })(this)
        });
      }
304
      // Event listeners
Fatih Acet's avatar
Fatih Acet committed
305 306 307 308 309 310
      this.dropdown.on("shown.bs.dropdown", this.opened);
      this.dropdown.on("hidden.bs.dropdown", this.hidden);
      $(this.el).on("update.label", this.updateLabel);
      this.dropdown.on("click", ".dropdown-menu, .dropdown-menu-close", this.shouldPropagate);
      this.dropdown.on('keyup', (function(_this) {
        return function(e) {
311
          // Escape key
Fatih Acet's avatar
Fatih Acet committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
          if (e.which === 27) {
            return $('.dropdown-menu-close', _this.dropdown).trigger('click');
          }
        };
      })(this));
      this.dropdown.on('blur', 'a', (function(_this) {
        return function(e) {
          var $dropdownMenu, $relatedTarget;
          if (e.relatedTarget != null) {
            $relatedTarget = $(e.relatedTarget);
            $dropdownMenu = $relatedTarget.closest('.dropdown-menu');
            if ($dropdownMenu.length === 0) {
              return _this.dropdown.removeClass('open');
            }
          }
        };
      })(this));
      if (this.dropdown.find(".dropdown-toggle-page").length) {
        this.dropdown.find(".dropdown-toggle-page, .dropdown-menu-back").on("click", (function(_this) {
          return function(e) {
            e.preventDefault();
            e.stopPropagation();
            return _this.togglePage();
          };
        })(this));
      }
      if (this.options.selectable) {
        selector = ".dropdown-content a";
        if (this.dropdown.find(".dropdown-toggle-page").length) {
          selector = ".dropdown-page-one .dropdown-content a";
        }
        this.dropdown.on("click", selector, function(e) {
344
          var $el, selected, selectedObj, isMarking;
Fatih Acet's avatar
Fatih Acet committed
345 346
          $el = $(this);
          selected = self.rowClicked($el);
347 348
          selectedObj = selected ? selected[0] : null;
          isMarking = selected ? selected[1] : null;
Fatih Acet's avatar
Fatih Acet committed
349
          if (self.options.clicked) {
350
            self.options.clicked(selectedObj, $el, e, isMarking);
Fatih Acet's avatar
Fatih Acet committed
351
          }
352 353 354

          // Update label right after all modifications in dropdown has been done
          if (self.options.toggleLabel) {
355
            self.updateLabel(selectedObj, $el, self);
356 357 358
          }

          $el.trigger('blur');
Fatih Acet's avatar
Fatih Acet committed
359 360 361 362
        });
      }
    }

363
    // Finds an element inside wrapper element
Fatih Acet's avatar
Fatih Acet committed
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    GitLabDropdown.prototype.getElement = function(selector) {
      return this.dropdown.find(selector);
    };

    GitLabDropdown.prototype.toggleLoading = function() {
      return $('.dropdown-menu', this.dropdown).toggleClass(LOADING_CLASS);
    };

    GitLabDropdown.prototype.togglePage = function() {
      var menu;
      menu = $('.dropdown-menu', this.dropdown);
      if (menu.hasClass(PAGE_TWO_CLASS)) {
        if (this.remote) {
          this.remote.execute();
        }
      }
      menu.toggleClass(PAGE_TWO_CLASS);
381
      // Focus first visible input on active page
Fatih Acet's avatar
Fatih Acet committed
382 383 384 385 386 387 388
      return this.dropdown.find('[class^="dropdown-page-"]:visible :text:visible:first').focus();
    };

    GitLabDropdown.prototype.parseData = function(data) {
      var full_html, groupData, html, name;
      this.renderedData = data;
      if (this.options.filterable && data.length === 0) {
389
        // render no matching results
Fatih Acet's avatar
Fatih Acet committed
390 391
        html = [this.noResults()];
      } else {
392
        // Handle array groups
Fatih Acet's avatar
Fatih Acet committed
393 394 395 396 397 398
        if (gl.utils.isObject(data)) {
          html = [];
          for (name in data) {
            groupData = data[name];
            html.push(this.renderItem({
              header: name
399
            // Add header for each group
Fatih Acet's avatar
Fatih Acet committed
400 401 402 403 404 405
            }, name));
            this.renderData(groupData, name).map(function(item) {
              return html.push(item);
            });
          }
        } else {
406
          // Render each row
Fatih Acet's avatar
Fatih Acet committed
407 408 409
          html = this.renderData(data);
        }
      }
410
      // Render the full menu
Fatih Acet's avatar
Fatih Acet committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
      full_html = this.renderMenu(html);
      return this.appendMenu(full_html);
    };

    GitLabDropdown.prototype.renderData = function(data, group) {
      if (group == null) {
        group = false;
      }
      return data.map((function(_this) {
        return function(obj, index) {
          return _this.renderItem(obj, group, index);
        };
      })(this));
    };

    GitLabDropdown.prototype.shouldPropagate = function(e) {
      var $target;
      if (this.options.multiSelect) {
        $target = $(e.target);
430 431 432
        if ($target && !$target.hasClass('dropdown-menu-close') &&
                       !$target.hasClass('dropdown-menu-close-icon') &&
                       !$target.data('is-link')) {
Fatih Acet's avatar
Fatih Acet committed
433 434 435 436 437 438 439 440 441 442
          e.stopPropagation();
          return false;
        } else {
          return true;
        }
      }
    };

    GitLabDropdown.prototype.opened = function() {
      var contentHtml;
443
      this.resetRows();
Fatih Acet's avatar
Fatih Acet committed
444
      this.addArrowKeyEvent();
445

446
      // Makes indeterminate items effective
Fatih Acet's avatar
Fatih Acet committed
447 448 449 450 451 452
      if (this.fullData && this.dropdown.find('.dropdown-menu-toggle').hasClass('js-filter-bulk-update')) {
        this.parseData(this.fullData);
      }
      contentHtml = $('.dropdown-content', this.dropdown).html();
      if (this.remote && contentHtml === "") {
        this.remote.execute();
453 454
      } else {
        this.focusTextInput();
Fatih Acet's avatar
Fatih Acet committed
455
      }
456 457 458 459 460

      if (this.options.showMenuAbove) {
        this.positionMenuAbove();
      }

Fatih Acet's avatar
Fatih Acet committed
461 462 463
      return this.dropdown.trigger('shown.gl.dropdown');
    };

464 465 466 467 468 469 470
    GitLabDropdown.prototype.positionMenuAbove = function() {
      var $button = $(this.el);
      var $menu = this.dropdown.find('.dropdown-menu');

      $menu.css('top', ($button.height() + $menu.height()) * -1);
    };

Fatih Acet's avatar
Fatih Acet committed
471 472
    GitLabDropdown.prototype.hidden = function(e) {
      var $input;
473
      this.resetRows();
Fatih Acet's avatar
Fatih Acet committed
474 475 476
      this.removeArrayKeyEvent();
      $input = this.dropdown.find(".dropdown-input-field");
      if (this.options.filterable) {
477
        $input.blur();
Fatih Acet's avatar
Fatih Acet committed
478 479 480 481 482 483 484 485 486 487
      }
      if (this.dropdown.find(".dropdown-toggle-page").length) {
        $('.dropdown-menu', this.dropdown).removeClass(PAGE_TWO_CLASS);
      }
      if (this.options.hidden) {
        this.options.hidden.call(this, e);
      }
      return this.dropdown.trigger('hidden.gl.dropdown');
    };

488
    // Render the full menu
Fatih Acet's avatar
Fatih Acet committed
489 490
    GitLabDropdown.prototype.renderMenu = function(html) {
      if (this.options.renderMenu) {
491
        return this.options.renderMenu(html);
Fatih Acet's avatar
Fatih Acet committed
492
      } else {
493 494
        var ul = document.createElement('ul');

495
        for (var i = 0; i < html.length; i += 1) {
496 497
          var el = html[i];

498 499 500 501
          if (el instanceof jQuery) {
            el = el.get(0);
          }

502 503 504 505 506
          if (typeof el === 'string') {
            ul.innerHTML += el;
          } else {
            ul.appendChild(el);
          }
507 508 509
        }

        return ul;
Fatih Acet's avatar
Fatih Acet committed
510 511 512
      }
    };

513
    // Append the menu into the dropdown
Fatih Acet's avatar
Fatih Acet committed
514
    GitLabDropdown.prototype.appendMenu = function(html) {
515 516 517 518
      return this.clearMenu().append(html);
    };

    GitLabDropdown.prototype.clearMenu = function() {
Fatih Acet's avatar
Fatih Acet committed
519 520 521 522 523
      var selector;
      selector = '.dropdown-content';
      if (this.dropdown.find(".dropdown-toggle-page").length) {
        selector = ".dropdown-page-one .dropdown-content";
      }
524 525

      return $(selector, this.dropdown).empty();
Fatih Acet's avatar
Fatih Acet committed
526 527 528
    };

    GitLabDropdown.prototype.renderItem = function(data, group, index) {
529
      var field, fieldName, html, selected, text, url, value;
Fatih Acet's avatar
Fatih Acet committed
530 531 532 533
      if (group == null) {
        group = false;
      }
      if (index == null) {
534
        // Render the row
Fatih Acet's avatar
Fatih Acet committed
535 536
        index = false;
      }
537 538 539 540
      html = document.createElement('li');
      if (data === 'divider' || data === 'separator') {
        html.className = data;
        return html;
Fatih Acet's avatar
Fatih Acet committed
541
      }
542
      // Header
Fatih Acet's avatar
Fatih Acet committed
543
      if (data.header != null) {
544 545 546
        html.className = 'dropdown-header';
        html.innerHTML = data.header;
        return html;
Fatih Acet's avatar
Fatih Acet committed
547 548
      }
      if (this.options.renderRow) {
549
        // Call the render function
Fatih Acet's avatar
Fatih Acet committed
550 551 552 553
        html = this.options.renderRow.call(this.options, data, this);
      } else {
        if (!selected) {
          value = this.options.id ? this.options.id(data) : data.id;
554
          fieldName = this.options.fieldName;
555

556
          if (value) { value = value.toString().replace(/'/g, '\\\''); }
557

Fatih Acet's avatar
Fatih Acet committed
558 559 560 561 562
          field = this.dropdown.parent().find("input[name='" + fieldName + "'][value='" + value + "']");
          if (field.length) {
            selected = true;
          }
        }
563
        // Set URL
Fatih Acet's avatar
Fatih Acet committed
564 565 566 567 568
        if (this.options.url != null) {
          url = this.options.url(data);
        } else {
          url = data.url != null ? data.url : '#';
        }
569
        // Set Text
Fatih Acet's avatar
Fatih Acet committed
570 571 572 573 574 575 576 577
        if (this.options.text != null) {
          text = this.options.text(data);
        } else {
          text = data.text != null ? data.text : '';
        }
        if (this.highlight) {
          text = this.highlightTextMatches(text, this.filterInput.val());
        }
578 579 580 581 582 583 584 585 586 587
        // Create the list item & the link
        var link = document.createElement('a');

        link.href = url;
        link.innerHTML = text;

        if (selected) {
          link.className = 'is-active';
        }

Fatih Acet's avatar
Fatih Acet committed
588
        if (group) {
589 590
          link.dataset.group = group;
          link.dataset.index = index;
Fatih Acet's avatar
Fatih Acet committed
591
        }
592 593

        html.appendChild(link);
Fatih Acet's avatar
Fatih Acet committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
      }
      return html;
    };

    GitLabDropdown.prototype.highlightTextMatches = function(text, term) {
      var occurrences;
      occurrences = fuzzaldrinPlus.match(text, term);
      return text.split('').map(function(character, i) {
        if (indexOf.call(occurrences, i) >= 0) {
          return "<b>" + character + "</b>";
        } else {
          return character;
        }
      }).join('');
    };

    GitLabDropdown.prototype.noResults = function() {
      var html;
      return html = "<li class='dropdown-menu-empty-link'> <a href='#' class='is-focused'> No matching results. </a> </li>";
    };

    GitLabDropdown.prototype.rowClicked = function(el) {
Alfredo Sumaran's avatar
Alfredo Sumaran committed
616
      var field, fieldName, groupName, isInput, selectedIndex, selectedObject, value, isMarking;
617

618
      fieldName = this.options.fieldName;
Fatih Acet's avatar
Fatih Acet committed
619 620 621 622 623 624 625 626 627 628 629
      isInput = $(this.el).is('input');
      if (this.renderedData) {
        groupName = el.data('group');
        if (groupName) {
          selectedIndex = el.data('index');
          selectedObject = this.renderedData[groupName][selectedIndex];
        } else {
          selectedIndex = el.closest('li').index();
          selectedObject = this.renderedData[selectedIndex];
        }
      }
630 631 632 633 634 635 636 637

      if (this.options.vue) {
        if (el.hasClass(ACTIVE_CLASS)) {
          el.removeClass(ACTIVE_CLASS);
        } else {
          el.addClass(ACTIVE_CLASS);
        }

638
        return [selectedObject];
639 640
      }

641
      field = [];
642 643 644
      value = this.options.id
        ? this.options.id(selectedObject, el)
        : selectedObject.id;
Fatih Acet's avatar
Fatih Acet committed
645 646
      if (isInput) {
        field = $(this.el);
647
      } else if (value) {
648
        field = this.dropdown.parent().find("input[name='" + fieldName + "'][value='" + value.toString().replace(/'/g, '\\\'') + "']");
Fatih Acet's avatar
Fatih Acet committed
649
      }
Phil Hughes's avatar
Phil Hughes committed
650 651 652 653 654

      if (this.options.isSelectable && !this.options.isSelectable(selectedObject, el)) {
        return;
      }

655
      if (el.hasClass(ACTIVE_CLASS)) {
656
        isMarking = false;
Fatih Acet's avatar
Fatih Acet committed
657
        el.removeClass(ACTIVE_CLASS);
658
        if (field && field.length) {
659
          this.clearField(field, isInput);
Fatih Acet's avatar
Fatih Acet committed
660 661
        }
      } else if (el.hasClass(INDETERMINATE_CLASS)) {
662
        isMarking = true;
Fatih Acet's avatar
Fatih Acet committed
663 664
        el.addClass(ACTIVE_CLASS);
        el.removeClass(INDETERMINATE_CLASS);
665
        if (field && field.length && value == null) {
666
          this.clearField(field, isInput);
Fatih Acet's avatar
Fatih Acet committed
667
        }
668
        if ((!field || !field.length) && fieldName) {
669
          this.addInput(fieldName, value, selectedObject);
Fatih Acet's avatar
Fatih Acet committed
670 671
        }
      } else {
672
        isMarking = true;
Fatih Acet's avatar
Fatih Acet committed
673 674 675 676 677 678
        if (!this.options.multiSelect || el.hasClass('dropdown-clear-active')) {
          this.dropdown.find("." + ACTIVE_CLASS).removeClass(ACTIVE_CLASS);
          if (!isInput) {
            this.dropdown.parent().find("input[name='" + fieldName + "']").remove();
          }
        }
679
        if (field && field.length && value == null) {
680
          this.clearField(field, isInput);
Fatih Acet's avatar
Fatih Acet committed
681
        }
682
        // Toggle active class for the tick mark
Fatih Acet's avatar
Fatih Acet committed
683 684
        el.addClass(ACTIVE_CLASS);
        if (value != null) {
685
          if ((!field || !field.length) && fieldName) {
686
            this.addInput(fieldName, value, selectedObject);
687
          } else if (field && field.length) {
Fatih Acet's avatar
Fatih Acet committed
688 689 690 691
            field.val(value).trigger('change');
          }
        }
      }
692

693
      return [selectedObject, isMarking];
Fatih Acet's avatar
Fatih Acet committed
694 695
    };

696
    GitLabDropdown.prototype.focusTextInput = function() {
697 698
      if (this.options.filterable) { this.filterInput.focus(); }
    };
699

700
    GitLabDropdown.prototype.addInput = function(fieldName, value, selectedObject) {
Fatih Acet's avatar
Fatih Acet committed
701
      var $input;
702
      // Create hidden input for form
Fatih Acet's avatar
Fatih Acet committed
703 704 705 706 707 708 709
      $input = $('<input>').attr('type', 'hidden').attr('name', fieldName).val(value);
      if (this.options.inputId != null) {
        $input.attr('id', this.options.inputId);
      }
      return this.dropdown.before($input);
    };

710
    GitLabDropdown.prototype.selectRowAtIndex = function(index) {
Fatih Acet's avatar
Fatih Acet committed
711
      var $el, selector;
712 713 714 715 716 717
      // If we pass an option index
      if (typeof index !== "undefined") {
        selector = SELECTABLE_CLASSES + ":eq(" + index + ") a";
      } else {
        selector = ".dropdown-content .is-focused";
      }
Fatih Acet's avatar
Fatih Acet committed
718 719 720
      if (this.dropdown.find(".dropdown-toggle-page").length) {
        selector = ".dropdown-page-one " + selector;
      }
721
      // simulate a click on the first link
Fatih Acet's avatar
Fatih Acet committed
722 723
      $el = $(selector, this.dropdown);
      if ($el.length) {
Luke Bennett's avatar
Luke Bennett committed
724
        var href = $el.attr('href');
725 726 727 728 729
        if (href && href !== '#') {
          Turbolinks.visit(href);
        } else {
          $el.first().trigger('click');
        }
Fatih Acet's avatar
Fatih Acet committed
730 731 732 733 734 735 736
      }
    };

    GitLabDropdown.prototype.addArrowKeyEvent = function() {
      var $input, ARROW_KEY_CODES, selector;
      ARROW_KEY_CODES = [38, 40];
      $input = this.dropdown.find(".dropdown-input-field");
737
      selector = SELECTABLE_CLASSES;
Fatih Acet's avatar
Fatih Acet committed
738 739 740 741 742 743 744 745 746 747 748 749
      if (this.dropdown.find(".dropdown-toggle-page").length) {
        selector = ".dropdown-page-one " + selector;
      }
      return $('body').on('keydown', (function(_this) {
        return function(e) {
          var $listItems, PREV_INDEX, currentKeyCode;
          currentKeyCode = e.which;
          if (ARROW_KEY_CODES.indexOf(currentKeyCode) >= 0) {
            e.preventDefault();
            e.stopImmediatePropagation();
            PREV_INDEX = currentIndex;
            $listItems = $(selector, _this.dropdown);
750 751
            // if @options.filterable
            //   $input.blur()
Fatih Acet's avatar
Fatih Acet committed
752
            if (currentKeyCode === 40) {
753
              // Move down
Fatih Acet's avatar
Fatih Acet committed
754 755 756 757
              if (currentIndex < ($listItems.length - 1)) {
                currentIndex += 1;
              }
            } else if (currentKeyCode === 38) {
758
              // Move up
Fatih Acet's avatar
Fatih Acet committed
759 760 761 762 763 764 765 766 767 768
              if (currentIndex > 0) {
                currentIndex -= 1;
              }
            }
            if (currentIndex !== PREV_INDEX) {
              _this.highlightRowAtIndex($listItems, currentIndex);
            }
            return false;
          }
          if (currentKeyCode === 13 && currentIndex !== -1) {
769
            e.preventDefault();
770
            _this.selectRowAtIndex();
Fatih Acet's avatar
Fatih Acet committed
771 772 773 774 775 776 777 778 779
          }
        };
      })(this));
    };

    GitLabDropdown.prototype.removeArrayKeyEvent = function() {
      return $('body').off('keydown');
    };

780
    GitLabDropdown.prototype.resetRows = function resetRows() {
Luke Bennett's avatar
Luke Bennett committed
781 782
      currentIndex = -1;
      $('.is-focused', this.dropdown).removeClass('is-focused');
783 784
    };

Fatih Acet's avatar
Fatih Acet committed
785 786
    GitLabDropdown.prototype.highlightRowAtIndex = function($listItems, index) {
      var $dropdownContent, $listItem, dropdownContentBottom, dropdownContentHeight, dropdownContentTop, dropdownScrollTop, listItemBottom, listItemHeight, listItemTop;
787
      // Remove the class for the previously focused row
Fatih Acet's avatar
Fatih Acet committed
788
      $('.is-focused', this.dropdown).removeClass('is-focused');
789
      // Update the class for the row at the specific index
Fatih Acet's avatar
Fatih Acet committed
790 791
      $listItem = $listItems.eq(index);
      $listItem.find('a:first-child').addClass("is-focused");
792
      // Dropdown content scroll area
Fatih Acet's avatar
Fatih Acet committed
793 794 795 796 797
      $dropdownContent = $listItem.closest('.dropdown-content');
      dropdownScrollTop = $dropdownContent.scrollTop();
      dropdownContentHeight = $dropdownContent.outerHeight();
      dropdownContentTop = $dropdownContent.prop('offsetTop');
      dropdownContentBottom = dropdownContentTop + dropdownContentHeight;
798
      // Get the offset bottom of the list item
Fatih Acet's avatar
Fatih Acet committed
799 800 801
      listItemHeight = $listItem.outerHeight();
      listItemTop = $listItem.prop('offsetTop');
      listItemBottom = listItemTop + listItemHeight;
802
      if (!index) {
803
        // Scroll the dropdown content to the top
804
        $dropdownContent.scrollTop(0);
Luke Bennett's avatar
Luke Bennett committed
805
      } else if (index === ($listItems.length - 1)) {
806
        // Scroll the dropdown content to the bottom
Luke Bennett's avatar
Luke Bennett committed
807
        $dropdownContent.scrollTop($dropdownContent.prop('scrollHeight'));
Luke Bennett's avatar
Luke Bennett committed
808
      } else if (listItemBottom > (dropdownContentBottom + dropdownScrollTop)) {
809
        // Scroll the dropdown content down
810 811
        $dropdownContent.scrollTop(listItemBottom - dropdownContentBottom + CURSOR_SELECT_SCROLL_PADDING);
      } else if (listItemTop < (dropdownContentTop + dropdownScrollTop)) {
812
        // Scroll the dropdown content up
813
        return $dropdownContent.scrollTop(listItemTop - dropdownContentTop - CURSOR_SELECT_SCROLL_PADDING);
Fatih Acet's avatar
Fatih Acet committed
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
      }
    };

    GitLabDropdown.prototype.updateLabel = function(selected, el, instance) {
      if (selected == null) {
        selected = null;
      }
      if (el == null) {
        el = null;
      }
      if (instance == null) {
        instance = null;
      }
      return $(this.el).find(".dropdown-toggle-text").text(this.options.toggleLabel(selected, el, instance));
    };

830 831 832 833
    GitLabDropdown.prototype.clearField = function(field, isInput) {
      return isInput ? field.val('') : field.remove();
    };

Fatih Acet's avatar
Fatih Acet committed
834 835 836 837 838 839 840 841 842 843
    return GitLabDropdown;
  })();

  $.fn.glDropdown = function(opts) {
    return this.each(function() {
      if (!$.data(this, 'glDropdown')) {
        return $.data(this, 'glDropdown', new GitLabDropdown(this, opts));
      }
    });
  };
844
}).call(this);