BigW Consortium Gitlab

LabelManager.js.coffee 2.15 KB
Newer Older
1
class @LabelManager
2 3
  errorMessage: 'Unable to update label prioritization at this time'

4 5 6 7 8 9 10 11 12 13
  constructor: (opts = {}) ->
    # Defaults
    {
      @togglePriorityButton = $('.js-toggle-priority')
      @prioritizedLabels = $('.js-prioritized-labels')
      @otherLabels = $('.js-other-labels')
    } = opts

    @prioritizedLabels.sortable(
      items: 'li'
14 15
      placeholder: 'list-placeholder'
      axis: 'y'
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
      update: @onPrioritySortUpdate.bind(@)
    )

    @bindEvents()

  bindEvents: ->
    @togglePriorityButton.on 'click', @, @onTogglePriorityClick

  onTogglePriorityClick: (e) ->
    e.preventDefault()
    _this = e.data
    $btn = $(e.currentTarget)
    $label = $("##{$btn.data('domId')}")
    action = if $btn.parents('.js-prioritized-labels').length then 'remove' else 'add'
    _this.toggleLabelPriority($label, action)

32
  toggleLabelPriority: ($label, action, persistState = true) ->
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    _this = @
    url = $label.find('.js-toggle-priority').data 'url'

    $target = @prioritizedLabels
    $from = @otherLabels

    # Optimistic update
    if action is 'remove'
      $target = @otherLabels
      $from = @prioritizedLabels

    if $from.find('li').length is 1
      $from.find('.empty-message').show()

    if not $target.find('li').length
      $target.find('.empty-message').hide()

    $label.detach().appendTo($target)

    # Return if we are not persisting state
53
    return unless persistState
54

55 56 57
    if action is 'remove'
      xhr = $.ajax url: url, type: 'DELETE'
    else
58
      xhr = @savePrioritySort($label, action)
59

60
    xhr.fail @rollbackLabelPosition.bind(@, $label, action)
61

62 63
  onPrioritySortUpdate: ->
    xhr = @savePrioritySort()
64 65

    xhr.fail ->
66 67 68 69 70 71 72 73 74 75 76 77 78
      new Flash(@errorMessage, 'alert')

  savePrioritySort: () ->
    $.post
      url: @prioritizedLabels.data('url')
      data:
        label_ids: @getSortedLabelsIds()

  rollbackLabelPosition: ($label, originalAction)->
    action = if originalAction is 'remove' then 'add' else 'remove'
    @toggleLabelPriority($label, action, false)

    new Flash(@errorMessage, 'alert')
79 80 81 82 83

  getSortedLabelsIds: ->
    sortedIds = []
    @prioritizedLabels.find('li').each ->
      sortedIds.push $(@).data 'id'
84
    sortedIds