summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/LabelManager.js.coffee
blob: 6d8faba40d73464a7d7931e06a2f349809245ce6 (plain)
1
2
3
4
5
6
7
8
9
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
87
88
89
90
91
92
class @LabelManager
  errorMessage: 'Unable to update label prioritization at this time'

  constructor: (opts = {}) ->
    # Defaults
    {
      @togglePriorityButton = $('.js-toggle-priority')
      @prioritizedLabels = $('.js-prioritized-labels')
      @otherLabels = $('.js-other-labels')
    } = opts

    @prioritizedLabels.sortable(
      items: 'li'
      placeholder: 'list-placeholder'
      axis: 'y'
      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'

    # Make sure tooltip will hide
    $tooltip = $ "##{$btn.find('.has-tooltip:visible').attr('aria-describedby')}"
    $tooltip.tooltip 'destroy'

    _this.toggleLabelPriority($label, action)

  toggleLabelPriority: ($label, action, persistState = true) ->
    _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').removeClass('hidden')

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

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

    # Return if we are not persisting state
    return unless persistState

    if action is 'remove'
      xhr = $.ajax url: url, type: 'DELETE'

      # Restore empty message
      $from.find('.empty-message').removeClass('hidden') unless $from.find('li').length
    else
      xhr = @savePrioritySort($label, action)

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

  onPrioritySortUpdate: ->
    xhr = @savePrioritySort()

    xhr.fail ->
      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')

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