gl_dropdown.js 31.3 KB
Newer Older
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
1
/* eslint-disable func-names, no-underscore-dangle, 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
/* global fuzzaldrinPlus */
3 4

import $ from 'jquery';
5
import _ from 'underscore';
6
import fuzzaldrinPlus from 'fuzzaldrin-plus';
7
import axios from './lib/utils/axios_utils';
Phil Hughes's avatar
Phil Hughes committed
8
import { visitUrl } from './lib/utils/url_utility';
9
import { isObject } from './lib/utils/type_utility';
10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
var GitLabDropdown, GitLabDropdownFilter, GitLabDropdownRemote, GitLabDropdownInput;

GitLabDropdownInput = (function() {
  function GitLabDropdownInput(input, options) {
    var $inputContainer, $clearButton;
    var _this = this;
    this.input = input;
    this.options = options;
    this.fieldName = this.options.fieldName || 'field-name';
    $inputContainer = this.input.parent();
    $clearButton = $inputContainer.find('.js-dropdown-input-clear');
    $clearButton.on('click', (function(_this) {
      // Clear click
      return function(e) {
        e.preventDefault();
        e.stopPropagation();
        return _this.input.val('').trigger('input').focus();
      };
    })(this));

    this.input
    .on('keydown', function (e) {
      var keyCode = e.which;
      if (keyCode === 13 && !options.elIsInput) {
        e.preventDefault();
      }
    })
    .on('input', function(e) {
39
      var val = e.currentTarget.value || _this.options.inputFieldName;
40
      val = val.split(' ').join('-') // replaces space with dash
41
        .replace(/[^a-zA-Z0-9 -]/g, '').toLowerCase() // replace non alphanumeric
42 43 44 45 46 47 48 49 50 51
        .replace(/(-)\1+/g, '-'); // replace repeated dashes
      _this.cb(_this.options.fieldName, val, {}, true);
      _this.input.closest('.dropdown')
        .find('.dropdown-toggle-text')
        .text(val);
    });
  }

  GitLabDropdownInput.prototype.onInput = function(cb) {
    this.cb = cb;
52
  };
53 54 55

  return GitLabDropdownInput;
})();
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

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) {
      // Clear click
      return function(e) {
        e.preventDefault();
        e.stopPropagation();
        return _this.input.val('').trigger('input').focus();
      };
    })(this));
    // Key events
    timeout = "";
    this.input
      .on('keydown', function (e) {
        var keyCode = e.which;
        if (keyCode === 13 && !options.elIsInput) {
Fatih Acet's avatar
Fatih Acet committed
87
          e.preventDefault();
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        }
      })
      .on('input', function() {
        if (this.input.val() !== "" && !$inputContainer.hasClass(HAS_VALUE_CLASS)) {
          $inputContainer.addClass(HAS_VALUE_CLASS);
        } else if (this.input.val() === "" && $inputContainer.hasClass(HAS_VALUE_CLASS)) {
          $inputContainer.removeClass(HAS_VALUE_CLASS);
        }
        // Only filter asynchronously only if option remote is set
        if (this.options.remote) {
          clearTimeout(timeout);
          return timeout = setTimeout(function() {
            $inputContainer.parent().addClass('is-loading');

            return this.options.query(this.input.val(), function(data) {
              $inputContainer.parent().removeClass('is-loading');
              return this.options.callback(data);
            }.bind(this));
          }.bind(this), 250);
        } else {
          return this.filter(this.input.val());
        }
      }.bind(this));
  }
Fatih Acet's avatar
Fatih Acet committed
112

113 114 115
  GitLabDropdownFilter.prototype.shouldBlur = function(keyCode) {
    return BLUR_KEYCODES.indexOf(keyCode) !== -1;
  };
Fatih Acet's avatar
Fatih Acet committed
116

117 118 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
  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 !== '') {
        // When data is an array of objects therefore [object Array] e.g.
        // [
        //   { prop: 'foo' },
        //   { prop: 'baz' }
        // ]
        if (_.isArray(data)) {
          results = fuzzaldrinPlus.filter(data, search_text, {
            key: this.options.keys
          });
        } else {
          // If data is grouped therefore an [object Object]. e.g.
          // {
          //   groupName1: [
          //     { prop: 'foo' },
          //     { prop: 'baz' }
          //   ],
          //   groupName2: [
          //     { prop: 'abc' },
          //     { prop: 'def' }
          //   ]
          // }
147
          if (isObject(data)) {
148 149 150 151 152 153 154 155 156
            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;
Fatih Acet's avatar
Fatih Acet committed
157 158 159 160 161
                });
              }
            }
          }
        }
162 163 164 165 166
      }
      return this.options.callback(results);
    } else {
      elements = this.options.elements();
      if (search_text) {
167
        elements.each(function() {
168 169 170 171 172 173 174 175
          var $el, matches;
          $el = $(this);
          matches = fuzzaldrinPlus.match($el.text().trim(), search_text);
          if (!$el.is('.dropdown-header')) {
            if (matches.length) {
              return $el.show().removeClass('option-hidden');
            } else {
              return $el.hide().addClass('option-hidden');
Fatih Acet's avatar
Fatih Acet committed
176
            }
177 178 179
          }
        });
      } else {
180
        elements.show().removeClass('option-hidden');
Fatih Acet's avatar
Fatih Acet committed
181
      }
182

183
      elements.parent().find('.dropdown-menu-empty-item').toggleClass('hidden', elements.is(':visible'));
184 185
    }
  };
Fatih Acet's avatar
Fatih Acet committed
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  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) {
        // Fetch the data by calling the data funcfion
        return function(data) {
          if (_this.options.success) {
            _this.options.success(data);
          }
          if (_this.options.beforeSend) {
            return _this.options.beforeSend();
          }
        };
      })(this));
Fatih Acet's avatar
Fatih Acet committed
214
    }
215
  };
Fatih Acet's avatar
Fatih Acet committed
216

217
  GitLabDropdownRemote.prototype.fetchData = function() {
218 219 220 221 222 223 224 225 226 227 228
    if (this.options.beforeSend) {
      this.options.beforeSend();
    }

    // Fetch the data through ajax if the data is a string
    return axios.get(this.dataEndpoint)
      .then(({ data }) => {
        if (this.options.success) {
          return this.options.success(data);
        }
      });
229
  };
Fatih Acet's avatar
Fatih Acet committed
230

231 232
  return GitLabDropdownRemote;
})();
Fatih Acet's avatar
Fatih Acet committed
233

234
GitLabDropdown = (function() {
235
  var ACTIVE_CLASS, FILTER_INPUT, NO_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
236

237
  LOADING_CLASS = "is-loading";
Fatih Acet's avatar
Fatih Acet committed
238

239
  PAGE_TWO_CLASS = "is-page-two";
Fatih Acet's avatar
Fatih Acet committed
240

241
  ACTIVE_CLASS = "is-active";
Fatih Acet's avatar
Fatih Acet committed
242

243
  INDETERMINATE_CLASS = "is-indeterminate";
Fatih Acet's avatar
Fatih Acet committed
244

245
  currentIndex = -1;
Fatih Acet's avatar
Fatih Acet committed
246

247
  NON_SELECTABLE_CLASSES = '.divider, .separator, .dropdown-header, .dropdown-menu-empty-item';
Fatih Acet's avatar
Fatih Acet committed
248

249 250 251 252
  SELECTABLE_CLASSES = ".dropdown-content li:not(" + NON_SELECTABLE_CLASSES + ", .option-hidden)";

  CURSOR_SELECT_SCROLL_PADDING = 5;

253
  FILTER_INPUT = '.dropdown-input .dropdown-input-field:not(.dropdown-no-filter)';
254

255
  NO_FILTER_INPUT = '.dropdown-input .dropdown-input-field.dropdown-no-filter';
256 257 258 259 260

  function GitLabDropdown(el1, options) {
    var searchFields, selector, self;
    this.el = el1;
    this.options = options;
261 262 263 264
    this.updateLabel = this.updateLabel.bind(this);
    this.hidden = this.hidden.bind(this);
    this.opened = this.opened.bind(this);
    this.shouldPropagate = this.shouldPropagate.bind(this);
265 266 267 268 269
    self = this;
    selector = $(this.el).data("target");
    this.dropdown = selector != null ? $(selector) : $(this.el).parent();
    // Set Defaults
    this.filterInput = this.options.filterInput || this.getElement(FILTER_INPUT);
270
    this.noFilterInput = this.options.noFilterInput || this.getElement(NO_FILTER_INPUT);
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    this.highlight = !!this.options.highlight;
    this.filterInputBlur = this.options.filterInputBlur != null
      ? this.options.filterInputBlur
      : true;
    // If no input is passed create a default one
    self = this;
    // If selector was passed
    if (_.isString(this.filterInput)) {
      this.filterInput = this.getElement(this.filterInput);
    }
    searchFields = this.options.search ? this.options.search.fields : [];
    if (this.options.data) {
      // If we provided data
      // data could be an array of objects or a group of arrays
      if (_.isObject(this.options.data) && !_.isFunction(this.options.data)) {
        this.fullData = this.options.data;
        currentIndex = -1;
        this.parseData(this.options.data);
        this.focusTextInput();
      } else {
        this.remote = new GitLabDropdownRemote(this.options.data, {
          dataType: this.options.dataType,
          beforeSend: this.toggleLoading.bind(this),
          success: (function(_this) {
Fatih Acet's avatar
Fatih Acet committed
295
            return function(data) {
296 297
              _this.fullData = data;
              _this.parseData(_this.fullData);
298
              _this.focusTextInput();
299 300
              if (_this.options.filterable && _this.filter && _this.filter.input && _this.filter.input.val() && _this.filter.input.val().trim() !== '') {
                return _this.filter.input.trigger('input');
Fatih Acet's avatar
Fatih Acet committed
301 302
              }
            };
303
          // Remote data
304 305
          })(this),
          instance: this,
Fatih Acet's avatar
Fatih Acet committed
306 307
        });
      }
308
    }
309
    if (this.noFilterInput.length) {
310
      this.plainInput = new GitLabDropdownInput(this.noFilterInput, this.options);
311
      this.plainInput.onInput(this.addInput.bind(this));
312
    }
313 314 315 316 317 318 319 320 321 322
    // Init filterable
    if (this.options.filterable) {
      this.filter = new GitLabDropdownFilter(this.filterInput, {
        elIsInput: $(this.el).is('input'),
        filterInputBlur: this.filterInputBlur,
        filterByText: this.options.filterByText,
        onFilter: this.options.onFilter,
        remote: this.options.filterRemote,
        query: this.options.data,
        keys: searchFields,
323
        instance: this,
324 325 326 327 328
        elements: (function(_this) {
          return function() {
            selector = '.dropdown-content li:not(' + NON_SELECTABLE_CLASSES + ')';
            if (_this.dropdown.find('.dropdown-toggle-page').length) {
              selector = ".dropdown-page-one " + selector;
Fatih Acet's avatar
Fatih Acet committed
329
            }
330
            return $(selector, this.instance.dropdown);
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
          };
        })(this),
        data: (function(_this) {
          return function() {
            return _this.fullData;
          };
        })(this),
        callback: (function(_this) {
          return function(data) {
            _this.parseData(data);
            if (_this.filterInput.val() !== '') {
              selector = SELECTABLE_CLASSES;
              if (_this.dropdown.find('.dropdown-toggle-page').length) {
                selector = ".dropdown-page-one " + selector;
              }
              if ($(_this.el).is('input')) {
                currentIndex = -1;
              } else {
                $(selector, _this.dropdown).first().find('a').addClass('is-focused');
                currentIndex = 0;
              }
            }
          };
        })(this)
      });
    }
    // Event listeners
    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) {
        // Escape key
        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) {
Clement Ho's avatar
Clement Ho committed
377
            return _this.dropdown.removeClass('show');
Fatih Acet's avatar
Fatih Acet committed
378
          }
379 380 381 382 383 384 385 386 387
        }
      };
    })(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();
Fatih Acet's avatar
Fatih Acet committed
388 389
        };
      })(this));
390 391 392
    }
    if (this.options.selectable) {
      selector = ".dropdown-content a";
Fatih Acet's avatar
Fatih Acet committed
393
      if (this.dropdown.find(".dropdown-toggle-page").length) {
394 395 396 397
        selector = ".dropdown-page-one .dropdown-content a";
      }
      this.dropdown.on("click", selector, function(e) {
        var $el, selected, selectedObj, isMarking;
398
        $el = $(e.currentTarget);
399 400 401
        selected = self.rowClicked($el);
        selectedObj = selected ? selected[0] : null;
        isMarking = selected ? selected[1] : null;
402 403 404 405 406 407 408
        if (this.options.clicked) {
          this.options.clicked.call(this, {
            selectedObj,
            $el,
            e,
            isMarking,
          });
Fatih Acet's avatar
Fatih Acet committed
409
        }
410

411
        // Update label right after all modifications in dropdown has been done
412 413
        if (this.options.toggleLabel) {
          this.updateLabel(selectedObj, $el, this);
414
        }
415

416
        $el.trigger('blur');
417
      }.bind(this));
Fatih Acet's avatar
Fatih Acet committed
418
    }
419
  }
Fatih Acet's avatar
Fatih Acet committed
420

421 422 423 424
  // Finds an element inside wrapper element
  GitLabDropdown.prototype.getElement = function(selector) {
    return this.dropdown.find(selector);
  };
Fatih Acet's avatar
Fatih Acet committed
425

426 427 428
  GitLabDropdown.prototype.toggleLoading = function() {
    return $('.dropdown-menu', this.dropdown).toggleClass(LOADING_CLASS);
  };
Fatih Acet's avatar
Fatih Acet committed
429

430 431 432 433 434 435
  GitLabDropdown.prototype.togglePage = function() {
    var menu;
    menu = $('.dropdown-menu', this.dropdown);
    if (menu.hasClass(PAGE_TWO_CLASS)) {
      if (this.remote) {
        this.remote.execute();
Fatih Acet's avatar
Fatih Acet committed
436
      }
437 438 439 440 441 442 443 444 445 446 447 448 449 450
    }
    menu.toggleClass(PAGE_TWO_CLASS);
    // Focus first visible input on active page
    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) {
      // render no matching results
      html = [this.noResults()];
    } else {
      // Handle array groups
451
      if (isObject(data)) {
452 453 454 455 456 457 458 459 460 461
        html = [];
        for (name in data) {
          groupData = data[name];
          html.push(this.renderItem({
            header: name
          // Add header for each group
          }, name));
          this.renderData(groupData, name).map(function(item) {
            return html.push(item);
          });
Fatih Acet's avatar
Fatih Acet committed
462
        }
463 464 465
      } else {
        // Render each row
        html = this.renderData(data);
Fatih Acet's avatar
Fatih Acet committed
466
      }
467 468 469 470 471
    }
    // Render the full menu
    full_html = this.renderMenu(html);
    return this.appendMenu(full_html);
  };
Fatih Acet's avatar
Fatih Acet committed
472

473 474 475 476 477 478 479 480 481 482
  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));
  };
483

484 485
  GitLabDropdown.prototype.shouldPropagate = function(e) {
    var $target;
486
    if (this.options.multiSelect || this.options.shouldPropagate === false) {
487 488 489
      $target = $(e.target);
      if ($target && !$target.hasClass('dropdown-menu-close') &&
                     !$target.hasClass('dropdown-menu-close-icon') &&
Phil Hughes's avatar
Phil Hughes committed
490
                     !$target.data('isLink')) {
491 492
        e.stopPropagation();
        return false;
493
      } else {
494
        return true;
Fatih Acet's avatar
Fatih Acet committed
495
      }
496 497
    }
  };
498

499 500 501 502 503 504 505
  GitLabDropdown.prototype.filteredFullData = function() {
    return this.fullData.filter(r => typeof r === 'object'
      && !Object.prototype.hasOwnProperty.call(r, 'beforeDivider')
      && !Object.prototype.hasOwnProperty.call(r, 'header')
    );
  };

506 507 508 509
  GitLabDropdown.prototype.opened = function(e) {
    var contentHtml;
    this.resetRows();
    this.addArrowKeyEvent();
510

511 512
    const dropdownToggle = this.dropdown.find('.dropdown-menu-toggle');
    const hasFilterBulkUpdate = dropdownToggle.hasClass('js-filter-bulk-update');
513
    const shouldRefreshOnOpen = dropdownToggle.hasClass('js-gl-dropdown-refresh-on-open');
514 515
    const hasMultiSelect = dropdownToggle.hasClass('js-multiselect');

516
    // Makes indeterminate items effective
517
    if (this.fullData && (shouldRefreshOnOpen || hasFilterBulkUpdate)) {
518 519
      this.parseData(this.fullData);
    }
520 521 522

    // Process the data to make sure rendered data
    // matches the correct layout
523 524
    const inputValue = this.filterInput.val();
    if (this.fullData && hasMultiSelect && this.options.processData && inputValue.length === 0) {
Clement Ho's avatar
Clement Ho committed
525
      this.options.processData.call(this.options, inputValue, this.filteredFullData(), this.parseData.bind(this));
526 527
    }

528 529 530 531 532 533
    contentHtml = $('.dropdown-content', this.dropdown).html();
    if (this.remote && contentHtml === "") {
      this.remote.execute();
    } else {
      this.focusTextInput();
    }
534

535 536 537
    if (this.options.showMenuAbove) {
      this.positionMenuAbove();
    }
Fatih Acet's avatar
Fatih Acet committed
538

539 540 541
    if (this.options.opened) {
      this.options.opened.call(this, e);
    }
542

543 544
    return this.dropdown.trigger('shown.gl.dropdown');
  };
545

546 547
  GitLabDropdown.prototype.positionMenuAbove = function() {
    var $menu = this.dropdown.find('.dropdown-menu');
Fatih Acet's avatar
Fatih Acet committed
548

549
    $menu.addClass('dropdown-open-top');
550 551
    $menu.css('top', 'initial');
    $menu.css('bottom', '100%');
552
  };
553

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
  GitLabDropdown.prototype.hidden = function(e) {
    var $input;
    this.resetRows();
    this.removeArrayKeyEvent();
    $input = this.dropdown.find(".dropdown-input-field");
    if (this.options.filterable) {
      $input.blur();
    }
    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');
  };
570

571 572 573 574 575 576
  // Render the full menu
  GitLabDropdown.prototype.renderMenu = function(html) {
    if (this.options.renderMenu) {
      return this.options.renderMenu(html);
    } else {
      var ul = document.createElement('ul');
577

578 579 580
      for (var i = 0; i < html.length; i += 1) {
        var el = html[i];

581
        if (el instanceof $) {
582
          el = el.get(0);
583 584
        }

585 586 587 588 589
        if (typeof el === 'string') {
          ul.innerHTML += el;
        } else {
          ul.appendChild(el);
        }
Fatih Acet's avatar
Fatih Acet committed
590 591
      }

592 593 594
      return ul;
    }
  };
595

596 597 598 599
  // Append the menu into the dropdown
  GitLabDropdown.prototype.appendMenu = function(html) {
    return this.clearMenu().append(html);
  };
600

601 602 603 604
  GitLabDropdown.prototype.clearMenu = function() {
    var selector;
    selector = '.dropdown-content';
    if (this.dropdown.find(".dropdown-toggle-page").length) {
605 606 607 608 609
      if (this.options.containerSelector) {
        selector = this.options.containerSelector;
      } else {
        selector = '.dropdown-page-one .dropdown-content';
      }
610
    }
Fatih Acet's avatar
Fatih Acet committed
611

612 613
    return $(selector, this.dropdown).empty();
  };
614

615 616
  GitLabDropdown.prototype.renderItem = function(data, group, index) {
    var field, fieldName, html, selected, text, url, value, rowHidden;
617

618 619
    if (!this.options.renderRow) {
      value = this.options.id ? this.options.id(data) : data.id;
620

621 622
      if (value) {
        value = value.toString().replace(/'/g, '\\\'');
Fatih Acet's avatar
Fatih Acet committed
623
      }
624
    }
625

626 627 628 629 630 631 632 633 634 635 636 637
    // Hide element
    if (this.options.hideRow && this.options.hideRow(value)) {
      rowHidden = true;
    }
    if (group == null) {
      group = false;
    }
    if (index == null) {
      // Render the row
      index = false;
    }
    html = document.createElement('li');
638

639 640 641 642
    if (rowHidden) {
      html.style.display = 'none';
    }

643
    if (data === 'divider' || data === 'separator') {
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
      html.className = data;
      return html;
    }
    // Header
    if (data.header != null) {
      html.className = 'dropdown-header';
      html.innerHTML = data.header;
      return html;
    }
    if (this.options.renderRow) {
      // Call the render function
      html = this.options.renderRow.call(this.options, data, this);
    } else {
      if (!selected) {
        fieldName = this.options.fieldName;

660 661 662 663 664 665 666 667
        if (value) {
          field = this.dropdown.parent().find(`input[name='${fieldName}'][value='${value}']`);
          if (field.length) {
            selected = true;
          }
        } else {
          field = this.dropdown.parent().find(`input[name='${fieldName}']`);
          selected = !field.length;
668
        }
Fatih Acet's avatar
Fatih Acet committed
669
      }
670 671 672 673 674
      // Set URL
      if (this.options.url != null) {
        url = this.options.url(data);
      } else {
        url = data.url != null ? data.url : '#';
Fatih Acet's avatar
Fatih Acet committed
675
      }
676 677 678
      // Set Text
      if (this.options.text != null) {
        text = this.options.text(data);
Fatih Acet's avatar
Fatih Acet committed
679
      } else {
680 681 682 683 684 685 686
        text = data.text != null ? data.text : '';
      }
      if (this.highlight) {
        text = this.highlightTextMatches(text, this.filterInput.val());
      }
      // Create the list item & the link
      var link = document.createElement('a');
687

688
      link.href = url;
689 690 691 692 693 694

      if (this.highlight) {
        link.innerHTML = text;
      } else {
        link.textContent = text;
      }
695

696 697
      if (selected) {
        link.className = 'is-active';
Fatih Acet's avatar
Fatih Acet committed
698
      }
699 700 701 702

      if (group) {
        link.dataset.group = group;
        link.dataset.index = index;
Fatih Acet's avatar
Fatih Acet committed
703
      }
704

705 706 707 708
      html.appendChild(link);
    }
    return html;
  };
709

710
  GitLabDropdown.prototype.highlightTextMatches = function(text, term) {
711 712
    const occurrences = fuzzaldrinPlus.match(text, term);
    const indexOf = [].indexOf;
713 714 715 716 717
    return text.split('').map(function(character, i) {
      if (indexOf.call(occurrences, i) !== -1) {
        return "<b>" + character + "</b>";
      } else {
        return character;
718
      }
719 720
    }).join('');
  };
721

722 723
  GitLabDropdown.prototype.noResults = function() {
    var html;
724
    return '<li class="dropdown-menu-empty-item"><a>No matching results</a></li>';
725 726 727 728
  };

  GitLabDropdown.prototype.rowClicked = function(el) {
    var field, fieldName, groupName, isInput, selectedIndex, selectedObject, value, isMarking;
Phil Hughes's avatar
Phil Hughes committed
729

730 731 732 733 734 735 736 737 738 739
    fieldName = this.options.fieldName;
    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];
Phil Hughes's avatar
Phil Hughes committed
740
      }
741
    }
Phil Hughes's avatar
Phil Hughes committed
742

743
    if (this.options.vue) {
744
      if (el.hasClass(ACTIVE_CLASS)) {
Fatih Acet's avatar
Fatih Acet committed
745 746 747 748
        el.removeClass(ACTIVE_CLASS);
      } else {
        el.addClass(ACTIVE_CLASS);
      }
749

750 751
      return [selectedObject];
    }
Fatih Acet's avatar
Fatih Acet committed
752

753 754 755 756 757 758
    field = [];
    value = this.options.id
      ? this.options.id(selectedObject, el)
      : selectedObject.id;
    if (isInput) {
      field = $(this.el);
759
    } else if (value != null) {
760 761
      field = this.dropdown.parent().find("input[name='" + fieldName + "'][value='" + value.toString().replace(/'/g, '\\\'') + "']");
    }
762

763
    if (this.options.isSelectable && !this.options.isSelectable(selectedObject, el)) {
764
      return [selectedObject];
765 766
    }

767
    if (el.hasClass(ACTIVE_CLASS) && value !== 0) {
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
      isMarking = false;
      el.removeClass(ACTIVE_CLASS);
      if (field && field.length) {
        this.clearField(field, isInput);
      }
    } else if (el.hasClass(INDETERMINATE_CLASS)) {
      isMarking = true;
      el.addClass(ACTIVE_CLASS);
      el.removeClass(INDETERMINATE_CLASS);
      if (field && field.length && value == null) {
        this.clearField(field, isInput);
      }
      if ((!field || !field.length) && fieldName) {
        this.addInput(fieldName, value, selectedObject);
      }
    } else {
      isMarking = true;
      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();
        }
790
      }
791 792
      if (field && field.length && value == null) {
        this.clearField(field, isInput);
Fatih Acet's avatar
Fatih Acet committed
793
      }
794 795 796 797 798 799 800
      // Toggle active class for the tick mark
      el.addClass(ACTIVE_CLASS);
      if (value != null) {
        if ((!field || !field.length) && fieldName) {
          this.addInput(fieldName, value, selectedObject);
        } else if (field && field.length) {
          field.val(value).trigger('change');
801
        }
Fatih Acet's avatar
Fatih Acet committed
802
      }
803
    }
Fatih Acet's avatar
Fatih Acet committed
804

805 806 807
    return [selectedObject, isMarking];
  };

808
  GitLabDropdown.prototype.focusTextInput = function() {
809
    if (this.options.filterable) {
810
      const initialScrollTop = $(window).scrollTop();
811

Clement Ho's avatar
Clement Ho committed
812
      if (this.dropdown.is('.show') && !this.filterInput.is(':focus')) {
813 814
        this.filterInput.focus();
      }
815

816 817
      if ($(window).scrollTop() < initialScrollTop) {
        $(window).scrollTop(initialScrollTop);
818 819
      }
    }
820 821
  };

822
  GitLabDropdown.prototype.addInput = function(fieldName, value, selectedObject, single) {
823 824
    var $input;
    // Create hidden input for form
825 826
    if (single) {
      $('input[name="' + fieldName + '"]').remove();
827
    }
828

829 830 831 832
    $input = $('<input>').attr('type', 'hidden').attr('name', fieldName).val(value);
    if (this.options.inputId != null) {
      $input.attr('id', this.options.inputId);
    }
833

834 835 836 837 838 839
    if (this.options.multiSelect) {
      Object.keys(selectedObject).forEach((attribute) => {
        $input.attr(`data-${attribute}`, selectedObject[attribute]);
      });
    }

840 841 842
    if (this.options.inputMeta) {
      $input.attr('data-meta', selectedObject[this.options.inputMeta]);
    }
843

844
    this.dropdown.before($input).trigger('change');
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
  };

  GitLabDropdown.prototype.selectRowAtIndex = function(index) {
    var $el, selector;
    // If we pass an option index
    if (typeof index !== "undefined") {
      selector = SELECTABLE_CLASSES + ":eq(" + index + ") a";
    } else {
      selector = ".dropdown-content .is-focused";
    }
    if (this.dropdown.find(".dropdown-toggle-page").length) {
      selector = ".dropdown-page-one " + selector;
    }
    // simulate a click on the first link
    $el = $(selector, this.dropdown);
    if ($el.length) {
      var href = $el.attr('href');
      if (href && href !== '#') {
Phil Hughes's avatar
Phil Hughes committed
863
        visitUrl(href);
864
      } else {
865
        $el.trigger('click');
Fatih Acet's avatar
Fatih Acet committed
866
      }
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    }
  };

  GitLabDropdown.prototype.addArrowKeyEvent = function() {
    var $input, ARROW_KEY_CODES, selector;
    ARROW_KEY_CODES = [38, 40];
    $input = this.dropdown.find(".dropdown-input-field");
    selector = SELECTABLE_CLASSES;
    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) !== -1) {
          e.preventDefault();
          e.stopImmediatePropagation();
          PREV_INDEX = currentIndex;
          $listItems = $(selector, _this.dropdown);
          // if @options.filterable
          //   $input.blur()
          if (currentKeyCode === 40) {
            // Move down
            if (currentIndex < ($listItems.length - 1)) {
              currentIndex += 1;
Fatih Acet's avatar
Fatih Acet committed
893
            }
894 895 896 897
          } else if (currentKeyCode === 38) {
            // Move up
            if (currentIndex > 0) {
              currentIndex -= 1;
Fatih Acet's avatar
Fatih Acet committed
898 899
            }
          }
900 901
          if (currentIndex !== PREV_INDEX) {
            _this.highlightRowAtIndex($listItems, currentIndex);
Fatih Acet's avatar
Fatih Acet committed
902
          }
903 904 905 906 907 908 909 910 911
          return false;
        }
        if (currentKeyCode === 13 && currentIndex !== -1) {
          e.preventDefault();
          _this.selectRowAtIndex();
        }
      };
    })(this));
  };
Fatih Acet's avatar
Fatih Acet committed
912

913 914 915
  GitLabDropdown.prototype.removeArrayKeyEvent = function() {
    return $('body').off('keydown');
  };
Fatih Acet's avatar
Fatih Acet committed
916

917 918 919 920
  GitLabDropdown.prototype.resetRows = function resetRows() {
    currentIndex = -1;
    $('.is-focused', this.dropdown).removeClass('is-focused');
  };
921

922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
  GitLabDropdown.prototype.highlightRowAtIndex = function($listItems, index) {
    var $dropdownContent, $listItem, dropdownContentBottom, dropdownContentHeight, dropdownContentTop, dropdownScrollTop, listItemBottom, listItemHeight, listItemTop;
    // Remove the class for the previously focused row
    $('.is-focused', this.dropdown).removeClass('is-focused');
    // Update the class for the row at the specific index
    $listItem = $listItems.eq(index);
    $listItem.find('a:first-child').addClass("is-focused");
    // Dropdown content scroll area
    $dropdownContent = $listItem.closest('.dropdown-content');
    dropdownScrollTop = $dropdownContent.scrollTop();
    dropdownContentHeight = $dropdownContent.outerHeight();
    dropdownContentTop = $dropdownContent.prop('offsetTop');
    dropdownContentBottom = dropdownContentTop + dropdownContentHeight;
    // Get the offset bottom of the list item
    listItemHeight = $listItem.outerHeight();
    listItemTop = $listItem.prop('offsetTop');
    listItemBottom = listItemTop + listItemHeight;
    if (!index) {
      // Scroll the dropdown content to the top
      $dropdownContent.scrollTop(0);
    } else if (index === ($listItems.length - 1)) {
      // Scroll the dropdown content to the bottom
      $dropdownContent.scrollTop($dropdownContent.prop('scrollHeight'));
    } else if (listItemBottom > (dropdownContentBottom + dropdownScrollTop)) {
      // Scroll the dropdown content down
      $dropdownContent.scrollTop(listItemBottom - dropdownContentBottom + CURSOR_SELECT_SCROLL_PADDING);
    } else if (listItemTop < (dropdownContentTop + dropdownScrollTop)) {
      // Scroll the dropdown content up
      return $dropdownContent.scrollTop(listItemTop - dropdownContentTop - CURSOR_SELECT_SCROLL_PADDING);
    }
  };
Fatih Acet's avatar
Fatih Acet committed
953

954 955 956 957 958 959 960 961 962 963
  GitLabDropdown.prototype.updateLabel = function(selected, el, instance) {
    if (selected == null) {
      selected = null;
    }
    if (el == null) {
      el = null;
    }
    if (instance == null) {
      instance = null;
    }
964 965 966 967 968 969 970 971

    let toggleText = this.options.toggleLabel(selected, el, instance);
    if (this.options.updateLabel) {
      // Option to override the dropdown label text
      toggleText = this.options.updateLabel;
    }

    return $(this.el).find(".dropdown-toggle-text").text(toggleText);
Fatih Acet's avatar
Fatih Acet committed
972
  };
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987

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

  return GitLabDropdown;
})();

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