gl_dropdown.js.coffee 17.2 KB
Newer Older
Phil Hughes's avatar
Phil Hughes committed
1 2
class GitLabDropdownFilter
  BLUR_KEYCODES = [27, 40]
3
  ARROW_KEY_CODES = [38, 40]
4
  HAS_VALUE_CLASS = "has-value"
Phil Hughes's avatar
Phil Hughes committed
5

6
  constructor: (@input, @options) ->
7
    {
8
      @filterInputBlur = true
9
    } = @options
Phil Hughes's avatar
Phil Hughes committed
10

11 12 13
    $inputContainer = @input.parent()
    $clearButton = $inputContainer.find('.js-dropdown-input-clear')

Alfredo Sumaran's avatar
typo  
Alfredo Sumaran committed
14
    @indeterminateIds = []
Alfredo Sumaran's avatar
Alfredo Sumaran committed
15

16 17 18 19 20 21 22 23
    # Clear click
    $clearButton.on 'click', (e) =>
      e.preventDefault()
      e.stopPropagation()
      @input
        .val('')
        .trigger('keyup')
        .focus()
Phil Hughes's avatar
Phil Hughes committed
24 25

    # Key events
Phil Hughes's avatar
Phil Hughes committed
26
    timeout = ""
Phil Hughes's avatar
Phil Hughes committed
27
    @input.on "keyup", (e) =>
28 29 30 31
      keyCode = e.which

      return if ARROW_KEY_CODES.indexOf(keyCode) >= 0

32 33 34 35 36
      if @input.val() isnt "" and !$inputContainer.hasClass HAS_VALUE_CLASS
        $inputContainer.addClass HAS_VALUE_CLASS
      else if @input.val() is "" and $inputContainer.hasClass HAS_VALUE_CLASS
        $inputContainer.removeClass HAS_VALUE_CLASS

37 38
      if keyCode is 13
        return false
39

40 41 42 43 44
      # Only filter asynchronously only if option remote is set
      if @options.remote
        clearTimeout timeout
        timeout = setTimeout =>
          blur_field = @shouldBlur keyCode
Phil Hughes's avatar
Phil Hughes committed
45

46 47
          if blur_field and @filterInputBlur
            @input.blur()
Phil Hughes's avatar
Phil Hughes committed
48

49
          @options.query @input.val(), (data) =>
50
            @options.callback(data)
51 52 53
        , 250
      else
        @filter @input.val()
Phil Hughes's avatar
Phil Hughes committed
54 55 56 57 58

  shouldBlur: (keyCode) ->
    return BLUR_KEYCODES.indexOf(keyCode) >= 0

  filter: (search_text) ->
59
    @options.onFilter(search_text) if @options.onFilter
60
    data = @options.data()
Phil Hughes's avatar
Phil Hughes committed
61

62
    if data? and not @options.filterByText
Phil Hughes's avatar
Phil Hughes committed
63
      results = data
Phil Hughes's avatar
Phil Hughes committed
64

Phil Hughes's avatar
Phil Hughes committed
65
      if search_text isnt ''
Alfredo Sumaran's avatar
Alfredo Sumaran committed
66 67 68 69 70
        # When data is an array of objects therefore [object Array] e.g.
        # [
        #   { prop: 'foo' },
        #   { prop: 'baz' }
        # ]
Alfredo Sumaran's avatar
Alfredo Sumaran committed
71 72 73 74
        if _.isArray(data)
          results = fuzzaldrinPlus.filter(data, search_text,
            key: @options.keys
          )
Alfredo Sumaran's avatar
Alfredo Sumaran committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        else
          # If data is grouped therefore an [object Object]. e.g.
          # {
          #   groupName1: [
          #     { prop: 'foo' },
          #     { prop: 'baz' }
          #   ],
          #   groupName2: [
          #     { prop: 'abc' },
          #     { prop: 'def' }
          #   ]
          # }
          if gl.utils.isObject data
            results = {}
            for key, group of data
              tmp = fuzzaldrinPlus.filter(group, search_text,
                key: @options.keys
              )

              if tmp.length
                results[key] = tmp.map (item) -> item
Phil Hughes's avatar
Phil Hughes committed
96 97 98 99 100 101 102 103 104 105

      @options.callback results
    else
      elements = @options.elements()

      if search_text
        elements.each ->
          $el = $(@)
          matches = fuzzaldrinPlus.match($el.text().trim(), search_text)

106
          unless $el.is('.dropdown-header')
107 108 109 110
            if matches.length
              $el.show()
            else
              $el.hide()
Phil Hughes's avatar
Phil Hughes committed
111 112
      else
        elements.show()
Phil Hughes's avatar
Phil Hughes committed
113 114 115 116 117 118 119 120 121 122 123 124

class GitLabDropdownRemote
  constructor: (@dataEndpoint, @options) ->

  execute: ->
    if typeof @dataEndpoint is "string"
      @fetchData()
    else if typeof @dataEndpoint is "function"
      if @options.beforeSend
        @options.beforeSend()

      # Fetch the data by calling the data funcfion
Phil Hughes's avatar
Phil Hughes committed
125
      @dataEndpoint "", (data) =>
Phil Hughes's avatar
Phil Hughes committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        if @options.success
          @options.success(data)

        if @options.beforeSend
          @options.beforeSend()

  # Fetch the data through ajax if the data is a string
  fetchData: ->
    $.ajax(
      url: @dataEndpoint,
      dataType: @options.dataType,
      beforeSend: =>
        if @options.beforeSend
          @options.beforeSend()
      success: (data) =>
        if @options.success
          @options.success(data)
    )

class GitLabDropdown
  LOADING_CLASS = "is-loading"
147
  PAGE_TWO_CLASS = "is-page-two"
148
  ACTIVE_CLASS = "is-active"
149
  INDETERMINATE_CLASS = "is-indeterminate"
150
  currentIndex = -1
Phil Hughes's avatar
Phil Hughes committed
151

152 153
  FILTER_INPUT = '.dropdown-input .dropdown-input-field'

Phil Hughes's avatar
Phil Hughes committed
154
  constructor: (@el, @options) ->
155 156 157
    self = @
    selector = $(@el).data "target"
    @dropdown = if selector? then $(selector) else $(@el).parent()
158 159 160 161

    # Set Defaults
    {
      # If no input is passed create a default one
Alfredo Sumaran's avatar
Alfredo Sumaran committed
162
      @filterInput = @getElement(FILTER_INPUT)
163
      @highlight = false
164
      @filterInputBlur = true
165 166 167 168 169 170
    } = @options

    self = @

    # If selector was passed
    if _.isString(@filterInput)
Alfredo Sumaran's avatar
Alfredo Sumaran committed
171
      @filterInput = @getElement(@filterInput)
172

Phil Hughes's avatar
Phil Hughes committed
173
    searchFields = if @options.search then @options.search.fields else [];
Phil Hughes's avatar
Phil Hughes committed
174 175

    if @options.data
Alfredo Sumaran's avatar
Alfredo Sumaran committed
176 177 178
      # If we provided data
      # data could be an array of objects or a group of arrays
      if _.isObject(@options.data) and not _.isFunction(@options.data)
179
        @fullData = @options.data
180 181 182 183 184 185 186 187
        @parseData @options.data
      else
        # Remote data
        @remote = new GitLabDropdownRemote @options.data, {
          dataType: @options.dataType,
          beforeSend: @toggleLoading.bind(@)
          success: (data) =>
            @fullData = data
Phil Hughes's avatar
Phil Hughes committed
188

189
            @parseData @fullData
190 191

            @filter.input.trigger('keyup') if @options.filterable and @filter and @filter.input
192
        }
Phil Hughes's avatar
Phil Hughes committed
193

194
    # Init filterable
Phil Hughes's avatar
Phil Hughes committed
195
    if @options.filterable
196
      @filter = new GitLabDropdownFilter @filterInput,
197
        filterInputBlur: @filterInputBlur
198
        filterByText: @options.filterByText
199
        onFilter: @options.onFilter
200 201
        remote: @options.filterRemote
        query: @options.data
Phil Hughes's avatar
Phil Hughes committed
202
        keys: searchFields
Phil Hughes's avatar
Phil Hughes committed
203
        elements: =>
Phil Hughes's avatar
Phil Hughes committed
204
          selector = '.dropdown-content li:not(.divider)'
Phil Hughes's avatar
Phil Hughes committed
205

Phil Hughes's avatar
Phil Hughes committed
206
          if @dropdown.find('.dropdown-toggle-page').length
Phil Hughes's avatar
Phil Hughes committed
207 208 209
            selector = ".dropdown-page-one #{selector}"

          return $(selector)
210 211 212
        data: =>
          return @fullData
        callback: (data) =>
213
          currentIndex = -1
214
          @parseData data
Phil Hughes's avatar
Phil Hughes committed
215 216

    # Event listeners
217

218 219
    @dropdown.on "shown.bs.dropdown", @opened
    @dropdown.on "hidden.bs.dropdown", @hidden
220
    $(@el).on "update.label", @updateLabel
221
    @dropdown.on "click", ".dropdown-menu, .dropdown-menu-close", @shouldPropagate
222 223 224
    @dropdown.on 'keyup', (e) =>
      if e.which is 27 # Escape key
        $('.dropdown-menu-close', @dropdown).trigger 'click'
225
    @dropdown.on 'blur', 'a', (e) =>
Phil Hughes's avatar
Phil Hughes committed
226 227 228
      if e.relatedTarget?
        $relatedTarget = $(e.relatedTarget)
        $dropdownMenu = $relatedTarget.closest('.dropdown-menu')
229

Phil Hughes's avatar
Phil Hughes committed
230 231
        if $dropdownMenu.length is 0
          @dropdown.removeClass('open')
232 233 234 235 236 237 238

    if @dropdown.find(".dropdown-toggle-page").length
      @dropdown.find(".dropdown-toggle-page, .dropdown-menu-back").on "click", (e) =>
        e.preventDefault()
        e.stopPropagation()

        @togglePage()
Phil Hughes's avatar
Phil Hughes committed
239 240

    if @options.selectable
241
      selector = ".dropdown-content a"
242 243

      if @dropdown.find(".dropdown-toggle-page").length
244
        selector = ".dropdown-page-one .dropdown-content a"
245 246

      @dropdown.on "click", selector, (e) ->
247 248
        $el = $(@)
        selected = self.rowClicked $el
Phil Hughes's avatar
Phil Hughes committed
249 250

        if self.options.clicked
251
          self.options.clicked(selected, $el, e)
Phil Hughes's avatar
Phil Hughes committed
252

253 254
        $el.trigger('blur')

Alfredo Sumaran's avatar
Alfredo Sumaran committed
255 256 257
  # Finds an element inside wrapper element
  getElement: (selector) ->
    @dropdown.find selector
258

Phil Hughes's avatar
Phil Hughes committed
259 260 261
  toggleLoading: ->
    $('.dropdown-menu', @dropdown).toggleClass LOADING_CLASS

262 263 264 265 266 267 268 269 270
  togglePage: ->
    menu = $('.dropdown-menu', @dropdown)

    if menu.hasClass(PAGE_TWO_CLASS)
      if @remote
        @remote.execute()

    menu.toggleClass PAGE_TWO_CLASS

271 272 273
    # Focus first visible input on active page
    @dropdown.find('[class^="dropdown-page-"]:visible :text:visible:first').focus()

Phil Hughes's avatar
Phil Hughes committed
274 275 276 277 278 279
  parseData: (data) ->
    @renderedData = data

    if @options.filterable and data.length is 0
      # render no matching results
      html = [@noResults()]
Alfredo Sumaran's avatar
Alfredo Sumaran committed
280 281
    else
      # Handle array groups
Alfredo Sumaran's avatar
Alfredo Sumaran committed
282
      if gl.utils.isObject data
Alfredo Sumaran's avatar
Alfredo Sumaran committed
283 284 285 286 287 288 289 290 291 292 293
        html = []
        for name, groupData of data
          # Add header for each group
          html.push(@renderItem(header: name, name))

          @renderData(groupData, name)
            .map (item) ->
              html.push item
      else
        # Render each row
        html = @renderData(data)
Phil Hughes's avatar
Phil Hughes committed
294 295

    # Render the full menu
296
    full_html = @renderMenu(html)
Phil Hughes's avatar
Phil Hughes committed
297 298 299

    @appendMenu(full_html)

Alfredo Sumaran's avatar
Alfredo Sumaran committed
300
  renderData: (data, group = false) ->
Alfredo Sumaran's avatar
Alfredo Sumaran committed
301
    data.map (obj, index) =>
Alfredo Sumaran's avatar
Alfredo Sumaran committed
302 303
      return @renderItem(obj, group, index)

304 305
  shouldPropagate: (e) =>
    if @options.multiSelect
306
      $target = $(e.target)
307

308
      if not $target.hasClass('dropdown-menu-close') and not $target.hasClass('dropdown-menu-close-icon') and not $target.data('is-link')
309 310 311 312
        e.stopPropagation()
        return false
      else
        return true
313

Phil Hughes's avatar
Phil Hughes committed
314
  opened: =>
315 316
    @addArrowKeyEvent()

Alfredo Sumaran's avatar
typo  
Alfredo Sumaran committed
317 318
    if @options.setIndeterminateIds
      @options.setIndeterminateIds.call(@)
Alfredo Sumaran's avatar
Alfredo Sumaran committed
319

320 321 322
    if @options.setActiveIds
      @options.setActiveIds.call(@)

Alfredo Sumaran's avatar
typo  
Alfredo Sumaran committed
323
    # Makes indeterminate items effective
Alfredo Sumaran's avatar
Alfredo Sumaran committed
324 325 326
    if @fullData and @dropdown.find('.dropdown-menu-toggle').hasClass('js-filter-bulk-update')
      @parseData @fullData

327 328
    contentHtml = $('.dropdown-content', @dropdown).html()
    if @remote && contentHtml is ""
Phil Hughes's avatar
Phil Hughes committed
329 330
      @remote.execute()

Phil Hughes's avatar
Phil Hughes committed
331
    if @options.filterable
332
      @filterInput.focus()
Phil Hughes's avatar
Phil Hughes committed
333

334 335
    @dropdown.trigger('shown.gl.dropdown')

336
  hidden: (e) =>
337
    @removeArrayKeyEvent()
Alfredo Sumaran's avatar
Alfredo Sumaran committed
338

339 340
    $input = @dropdown.find(".dropdown-input-field")

Phil Hughes's avatar
Phil Hughes committed
341
    if @options.filterable
342
      $input
343 344
        .blur()
        .val("")
345 346 347 348 349

    # Triggering 'keyup' will re-render the dropdown which is not always required
    # specially if we want to keep the state of the dropdown needed for bulk-assignment
    if not @options.persistWhenHide
      $input.trigger("keyup")
Phil Hughes's avatar
Phil Hughes committed
350

351 352 353
    if @dropdown.find(".dropdown-toggle-page").length
      $('.dropdown-menu', @dropdown).removeClass PAGE_TWO_CLASS

354 355 356
    if @options.hidden
      @options.hidden.call(@,e)

357 358
    @dropdown.trigger('hidden.gl.dropdown')

359

Phil Hughes's avatar
Phil Hughes committed
360 361 362 363 364 365 366
  # Render the full menu
  renderMenu: (html) ->
    menu_html = ""

    if @options.renderMenu
      menu_html = @options.renderMenu(html)
    else
367 368
      menu_html = $('<ul />')
        .append(html)
Phil Hughes's avatar
Phil Hughes committed
369 370 371 372 373

    return menu_html

  # Append the menu into the dropdown
  appendMenu: (html) ->
374 375 376
    selector = '.dropdown-content'
    if @dropdown.find(".dropdown-toggle-page").length
      selector = ".dropdown-page-one .dropdown-content"
377 378
    $(selector, @dropdown)
      .empty()
Phil Hughes's avatar
Phil Hughes committed
379
      .append(html)
Phil Hughes's avatar
Phil Hughes committed
380 381

  # Render the row
Alfredo Sumaran's avatar
Alfredo Sumaran committed
382
  renderItem: (data, group = false, index = false) ->
Phil Hughes's avatar
Phil Hughes committed
383 384
    html = ""

385
    # Divider
386 387
    return "<li class='divider'></li>" if data is "divider"

388 389 390
    # Separator is a full-width divider
    return "<li class='separator'></li>" if data is "separator"

391 392 393
    # Header
    return "<li class='dropdown-header'>#{data.header}</li>" if data.header?

Phil Hughes's avatar
Phil Hughes committed
394 395
    if @options.renderRow
      # Call the render function
Alfredo Sumaran's avatar
Alfredo Sumaran committed
396
      html = @options.renderRow.call(@options, data, @)
Phil Hughes's avatar
Phil Hughes committed
397
    else
398 399 400 401 402 403 404
      if not selected
        value = if @options.id then @options.id(data) else data.id
        fieldName = @options.fieldName
        field = @dropdown.parent().find("input[name='#{fieldName}'][value='#{value}']")
        if field.length
          selected = true

405 406 407 408
      # Set URL
      if @options.url?
        url = @options.url(data)
      else
Alfredo Sumaran's avatar
Alfredo Sumaran committed
409
        url = if data.url? then data.url else '#'
410 411

      # Set Text
412 413 414
      if @options.text?
        text = @options.text(data)
      else
415
        text = if data.text? then data.text else ''
416

Phil Hughes's avatar
Phil Hughes committed
417 418 419 420 421
      cssClass = "";

      if selected
        cssClass = "is-active"

422 423
      if @highlight
        text = @highlightTextMatches(text, @filterInput.val())
424

Alfredo Sumaran's avatar
Alfredo Sumaran committed
425 426 427 428 429
      if group
        groupAttrs = "data-group='#{group}' data-index='#{index}'"
      else
        groupAttrs = ''

430
      html = "<li>
Alfredo Sumaran's avatar
Alfredo Sumaran committed
431
        <a href='#{url}' #{groupAttrs} class='#{cssClass}'>
432 433 434
          #{text}
        </a>
      </li>"
Phil Hughes's avatar
Phil Hughes committed
435 436 437

    return html

438 439
  highlightTextMatches: (text, term) ->
    occurrences = fuzzaldrinPlus.match(text, term)
Alfredo Sumaran's avatar
Alfredo Sumaran committed
440 441 442
    text.split('').map((character, i) ->
      if i in occurrences then "<b>#{character}</b>" else character
    ).join('')
443

Phil Hughes's avatar
Phil Hughes committed
444
  noResults: ->
Phil Hughes's avatar
Phil Hughes committed
445 446 447 448 449
    html = "<li class='dropdown-menu-empty-link'>
      <a href='#' class='is-focused'>
        No matching results.
      </a>
    </li>"
Phil Hughes's avatar
Phil Hughes committed
450

451
  highlightRow: (index) ->
Alfredo Sumaran's avatar
Alfredo Sumaran committed
452
    if @filterInput.val() isnt ""
453 454 455 456
      selector = '.dropdown-content li:first-child a'
      if @dropdown.find(".dropdown-toggle-page").length
        selector = ".dropdown-page-one .dropdown-content li:first-child a"

457
      @getElement(selector).addClass 'is-focused'
458

Phil Hughes's avatar
Phil Hughes committed
459 460
  rowClicked: (el) ->
    fieldName = @options.fieldName
461 462
    isInput = $(@el).is('input')

463
    if @renderedData
Alfredo Sumaran's avatar
Alfredo Sumaran committed
464 465 466 467 468
      groupName = el.data('group')
      if groupName
        selectedIndex = el.data('index')
        selectedObject = @renderedData[groupName][selectedIndex]
      else
Alfredo Sumaran's avatar
Alfredo Sumaran committed
469
        selectedIndex = el.closest('li').index()
Alfredo Sumaran's avatar
Alfredo Sumaran committed
470 471
        selectedObject = @renderedData[selectedIndex]

472
    value = if @options.id then @options.id(selectedObject, el) else selectedObject.id
473 474 475 476 477 478

    if isInput
      field = $(@el)
    else
      field = @dropdown.parent().find("input[name='#{fieldName}'][value='#{value}']")

479
    if el.hasClass(ACTIVE_CLASS)
480
      el.removeClass(ACTIVE_CLASS)
481 482 483 484 485

      if isInput
        field.val('')
      else
        field.remove()
Phil Hughes's avatar
Phil Hughes committed
486 487 488

      # Toggle the dropdown label
      if @options.toggleLabel
489
        @updateLabel(selectedObject, el, @)
490 491
      else
        selectedObject
492 493 494 495
    else if el.hasClass(INDETERMINATE_CLASS)
      el.addClass ACTIVE_CLASS
      el.removeClass INDETERMINATE_CLASS

Alfredo Sumaran's avatar
Alfredo Sumaran committed
496
      if not value?
497 498
        field.remove()

Alfredo Sumaran's avatar
Alfredo Sumaran committed
499
      if not field.length and fieldName
500 501 502
        @addInput(fieldName, value)

      return selectedObject
Phil Hughes's avatar
Phil Hughes committed
503
    else
504
      if not @options.multiSelect or el.hasClass('dropdown-clear-active')
505
        @dropdown.find(".#{ACTIVE_CLASS}").removeClass ACTIVE_CLASS
506 507 508

        unless isInput
          @dropdown.parent().find("input[name='#{fieldName}']").remove()
509

510 511 512
      if !value?
        field.remove()

513
      # Toggle active class for the tick mark
Phil Hughes's avatar
Phil Hughes committed
514
      el.addClass ACTIVE_CLASS
515

516 517
      # Toggle the dropdown label
      if @options.toggleLabel
518
        @updateLabel(selectedObject, el, @)
519
      if value?
520
        if !field.length and fieldName
521
          @addInput(fieldName, value)
522
        else
523 524 525
          field
            .val value
            .trigger 'change'
Phil Hughes's avatar
Phil Hughes committed
526

Phil Hughes's avatar
Phil Hughes committed
527 528
      return selectedObject

529 530
  addInput: (fieldName, value)->
    # Create hidden input for form
Alfredo Sumaran's avatar
Alfredo Sumaran committed
531 532 533
    $input = $('<input>').attr('type', 'hidden')
                         .attr('name', fieldName)
                        .val(value)
Alfredo Sumaran's avatar
Alfredo Sumaran committed
534

535
    if @options.inputId?
Alfredo Sumaran's avatar
Alfredo Sumaran committed
536
      $input.attr('id', @options.inputId)
537

Alfredo Sumaran's avatar
Alfredo Sumaran committed
538
    @dropdown.before $input
539

540 541
  selectRowAtIndex: (e, index) ->
    selector = ".dropdown-content li:not(.divider,.dropdown-header,.separator):eq(#{index}) a"
542

543
    if @dropdown.find(".dropdown-toggle-page").length
544
      selector = ".dropdown-page-one #{selector}"
545

546
    # simulate a click on the first link
547 548 549 550 551
    $el = $(selector, @dropdown)

    if $el.length
      e.preventDefault()
      e.stopImmediatePropagation()
552
      $el.first().trigger('click')
553

554 555 556 557
  addArrowKeyEvent: ->
    ARROW_KEY_CODES = [38, 40]
    $input = @dropdown.find(".dropdown-input-field")

558
    selector = '.dropdown-content li:not(.divider,.dropdown-header,.separator)'
559 560 561 562
    if @dropdown.find(".dropdown-toggle-page").length
      selector = ".dropdown-page-one #{selector}"

    $('body').on 'keydown', (e) =>
563
      currentKeyCode = e.which
564 565 566

      if ARROW_KEY_CODES.indexOf(currentKeyCode) >= 0
        e.preventDefault()
567
        e.stopImmediatePropagation()
568

569
        PREV_INDEX = currentIndex
570 571
        $listItems = $(selector, @dropdown)

572 573
        # if @options.filterable
        #   $input.blur()
574 575 576

        if currentKeyCode is 40
          # Move down
577
          currentIndex += 1 if currentIndex < ($listItems.length - 1)
578 579
        else if currentKeyCode is 38
          # Move up
580
          currentIndex -= 1 if currentIndex > 0
581

582
        @highlightRowAtIndex($listItems, currentIndex) if currentIndex isnt PREV_INDEX
583 584 585

        return false

586 587
      if currentKeyCode is 13 and currentIndex isnt -1
        @selectRowAtIndex e, currentIndex
588

589 590 591
  removeArrayKeyEvent: ->
    $('body').off 'keydown'

592
  highlightRowAtIndex: ($listItems, index) ->
593 594 595 596
    # Remove the class for the previously focused row
    $('.is-focused', @dropdown).removeClass 'is-focused'

    # Update the class for the row at the specific index
597
    $listItem = $listItems.eq(index)
Phil Hughes's avatar
Phil Hughes committed
598
    $listItem.find('a:first-child').addClass "is-focused"
599

600 601
    # Dropdown content scroll area
    $dropdownContent = $listItem.closest('.dropdown-content')
602 603
    dropdownScrollTop = $dropdownContent.scrollTop()
    dropdownContentHeight = $dropdownContent.outerHeight()
604 605
    dropdownContentTop = $dropdownContent.prop('offsetTop')
    dropdownContentBottom = dropdownContentTop + dropdownContentHeight
606 607

    # Get the offset bottom of the list item
608
    listItemHeight = $listItem.outerHeight()
609 610
    listItemTop = $listItem.prop('offsetTop')
    listItemBottom = listItemTop + listItemHeight
611

612
    if listItemBottom > dropdownContentBottom + dropdownScrollTop
613 614
      # Scroll the dropdown content down
      $dropdownContent.scrollTop(listItemBottom - dropdownContentBottom)
615 616 617
    else if listItemTop < dropdownContentTop + dropdownScrollTop
      # Scroll the dropdown content up
      $dropdownContent.scrollTop(listItemTop - dropdownContentTop)
618

619 620
  updateLabel: (selected = null, el = null, instance = null) =>
    $(@el).find(".dropdown-toggle-text").text @options.toggleLabel(selected, el, instance)
621

Phil Hughes's avatar
Phil Hughes committed
622 623
$.fn.glDropdown = (opts) ->
  return @.each ->
624 625
    if (!$.data @, 'glDropdown')
      $.data(@, 'glDropdown', new GitLabDropdown @, opts)