gl_dropdown.js 26.9 KB
Newer Older
1
/* eslint-disable max-classes-per-file, one-var, consistent-return */
2 3

import $ from 'jquery';
4
import { escape } from 'lodash';
5
import fuzzaldrinPlus from 'fuzzaldrin-plus';
6
import axios from './lib/utils/axios_utils';
7
import { visitUrl } from '~/lib/utils/url_utility';
8
import { isObject } from './lib/utils/type_utility';
9
import renderItem from './gl_dropdown/render';
10

11
const BLUR_KEYCODES = [27, 40];
12

13
const HAS_VALUE_CLASS = 'has-value';
14

15
const LOADING_CLASS = 'is-loading';
Fatih Acet's avatar
Fatih Acet committed
16

17
const PAGE_TWO_CLASS = 'is-page-two';
Fatih Acet's avatar
Fatih Acet committed
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
const ACTIVE_CLASS = 'is-active';

const INDETERMINATE_CLASS = 'is-indeterminate';

let currentIndex = -1;

const NON_SELECTABLE_CLASSES = '.divider, .separator, .dropdown-header, .dropdown-menu-empty-item';

const SELECTABLE_CLASSES = `.dropdown-content li:not(${NON_SELECTABLE_CLASSES}, .option-hidden)`;

const CURSOR_SELECT_SCROLL_PADDING = 5;

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

const NO_FILTER_INPUT = '.dropdown-input .dropdown-input-field.dropdown-no-filter';

Marvin Karegyeya's avatar
Marvin Karegyeya committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
class GitLabDropdownInput {
  constructor(input, options) {
    this.input = input;
    this.options = options;
    this.fieldName = this.options.fieldName || 'field-name';
    const $inputContainer = this.input.parent();
    const $clearButton = $inputContainer.find('.js-dropdown-input-clear');
    $clearButton.on('click', e => {
      // Clear click
      e.preventDefault();
      e.stopPropagation();
      return this.input
        .val('')
        .trigger('input')
        .focus();
50 51
    });

Marvin Karegyeya's avatar
Marvin Karegyeya committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    this.input
      .on('keydown', e => {
        const keyCode = e.which;
        if (keyCode === 13 && !options.elIsInput) {
          e.preventDefault();
        }
      })
      .on('input', e => {
        let val = e.currentTarget.value || this.options.inputFieldName;
        val = val
          .split(' ')
          .join('-') // replaces space with dash
          .replace(/[^a-zA-Z0-9 -]/g, '')
          .toLowerCase() // replace non alphanumeric
          .replace(/(-)\1+/g, '-'); // replace repeated dashes
        this.cb(this.options.fieldName, val, {}, true);
        this.input
          .closest('.dropdown')
          .find('.dropdown-toggle-text')
          .text(val);
      });
  }
74

Marvin Karegyeya's avatar
Marvin Karegyeya committed
75 76 77
  onInput(cb) {
    this.cb = cb;
  }
78 79
}

Marvin Karegyeya's avatar
Marvin Karegyeya committed
80 81 82 83 84 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 119 120 121 122 123 124 125 126 127 128
class GitLabDropdownFilter {
  constructor(input, options) {
    let ref, timeout;
    this.input = input;
    this.options = options;
    // eslint-disable-next-line no-cond-assign
    this.filterInputBlur = (ref = this.options.filterInputBlur) != null ? ref : true;
    const $inputContainer = this.input.parent();
    const $clearButton = $inputContainer.find('.js-dropdown-input-clear');
    $clearButton.on('click', e => {
      // Clear click
      e.preventDefault();
      e.stopPropagation();
      return this.input
        .val('')
        .trigger('input')
        .focus();
    });
    // Key events
    timeout = '';
    this.input
      .on('keydown', e => {
        const keyCode = e.which;
        if (keyCode === 13 && !options.elIsInput) {
          e.preventDefault();
        }
      })
      .on('input', () => {
        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);
          // eslint-disable-next-line no-return-assign
          return (timeout = setTimeout(() => {
            $inputContainer.parent().addClass('is-loading');

            return this.options.query(this.input.val(), data => {
              $inputContainer.parent().removeClass('is-loading');
              return this.options.callback(data);
            });
          }, 250));
        }
        return this.filter(this.input.val());
      });
  }
129

Marvin Karegyeya's avatar
Marvin Karegyeya committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  static shouldBlur(keyCode) {
    return BLUR_KEYCODES.indexOf(keyCode) !== -1;
  }

  filter(searchText) {
    let group, results, tmp;
    if (this.options.onFilter) {
      this.options.onFilter(searchText);
    }
    const data = this.options.data();
    if (data != null && !this.options.filterByText) {
      results = data;
      if (searchText !== '') {
        // When data is an array of objects therefore [object Array] e.g.
        // [
        //   { prop: 'foo' },
        //   { prop: 'baz' }
        // ]
lauraMon's avatar
lauraMon committed
148
        if (Array.isArray(data)) {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
149 150 151 152
          results = fuzzaldrinPlus.filter(data, searchText, {
            key: this.options.keys,
          });
        }
153 154 155 156 157 158 159 160 161 162 163
        // If data is grouped therefore an [object Object]. e.g.
        // {
        //   groupName1: [
        //     { prop: 'foo' },
        //     { prop: 'baz' }
        //   ],
        //   groupName2: [
        //     { prop: 'abc' },
        //     { prop: 'def' }
        //   ]
        // }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
164
        else if (isObject(data)) {
165
          results = {};
Marvin Karegyeya's avatar
Marvin Karegyeya committed
166
          Object.keys(data).forEach(key => {
167
            group = data[key];
Marvin Karegyeya's avatar
Marvin Karegyeya committed
168
            tmp = fuzzaldrinPlus.filter(group, searchText, {
169 170 171 172
              key: this.options.keys,
            });
            if (tmp.length) {
              results[key] = tmp.map(item => item);
Fatih Acet's avatar
Fatih Acet committed
173
            }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
174
          });
Fatih Acet's avatar
Fatih Acet committed
175
        }
176
      }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
177
      return this.options.callback(results);
178
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
179 180 181
    const elements = this.options.elements();
    if (searchText) {
      // eslint-disable-next-line func-names
182
      elements.each(function() {
183
        const $el = $(this);
Marvin Karegyeya's avatar
Marvin Karegyeya committed
184
        const matches = fuzzaldrinPlus.match($el.text().trim(), searchText);
185 186 187
        if (!$el.is('.dropdown-header')) {
          if (matches.length) {
            return $el.show().removeClass('option-hidden');
188
          }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
189
          return $el.hide().addClass('option-hidden');
190 191 192 193
        }
      });
    } else {
      elements.show().removeClass('option-hidden');
194 195
    }

196 197 198 199
    elements
      .parent()
      .find('.dropdown-menu-empty-item')
      .toggleClass('hidden', elements.is(':visible'));
200
  }
201
}
Fatih Acet's avatar
Fatih Acet committed
202

Marvin Karegyeya's avatar
Marvin Karegyeya committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
class GitLabDropdownRemote {
  constructor(dataEndpoint, options) {
    this.dataEndpoint = dataEndpoint;
    this.options = options;
  }

  execute() {
    if (typeof this.dataEndpoint === 'string') {
      return this.fetchData();
    } else if (typeof this.dataEndpoint === 'function') {
      if (this.options.beforeSend) {
        this.options.beforeSend();
      }
      return this.dataEndpoint('', data => {
        // Fetch the data by calling the data function
        if (this.options.success) {
          this.options.success(data);
        }
        if (this.options.beforeSend) {
          return this.options.beforeSend();
        }
      });
    }
  }

  fetchData() {
229 230 231
    if (this.options.beforeSend) {
      this.options.beforeSend();
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
232 233 234

    // Fetch the data through ajax if the data is a string
    return axios.get(this.dataEndpoint).then(({ data }) => {
235
      if (this.options.success) {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
236
        return this.options.success(data);
237 238
      }
    });
239
  }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
240
}
Fatih Acet's avatar
Fatih Acet committed
241

Marvin Karegyeya's avatar
Marvin Karegyeya committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
class GitLabDropdown {
  constructor(el1, options) {
    let selector, self;
    this.el = el1;
    this.options = options;
    this.updateLabel = this.updateLabel.bind(this);
    this.hidden = this.hidden.bind(this);
    this.opened = this.opened.bind(this);
    this.shouldPropagate = this.shouldPropagate.bind(this);
    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);
    this.noFilterInput = this.options.noFilterInput || this.getElement(NO_FILTER_INPUT);
    this.highlight = Boolean(this.options.highlight);
    this.icon = Boolean(this.options.icon);
    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
lauraMon's avatar
lauraMon committed
264
    if (typeof this.filterInput === 'string') {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
265
      this.filterInput = this.getElement(this.filterInput);
266
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
267 268 269 270
    const 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
lauraMon's avatar
lauraMon committed
271
      if (typeof this.options.data === 'object' && !(this.options.data instanceof Function)) {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        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: data => {
            this.fullData = data;
            this.parseData(this.fullData);
            this.focusTextInput();

            // Update dropdown position since remote data may have changed dropdown size
            this.dropdown.find('.dropdown-menu-toggle').dropdown('update');

            if (
              this.options.filterable &&
              this.filter &&
              this.filter.input &&
              this.filter.input.val() &&
              this.filter.input.val().trim() !== ''
            ) {
              return this.filter.input.trigger('input');
            }
          },
          instance: this,
        });
      }
301
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    if (this.noFilterInput.length) {
      this.plainInput = new GitLabDropdownInput(this.noFilterInput, this.options);
      this.plainInput.onInput(this.addInput.bind(this));
    }
    // 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,
        instance: this,
        elements: () => {
          selector = `.dropdown-content li:not(${NON_SELECTABLE_CLASSES})`;
319 320
          if (this.dropdown.find('.dropdown-toggle-page').length) {
            selector = `.dropdown-page-one ${selector}`;
Fatih Acet's avatar
Fatih Acet committed
321
          }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
          return $(selector, this.dropdown);
        },
        data: () => this.fullData,
        callback: 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;
            }
341
          }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
342 343
        },
      });
344
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    // 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', e => {
      // Escape key
      if (e.which === 27) {
        return $('.dropdown-menu-close', this.dropdown).trigger('click');
      }
    });
    this.dropdown.on('blur', 'a', e => {
      let $dropdownMenu, $relatedTarget;
      if (e.relatedTarget != null) {
        $relatedTarget = $(e.relatedTarget);
        $dropdownMenu = $relatedTarget.closest('.dropdown-menu');
        if ($dropdownMenu.length === 0) {
          return this.dropdown.removeClass('show');
        }
364 365 366
      }
    });
    if (this.dropdown.find('.dropdown-toggle-page').length) {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
367 368 369 370 371 372 373 374 375 376
      this.dropdown.find('.dropdown-toggle-page, .dropdown-menu-back').on('click', e => {
        e.preventDefault();
        e.stopPropagation();
        return this.togglePage();
      });
    }
    if (this.options.selectable) {
      selector = '.dropdown-content a';
      if (this.dropdown.find('.dropdown-toggle-page').length) {
        selector = '.dropdown-page-one .dropdown-content a';
377
      }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
378 379 380 381 382 383 384 385 386 387 388 389 390
      this.dropdown.on('click', selector, e => {
        const $el = $(e.currentTarget);
        const selected = self.rowClicked($el);
        const selectedObj = selected ? selected[0] : null;
        const isMarking = selected ? selected[1] : null;
        if (this.options.clicked) {
          this.options.clicked.call(this, {
            selectedObj,
            $el,
            e,
            isMarking,
          });
        }
391

Marvin Karegyeya's avatar
Marvin Karegyeya committed
392 393 394 395
        // Update label right after all modifications in dropdown has been done
        if (this.options.toggleLabel) {
          this.updateLabel(selectedObj, $el, this);
        }
396

Marvin Karegyeya's avatar
Marvin Karegyeya committed
397 398 399
        $el.trigger('blur');
      });
    }
400
  }
Fatih Acet's avatar
Fatih Acet committed
401

Marvin Karegyeya's avatar
Marvin Karegyeya committed
402 403 404 405
  // Finds an element inside wrapper element
  getElement(selector) {
    return this.dropdown.find(selector);
  }
Fatih Acet's avatar
Fatih Acet committed
406

Marvin Karegyeya's avatar
Marvin Karegyeya committed
407 408 409
  toggleLoading() {
    return $('.dropdown-menu', this.dropdown).toggleClass(LOADING_CLASS);
  }
Fatih Acet's avatar
Fatih Acet committed
410

Marvin Karegyeya's avatar
Marvin Karegyeya committed
411 412 413 414 415 416
  togglePage() {
    const menu = $('.dropdown-menu', this.dropdown);
    if (menu.hasClass(PAGE_TWO_CLASS)) {
      if (this.remote) {
        this.remote.execute();
      }
417
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
418 419 420
    menu.toggleClass(PAGE_TWO_CLASS);
    // Focus first visible input on active page
    return this.dropdown.find('[class^="dropdown-page-"]:visible :text:visible:first').focus();
421 422
  }

Marvin Karegyeya's avatar
Marvin Karegyeya committed
423 424 425 426 427 428 429
  parseData(data) {
    let groupData, html;
    this.renderedData = data;
    if (this.options.filterable && data.length === 0) {
      // render no matching results
      html = [this.noResults()];
    }
430
    // Handle array groups
Marvin Karegyeya's avatar
Marvin Karegyeya committed
431
    else if (isObject(data)) {
432
      html = [];
Marvin Karegyeya's avatar
Marvin Karegyeya committed
433 434

      Object.keys(data).forEach(name => {
435 436 437 438 439 440 441 442 443 444 445
        groupData = data[name];
        html.push(
          this.renderItem(
            {
              content: name,
              type: 'header',
            },
            name,
          ),
        );
        this.renderData(groupData, name).map(item => html.push(item));
Marvin Karegyeya's avatar
Marvin Karegyeya committed
446
      });
447 448 449
    } else {
      // Render each row
      html = this.renderData(data);
450
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    // Render the full menu
    const fullHtml = this.renderMenu(html);
    return this.appendMenu(fullHtml);
  }

  renderData(data, group) {
    return data.map((obj, index) => this.renderItem(obj, group || false, index));
  }

  shouldPropagate(e) {
    let $target;
    if (this.options.multiSelect || this.options.shouldPropagate === false) {
      $target = $(e.target);
      if (
        $target &&
        !$target.hasClass('dropdown-menu-close') &&
        !$target.hasClass('dropdown-menu-close-icon') &&
        !$target.data('isLink')
      ) {
        e.stopPropagation();

        // This prevents automatic scrolling to the top
        if ($target.closest('a').length) {
          return false;
        }
476
      }
477

Marvin Karegyeya's avatar
Marvin Karegyeya committed
478 479
      return true;
    }
480
  }
481

Marvin Karegyeya's avatar
Marvin Karegyeya committed
482 483 484 485 486 487
  filteredFullData() {
    return this.fullData.filter(
      r =>
        typeof r === 'object' &&
        !Object.prototype.hasOwnProperty.call(r, 'beforeDivider') &&
        !Object.prototype.hasOwnProperty.call(r, 'header'),
488 489 490
    );
  }

Marvin Karegyeya's avatar
Marvin Karegyeya committed
491 492 493
  opened(e) {
    this.resetRows();
    this.addArrowKeyEvent();
494

Marvin Karegyeya's avatar
Marvin Karegyeya committed
495 496 497 498
    const dropdownToggle = this.dropdown.find('.dropdown-menu-toggle');
    const hasFilterBulkUpdate = dropdownToggle.hasClass('js-filter-bulk-update');
    const shouldRefreshOnOpen = dropdownToggle.hasClass('js-gl-dropdown-refresh-on-open');
    const hasMultiSelect = dropdownToggle.hasClass('js-multiselect');
499

Marvin Karegyeya's avatar
Marvin Karegyeya committed
500 501 502
    // Makes indeterminate items effective
    if (this.fullData && (shouldRefreshOnOpen || hasFilterBulkUpdate)) {
      this.parseData(this.fullData);
503 504
    }

Marvin Karegyeya's avatar
Marvin Karegyeya committed
505 506 507 508 509 510 511 512 513 514 515
    // Process the data to make sure rendered data
    // matches the correct layout
    const inputValue = this.filterInput.val();
    if (this.fullData && hasMultiSelect && this.options.processData && inputValue.length === 0) {
      this.options.processData.call(
        this.options,
        inputValue,
        this.filteredFullData(),
        this.parseData.bind(this),
      );
    }
516

Marvin Karegyeya's avatar
Marvin Karegyeya committed
517 518 519 520 521 522
    const contentHtml = $('.dropdown-content', this.dropdown).html();
    if (this.remote && contentHtml === '') {
      this.remote.execute();
    } else {
      this.focusTextInput();
    }
Fatih Acet's avatar
Fatih Acet committed
523

Marvin Karegyeya's avatar
Marvin Karegyeya committed
524 525 526 527 528 529 530 531 532 533 534
    if (this.options.showMenuAbove) {
      this.positionMenuAbove();
    }

    if (this.options.opened) {
      if (this.options.preserveContext) {
        this.options.opened(e);
      } else {
        this.options.opened.call(this, e);
      }
    }
535

Marvin Karegyeya's avatar
Marvin Karegyeya committed
536
    return this.dropdown.trigger('shown.gl.dropdown');
537
  }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
538 539 540 541 542 543 544

  positionMenuAbove() {
    const $menu = this.dropdown.find('.dropdown-menu');

    $menu.addClass('dropdown-open-top');
    $menu.css('top', 'initial');
    $menu.css('bottom', '100%');
545
  }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

  hidden(e) {
    this.resetRows();
    this.removeArrowKeyEvent();
    const $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');
561
  }
562

Marvin Karegyeya's avatar
Marvin Karegyeya committed
563 564 565 566 567
  // Render the full menu
  renderMenu(html) {
    if (this.options.renderMenu) {
      return this.options.renderMenu(html);
    }
568 569
    return $('<ul>').append(html);
  }
Fatih Acet's avatar
Fatih Acet committed
570

Marvin Karegyeya's avatar
Marvin Karegyeya committed
571 572 573 574
  // Append the menu into the dropdown
  appendMenu(html) {
    return this.clearMenu().append(html);
  }
575

Marvin Karegyeya's avatar
Marvin Karegyeya committed
576 577 578 579 580 581 582 583
  clearMenu() {
    let selector = '.dropdown-content';
    if (this.dropdown.find('.dropdown-toggle-page').length) {
      if (this.options.containerSelector) {
        selector = this.options.containerSelector;
      } else {
        selector = '.dropdown-page-one .dropdown-content';
      }
584
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
585 586

    return $(selector, this.dropdown).empty();
587
  }
588

Marvin Karegyeya's avatar
Marvin Karegyeya committed
589 590
  renderItem(data, group, index) {
    let parent;
591

Marvin Karegyeya's avatar
Marvin Karegyeya committed
592 593 594
    if (this.dropdown && this.dropdown[0]) {
      parent = this.dropdown[0].parentNode;
    }
595

Marvin Karegyeya's avatar
Marvin Karegyeya committed
596 597
    return renderItem({
      instance: this,
598 599
      options: {
        ...this.options,
Marvin Karegyeya's avatar
Marvin Karegyeya committed
600 601 602 603 604
        icon: this.icon,
        highlight: this.highlight,
        highlightText: text => this.highlightTextMatches(text, this.filterInput.val()),
        highlightTemplate: this.highlightTemplate.bind(this),
        parent,
605
      },
Marvin Karegyeya's avatar
Marvin Karegyeya committed
606 607 608 609 610
      data,
      group,
      index,
    });
  }
611

Marvin Karegyeya's avatar
Marvin Karegyeya committed
612 613
  // eslint-disable-next-line class-methods-use-this
  highlightTemplate(text, template) {
614
    return `"<b>${escape(text)}</b>" ${template}`;
Marvin Karegyeya's avatar
Marvin Karegyeya committed
615
  }
Phil Hughes's avatar
Phil Hughes committed
616

Marvin Karegyeya's avatar
Marvin Karegyeya committed
617 618 619 620 621 622 623 624 625 626 627
  // eslint-disable-next-line class-methods-use-this
  highlightTextMatches(text, term) {
    const occurrences = fuzzaldrinPlus.match(text, term);
    const { indexOf } = [];

    return text
      .split('')
      .map((character, i) => {
        if (indexOf.call(occurrences, i) !== -1) {
          return `<b>${character}</b>`;
        }
628
        return character;
Marvin Karegyeya's avatar
Marvin Karegyeya committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
      })
      .join('');
  }

  // eslint-disable-next-line class-methods-use-this
  noResults() {
    return '<li class="dropdown-menu-empty-item"><a>No matching results</a></li>';
  }

  rowClicked(el) {
    let field, groupName, selectedIndex, selectedObject, isMarking;
    const { fieldName } = this.options;
    const 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();
        this.selectedIndex = selectedIndex;
        selectedObject = this.renderedData[selectedIndex];
Fatih Acet's avatar
Fatih Acet committed
651
      }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
652
    }
653

Marvin Karegyeya's avatar
Marvin Karegyeya committed
654 655 656 657 658 659
    if (this.options.vue) {
      if (el.hasClass(ACTIVE_CLASS)) {
        el.removeClass(ACTIVE_CLASS);
      } else {
        el.addClass(ACTIVE_CLASS);
      }
Fatih Acet's avatar
Fatih Acet committed
660

Marvin Karegyeya's avatar
Marvin Karegyeya committed
661
      return [selectedObject];
662 663
    }

Marvin Karegyeya's avatar
Marvin Karegyeya committed
664 665 666 667 668 669 670 671
    field = [];
    const value = this.options.id ? this.options.id(selectedObject, el) : selectedObject.id;
    if (isInput) {
      field = $(this.el);
    } else if (value != null) {
      field = this.dropdown
        .parent()
        .find(`input[name='${fieldName}'][value='${value.toString().replace(/'/g, "\\'")}']`);
672
    }
Fatih Acet's avatar
Fatih Acet committed
673

Marvin Karegyeya's avatar
Marvin Karegyeya committed
674 675 676
    if (this.options.isSelectable && !this.options.isSelectable(selectedObject, el)) {
      return [selectedObject];
    }
677

Marvin Karegyeya's avatar
Marvin Karegyeya committed
678 679 680 681 682 683 684 685 686 687 688 689
    if (el.hasClass(ACTIVE_CLASS) && value !== 0) {
      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);
690
      }
691 692
      if ((!field || !field.length) && fieldName) {
        this.addInput(fieldName, value, selectedObject);
Marvin Karegyeya's avatar
Marvin Karegyeya committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
      }
    } 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();
        }
      }
      if (field && field.length && value == null) {
        this.clearField(field, isInput);
      }
      // 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');
        }
716 717
      }
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
718 719

    return [selectedObject, isMarking];
720
  }
721

Marvin Karegyeya's avatar
Marvin Karegyeya committed
722 723 724
  focusTextInput() {
    if (this.options.filterable) {
      const initialScrollTop = $(window).scrollTop();
725

Marvin Karegyeya's avatar
Marvin Karegyeya committed
726 727 728
      if (this.dropdown.is('.show') && !this.filterInput.is(':focus')) {
        this.filterInput.focus();
      }
729

Marvin Karegyeya's avatar
Marvin Karegyeya committed
730 731 732
      if ($(window).scrollTop() < initialScrollTop) {
        $(window).scrollTop(initialScrollTop);
      }
Clement Ho's avatar
Clement Ho committed
733
    }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
734
  }
Clement Ho's avatar
Clement Ho committed
735

Marvin Karegyeya's avatar
Marvin Karegyeya committed
736 737 738 739
  addInput(fieldName, value, selectedObject, single) {
    // Create hidden input for form
    if (single) {
      $(`input[name="${fieldName}"]`).remove();
740
    }
741

Marvin Karegyeya's avatar
Marvin Karegyeya committed
742 743 744 745 746 747 748
    const $input = $('<input>')
      .attr('type', 'hidden')
      .attr('name', fieldName)
      .val(value);
    if (this.options.inputId != null) {
      $input.attr('id', this.options.inputId);
    }
749

Marvin Karegyeya's avatar
Marvin Karegyeya committed
750 751 752 753 754
    if (this.options.multiSelect) {
      Object.keys(selectedObject).forEach(attribute => {
        $input.attr(`data-${attribute}`, selectedObject[attribute]);
      });
    }
755

Marvin Karegyeya's avatar
Marvin Karegyeya committed
756 757 758
    if (this.options.inputMeta) {
      $input.attr('data-meta', selectedObject[this.options.inputMeta]);
    }
759

Marvin Karegyeya's avatar
Marvin Karegyeya committed
760
    this.dropdown.before($input).trigger('change');
761
  }
762

Marvin Karegyeya's avatar
Marvin Karegyeya committed
763 764 765 766 767
  selectRowAtIndex(index) {
    // If we pass an option index
    let selector;
    if (typeof index !== 'undefined') {
      selector = `${SELECTABLE_CLASSES}:eq(${index}) a`;
768
    } else {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
769 770 771 772 773 774 775 776 777 778 779 780 781 782
      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
    const $el = $(selector, this.dropdown);
    if ($el.length) {
      const href = $el.attr('href');
      if (href && href !== '#') {
        visitUrl(href);
      } else {
        $el.trigger('click');
      }
783
    }
784
  }
785

Marvin Karegyeya's avatar
Marvin Karegyeya committed
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  addArrowKeyEvent() {
    const ARROW_KEY_CODES = [38, 40];
    let selector = SELECTABLE_CLASSES;
    if (this.dropdown.find('.dropdown-toggle-page').length) {
      selector = `.dropdown-page-one ${selector}`;
    }
    return $('body').on('keydown', e => {
      let $listItems, PREV_INDEX;
      const 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;
          }
        } else if (currentKeyCode === 38) {
          // Move up
          if (currentIndex > 0) {
            currentIndex -= 1;
          }
812
        }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
813 814
        if (currentIndex !== PREV_INDEX) {
          this.highlightRowAtIndex($listItems, currentIndex);
815
        }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
816
        return false;
817
      }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
818 819 820
      if (currentKeyCode === 13 && currentIndex !== -1) {
        e.preventDefault();
        this.selectRowAtIndex();
821
      }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
822
    });
823 824
  }

Marvin Karegyeya's avatar
Marvin Karegyeya committed
825 826 827
  // eslint-disable-next-line class-methods-use-this
  removeArrowKeyEvent() {
    return $('body').off('keydown');
828
  }
Marvin Karegyeya's avatar
Marvin Karegyeya committed
829 830 831 832

  resetRows() {
    currentIndex = -1;
    $('.is-focused', this.dropdown).removeClass('is-focused');
833
  }
834

Marvin Karegyeya's avatar
Marvin Karegyeya committed
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
  highlightRowAtIndex($listItems, index) {
    if (!$listItems) {
      // eslint-disable-next-line no-param-reassign
      $listItems = $(SELECTABLE_CLASSES, this.dropdown);
    }

    // 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
    const $listItem = $listItems.eq(index);
    $listItem.find('a:first-child').addClass('is-focused');
    // Dropdown content scroll area
    const $dropdownContent = $listItem.closest('.dropdown-content');
    const dropdownScrollTop = $dropdownContent.scrollTop();
    const dropdownContentHeight = $dropdownContent.outerHeight();
    const dropdownContentTop = $dropdownContent.prop('offsetTop');
    const dropdownContentBottom = dropdownContentTop + dropdownContentHeight;
    // Get the offset bottom of the list item
    const listItemHeight = $listItem.outerHeight();
    const listItemTop = $listItem.prop('offsetTop');
    const 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,
      );
    }
873
  }
874

Marvin Karegyeya's avatar
Marvin Karegyeya committed
875 876 877 878 879 880
  updateLabel(selected = null, el = null, instance = null) {
    let toggleText = this.options.toggleLabel(selected, el, instance);
    if (this.options.updateLabel) {
      // Option to override the dropdown label text
      toggleText = this.options.updateLabel;
    }
881

Marvin Karegyeya's avatar
Marvin Karegyeya committed
882 883 884 885 886 887 888 889 890 891
    return $(this.el)
      .find('.dropdown-toggle-text')
      .text(toggleText);
  }

  // eslint-disable-next-line class-methods-use-this
  clearField(field, isInput) {
    return isInput ? field.val('') : field.remove();
  }
}
892

Marvin Karegyeya's avatar
Marvin Karegyeya committed
893
// eslint-disable-next-line func-names
894
$.fn.glDropdown = function(opts) {
Marvin Karegyeya's avatar
Marvin Karegyeya committed
895
  // eslint-disable-next-line func-names
896 897 898 899 900 901
  return this.each(function() {
    if (!$.data(this, 'glDropdown')) {
      return $.data(this, 'glDropdown', new GitLabDropdown(this, opts));
    }
  });
};