labels_select.js 15.5 KB
Newer Older
Fatih Acet's avatar
Fatih Acet committed
1 2 3 4 5 6
(function() {
  this.LabelsSelect = (function() {
    function LabelsSelect() {
      var _this;
      _this = this;
      $('.js-label-select').each(function(i, dropdown) {
7
        var $block, $colorPreview, $dropdown, $form, $loading, $selectbox, $sidebarCollapsedValue, $value, abilityName, defaultLabel, enableLabelCreateButton, issueURLSplit, issueUpdateURL, labelHTMLTemplate, labelNoneHTMLTemplate, labelUrl, projectId, saveLabelData, selectedLabel, showAny, showNo, $sidebarLabelTooltip, $toggleText, fieldName, useId, propertyName;
Fatih Acet's avatar
Fatih Acet committed
8
        $dropdown = $(dropdown);
9
        $toggleText = $dropdown.find('.dropdown-toggle-text');
Fatih Acet's avatar
Fatih Acet committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
        projectId = $dropdown.data('project-id');
        labelUrl = $dropdown.data('labels');
        issueUpdateURL = $dropdown.data('issueUpdate');
        selectedLabel = $dropdown.data('selected');
        if ((selectedLabel != null) && !$dropdown.hasClass('js-multiselect')) {
          selectedLabel = selectedLabel.split(',');
        }
        showNo = $dropdown.data('show-no');
        showAny = $dropdown.data('show-any');
        defaultLabel = $dropdown.data('default-label');
        abilityName = $dropdown.data('ability-name');
        $selectbox = $dropdown.closest('.selectbox');
        $block = $selectbox.closest('.block');
        $form = $dropdown.closest('form');
        $sidebarCollapsedValue = $block.find('.sidebar-collapsed-icon span');
25
        $sidebarLabelTooltip = $block.find('.js-sidebar-labels-tooltip');
Fatih Acet's avatar
Fatih Acet committed
26 27
        $value = $block.find('.value');
        $loading = $block.find('.block-loading').fadeOut();
28 29 30 31
        fieldName = $dropdown.data('field-name');
        useId = $dropdown.is('.js-issuable-form-dropdown, .js-filter-bulk-update, .js-label-sidebar-dropdown');
        propertyName = useId ? 'id' : 'title';

Fatih Acet's avatar
Fatih Acet committed
32 33 34 35 36 37 38
        if (issueUpdateURL != null) {
          issueURLSplit = issueUpdateURL.split('/');
        }
        if (issueUpdateURL) {
          labelHTMLTemplate = _.template('<% _.each(labels, function(label){ %> <a href="<%- ["",issueURLSplit[1], issueURLSplit[2],""].join("/") %>issues?label_name[]=<%- encodeURIComponent(label.title) %>"> <span class="label has-tooltip color-label" title="<%- label.description %>" style="background-color: <%- label.color %>; color: <%- label.text_color %>;"> <%- label.title %> </span> </a> <% }); %>');
          labelNoneHTMLTemplate = '<span class="no-value">None</span>';
        }
39

Phil Hughes's avatar
Phil Hughes committed
40 41
        $sidebarLabelTooltip.tooltip();

42 43 44
        if ($dropdown.closest('.dropdown').find('.dropdown-new-label').length) {
          new gl.CreateLabelDropdown($dropdown.closest('.dropdown').find('.dropdown-new-label'), projectId);
        }
45

Fatih Acet's avatar
Fatih Acet committed
46 47
        saveLabelData = function() {
          var data, selected;
48
          selected = $dropdown.closest('.selectbox').find("input[name='" + fieldName + "']").map(function() {
Fatih Acet's avatar
Fatih Acet committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
            return this.value;
          }).get();
          data = {};
          data[abilityName] = {};
          data[abilityName].label_ids = selected;
          if (!selected.length) {
            data[abilityName].label_ids = [''];
          }
          $loading.fadeIn();
          $dropdown.trigger('loading.gl.dropdown');
          return $.ajax({
            type: 'PUT',
            url: issueUpdateURL,
            dataType: 'JSON',
            data: data
          }).done(function(data) {
65
            var labelCount, template, labelTooltipTitle, labelTitles;
Fatih Acet's avatar
Fatih Acet committed
66 67 68 69 70 71 72 73 74 75 76 77 78
            $loading.fadeOut();
            $dropdown.trigger('loaded.gl.dropdown');
            $selectbox.hide();
            data.issueURLSplit = issueURLSplit;
            labelCount = 0;
            if (data.labels.length) {
              template = labelHTMLTemplate(data);
              labelCount = data.labels.length;
            } else {
              template = labelNoneHTMLTemplate;
            }
            $value.removeAttr('style').html(template);
            $sidebarCollapsedValue.text(labelCount);
79 80

            if (data.labels.length) {
81 82 83
              labelTitles = data.labels.map(function(label) {
                return label.title;
              });
84

85 86 87
              if (labelTitles.length > 5) {
                labelTitles = labelTitles.slice(0, 5);
                labelTitles.push('and ' + (data.labels.length - 5) + ' more');
88 89
              }

90
              labelTooltipTitle = labelTitles.join(', ');
91 92 93 94 95 96 97 98 99
            } else {
              labelTooltipTitle = '';
              $sidebarLabelTooltip.tooltip('destroy');
            }

            $sidebarLabelTooltip
              .attr('title', labelTooltipTitle)
              .tooltip('fixTitle');

Fatih Acet's avatar
Fatih Acet committed
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 129 130 131
            $('.has-tooltip', $value).tooltip({
              container: 'body'
            });
            return $value.find('a').each(function(i) {
              return setTimeout((function(_this) {
                return function() {
                  return gl.animate.animate($(_this), 'pulse');
                };
              })(this), 200 * i);
            });
          });
        };
        return $dropdown.glDropdown({
          data: function(term, callback) {
            return $.ajax({
              url: labelUrl
            }).done(function(data) {
              data = _.chain(data).groupBy(function(label) {
                return label.title;
              }).map(function(label) {
                var color;
                color = _.map(label, function(dup) {
                  return dup.color;
                });
                return {
                  id: label[0].id,
                  title: label[0].title,
                  color: color,
                  duplicate: color.length > 1
                };
              }).value();
              if ($dropdown.hasClass('js-extra-options')) {
132
                var extraData = [];
Fatih Acet's avatar
Fatih Acet committed
133
                if (showNo) {
134
                  extraData.unshift({
Fatih Acet's avatar
Fatih Acet committed
135 136 137 138 139
                    id: 0,
                    title: 'No Label'
                  });
                }
                if (showAny) {
140
                  extraData.unshift({
Fatih Acet's avatar
Fatih Acet committed
141 142 143 144
                    isAny: true,
                    title: 'Any Label'
                  });
                }
145 146 147
                if (extraData.length) {
                  extraData.push('divider');
                  data = extraData.concat(data);
Fatih Acet's avatar
Fatih Acet committed
148 149 150 151 152 153 154 155 156 157
                }
              }
              return callback(data);
            });
          },
          renderRow: function(label, instance) {
            var $a, $li, active, color, colorEl, indeterminate, removesAll, selectedClass, spacing;
            $li = $('<li>');
            $a = $('<a href="#">');
            selectedClass = [];
158
            removesAll = label.id <= 0 || (label.id == null);
Fatih Acet's avatar
Fatih Acet committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
            if ($dropdown.hasClass('js-filter-bulk-update')) {
              indeterminate = instance.indeterminateIds;
              active = instance.activeIds;
              if (indeterminate.indexOf(label.id) !== -1) {
                selectedClass.push('is-indeterminate');
              }
              if (active.indexOf(label.id) !== -1) {
                i = selectedClass.indexOf('is-indeterminate');
                if (i !== -1) {
                  selectedClass.splice(i, 1);
                }
                selectedClass.push('is-active');
                instance.addInput(this.fieldName, label.id);
              }
            }
174
            if ($form.find("input[type='hidden'][name='" + ($dropdown.data('fieldName')) + "'][value=\"" + (this.id(label)) + "\"]").length) {
Fatih Acet's avatar
Fatih Acet committed
175 176 177 178 179 180 181 182 183 184 185 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
              selectedClass.push('is-active');
            }
            if ($dropdown.hasClass('js-multiselect') && removesAll) {
              selectedClass.push('dropdown-clear-active');
            }
            if (label.duplicate) {
              spacing = 100 / label.color.length;
              label.color = label.color.filter(function(color, i) {
                return i < 4;
              });
              color = _.map(label.color, function(color, i) {
                var percentFirst, percentSecond;
                percentFirst = Math.floor(spacing * i);
                percentSecond = Math.floor(spacing * (i + 1));
                return color + " " + percentFirst + "%," + color + " " + percentSecond + "% ";
              }).join(',');
              color = "linear-gradient(" + color + ")";
            } else {
              if (label.color != null) {
                color = label.color[0];
              }
            }
            if (color) {
              colorEl = "<span class='dropdown-label-box' style='background: " + color + "'></span>";
            } else {
              colorEl = '';
            }
            if (label.id) {
              selectedClass.push('label-item');
              $a.attr('data-label-id', label.id);
            }
            $a.addClass(selectedClass.join(' ')).html(colorEl + " " + label.title);
            return $li.html($a).prop('outerHTML');
          },
          persistWhenHide: $dropdown.data('persistWhenHide'),
          search: {
            fields: ['title']
          },
          selectable: true,
          filterable: true,
          toggleLabel: function(selected, el) {
            var selected_labels;
            selected_labels = $('.js-label-select').siblings('.dropdown-menu-labels').find('.is-active');
            if (selected && (selected.title != null)) {
              if (selected_labels.length > 1) {
                return selected.title + " +" + (selected_labels.length - 1) + " more";
              } else {
                return selected.title;
              }
            } else if (!selected && selected_labels.length !== 0) {
              if (selected_labels.length > 1) {
                return ($(selected_labels[0]).text()) + " +" + (selected_labels.length - 1) + " more";
              } else if (selected_labels.length === 1) {
                return $(selected_labels).text();
              }
            } else {
              return defaultLabel;
            }
          },
          fieldName: $dropdown.data('field-name'),
          id: function(label) {
236 237 238 239 240 241
            if (label.id <= 0) return;

            if ($dropdown.hasClass('js-issuable-form-dropdown')) {
              return label.id;
            }

Fatih Acet's avatar
Fatih Acet committed
242 243 244 245 246 247 248 249 250 251 252 253 254
            if ($dropdown.hasClass("js-filter-submit") && (label.isAny == null)) {
              return label.title;
            } else {
              return label.id;
            }
          },
          hidden: function() {
            var isIssueIndex, isMRIndex, page, selectedLabels;
            page = $('body').data('page');
            isIssueIndex = page === 'projects:issues:index';
            isMRIndex = page === 'projects:merge_requests:index';
            $selectbox.hide();
            $value.removeAttr('style');
255 256 257 258 259

            if ($dropdown.hasClass('js-issuable-form-dropdown')) {
              return;
            }

260 261 262
            if (page === 'projects:boards:show') {
              return;
            }
Fatih Acet's avatar
Fatih Acet committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
            if ($dropdown.hasClass('js-multiselect')) {
              if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
                selectedLabels = $dropdown.closest('form').find("input:hidden[name='" + ($dropdown.data('fieldName')) + "']");
                Issuable.filterResults($dropdown.closest('form'));
              } else if ($dropdown.hasClass('js-filter-submit')) {
                $dropdown.closest('form').submit();
              } else {
                if (!$dropdown.hasClass('js-filter-bulk-update')) {
                  saveLabelData();
                }
              }
            }
            if ($dropdown.hasClass('js-filter-bulk-update')) {
              if (!this.options.persistWhenHide) {
                return $dropdown.parent().find('.is-active, .is-indeterminate').removeClass();
              }
            }
          },
          multiSelect: $dropdown.hasClass('js-multiselect'),
282
          clicked: function(label, $el, e) {
Fatih Acet's avatar
Fatih Acet committed
283 284
            var isIssueIndex, isMRIndex, page;
            _this.enableBulkLabelDropdown();
285 286 287 288 289 290 291 292

            if ($dropdown.parent().find('.is-active:not(.dropdown-clear-active)').length) {
              $dropdown.parent()
                .find('.dropdown-clear-active')
                .removeClass('is-active')
            }

            if ($dropdown.hasClass('js-filter-bulk-update') || $dropdown.hasClass('js-issuable-form-dropdown')) {
Fatih Acet's avatar
Fatih Acet committed
293 294
              return;
            }
295

Fatih Acet's avatar
Fatih Acet committed
296 297 298
            page = $('body').data('page');
            isIssueIndex = page === 'projects:issues:index';
            isMRIndex = page === 'projects:merge_requests:index';
299
            if (page === 'projects:boards:show') {
Phil Hughes's avatar
Phil Hughes committed
300
              if (label.isAny) {
301
                gl.issueBoards.BoardsStore.state.filters['label_name'] = [];
Phil Hughes's avatar
Phil Hughes committed
302
              } else if (label.title) {
303
                gl.issueBoards.BoardsStore.state.filters['label_name'].push(label.title);
Phil Hughes's avatar
Phil Hughes committed
304
              } else {
305
                var filters = gl.issueBoards.BoardsStore.state.filters['label_name'];
306 307 308
                filters = filters.filter(function (label) {
                  return label !== $el.text().trim();
                });
309
                gl.issueBoards.BoardsStore.state.filters['label_name'] = filters;
Phil Hughes's avatar
Phil Hughes committed
310 311
              }

312
              gl.issueBoards.BoardsStore.updateFiltersUrl();
313
              e.preventDefault();
314 315
              return;
            } else if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
Fatih Acet's avatar
Fatih Acet committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
              if (!$dropdown.hasClass('js-multiselect')) {
                selectedLabel = label.title;
                return Issuable.filterResults($dropdown.closest('form'));
              }
            } else if ($dropdown.hasClass('js-filter-submit')) {
              return $dropdown.closest('form').submit();
            } else {
              if ($dropdown.hasClass('js-multiselect')) {

              } else {
                return saveLabelData();
              }
            }
          },
          setIndeterminateIds: function() {
            if (this.dropdown.find('.dropdown-menu-toggle').hasClass('js-filter-bulk-update')) {
              return this.indeterminateIds = _this.getIndeterminateIds();
            }
          },
          setActiveIds: function() {
            if (this.dropdown.find('.dropdown-menu-toggle').hasClass('js-filter-bulk-update')) {
              return this.activeIds = _this.getActiveIds();
            }
          }
        });
      });
      this.bindEvents();
    }

    LabelsSelect.prototype.bindEvents = function() {
      return $('body').on('change', '.selected_issue', this.onSelectCheckboxIssue);
    };

    LabelsSelect.prototype.onSelectCheckboxIssue = function() {
      if ($('.selected_issue:checked').length) {
        return;
      }
      $('.issues_bulk_update .labels-filter input[type="hidden"]').remove();
      return $('.issues_bulk_update .labels-filter .dropdown-toggle-text').text('Label');
    };

    LabelsSelect.prototype.getIndeterminateIds = function() {
      var label_ids;
      label_ids = [];
      $('.selected_issue:checked').each(function(i, el) {
        var issue_id;
        issue_id = $(el).data('id');
        return label_ids.push($("#issue_" + issue_id).data('labels'));
      });
      return _.flatten(label_ids);
    };

    LabelsSelect.prototype.getActiveIds = function() {
      var label_ids;
      label_ids = [];
      $('.selected_issue:checked').each(function(i, el) {
        var issue_id;
        issue_id = $(el).data('id');
        return label_ids.push($("#issue_" + issue_id).data('labels'));
      });
      return _.intersection.apply(_, label_ids);
    };

    LabelsSelect.prototype.enableBulkLabelDropdown = function() {
      var issuableBulkActions;
      if ($('.selected_issue:checked').length) {
        issuableBulkActions = $('.bulk-update').data('bulkActions');
        return issuableBulkActions.willUpdateLabels = true;
      }
    };

    return LabelsSelect;

  })();

}).call(this);