BigW Consortium Gitlab

labels_select.js 15.4 KB
Newer Older
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, initialSelected;
Fatih Acet committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
        $dropdown = $(dropdown);
        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');
24
        $sidebarLabelTooltip = $block.find('.js-sidebar-labels-tooltip');
Fatih Acet committed
25 26
        $value = $block.find('.value');
        $loading = $block.find('.block-loading').fadeOut();
27 28 29 30 31
        initialSelected = $selectbox
          .find('input[name="' + $dropdown.data('field-name') + '"]')
          .map(function () {
            return this.value;
          }).get();
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 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 committed
46 47 48 49 50
        saveLabelData = function() {
          var data, selected;
          selected = $dropdown.closest('.selectbox').find("input[name='" + ($dropdown.data('field-name')) + "']").map(function() {
            return this.value;
          }).get();
51 52 53 54

          if (_.isEqual(initialSelected, selected)) return;
          initialSelected = selected;

Fatih Acet committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68
          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) {
69
            var labelCount, template, labelTooltipTitle, labelTitles;
Fatih Acet committed
70 71 72 73 74 75 76 77 78 79 80 81 82
            $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);
83 84

            if (data.labels.length) {
85 86 87
              labelTitles = data.labels.map(function(label) {
                return label.title;
              });
88

89 90 91
              if (labelTitles.length > 5) {
                labelTitles = labelTitles.slice(0, 5);
                labelTitles.push('and ' + (data.labels.length - 5) + ' more');
92 93
              }

94
              labelTooltipTitle = labelTitles.join(', ');
95 96 97 98 99 100 101 102 103
            } else {
              labelTooltipTitle = '';
              $sidebarLabelTooltip.tooltip('destroy');
            }

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

Fatih Acet committed
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
            $('.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')) {
                if (showNo) {
                  data.unshift({
                    id: 0,
                    title: 'No Label'
                  });
                }
                if (showAny) {
                  data.unshift({
                    isAny: true,
                    title: 'Any Label'
                  });
                }
                if (data.length > 2) {
                  data.splice(2, 0, 'divider');
                }
              }
              return callback(data);
            });
          },
          renderRow: function(label, instance) {
            var $a, $li, active, color, colorEl, indeterminate, removesAll, selectedClass, spacing;
            $li = $('<li>');
            $a = $('<a href="#">');
            selectedClass = [];
            removesAll = label.id === 0 || (label.id == null);
            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) {
168
                // Remove is-indeterminate class if the item will be marked as active
Fatih Acet committed
169 170 171 172 173
                i = selectedClass.indexOf('is-indeterminate');
                if (i !== -1) {
                  selectedClass.splice(i, 1);
                }
                selectedClass.push('is-active');
174
                // Add input manually
Fatih Acet committed
175 176 177
                instance.addInput(this.fieldName, label.id);
              }
            }
178
            if (this.id(label) && $form.find("input[type='hidden'][name='" + ($dropdown.data('fieldName')) + "'][value='" + this.id(label).toString().replace(/'/g, '\\\'') + "']").length) {
Fatih Acet committed
179 180 181 182 183 184 185
              selectedClass.push('is-active');
            }
            if ($dropdown.hasClass('js-multiselect') && removesAll) {
              selectedClass.push('dropdown-clear-active');
            }
            if (label.duplicate) {
              spacing = 100 / label.color.length;
186
              // Reduce the colors to 4
Fatih Acet committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
              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 = '';
            }
207
            // We need to identify which items are actually labels
Fatih Acet committed
208 209 210 211 212
            if (label.id) {
              selectedClass.push('label-item');
              $a.attr('data-label-id', label.id);
            }
            $a.addClass(selectedClass.join(' ')).html(colorEl + " " + label.title);
213
            // Return generated html
Fatih Acet committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            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) {
            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();
255
            // display:block overrides the hide-collapse rule
Fatih Acet committed
256
            $value.removeAttr('style');
257 258 259
            if (page === 'projects:boards:show') {
              return;
            }
Fatih Acet committed
260 261 262 263 264 265 266 267 268 269 270 271 272
            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')) {
273
              // If we are persisting state we need the classes
Fatih Acet committed
274 275 276 277 278 279
              if (!this.options.persistWhenHide) {
                return $dropdown.parent().find('.is-active, .is-indeterminate').removeClass();
              }
            }
          },
          multiSelect: $dropdown.hasClass('js-multiselect'),
280
          clicked: function(label, $el, e) {
Fatih Acet committed
281 282 283 284 285 286 287 288
            var isIssueIndex, isMRIndex, page;
            _this.enableBulkLabelDropdown();
            if ($dropdown.hasClass('js-filter-bulk-update')) {
              return;
            }
            page = $('body').data('page');
            isIssueIndex = page === 'projects:issues:index';
            isMRIndex = page === 'projects:merge_requests:index';
289
            if (page === 'projects:boards:show') {
290
              if (label.isAny) {
291
                gl.issueBoards.BoardsStore.state.filters['label_name'] = [];
292
              } else if ($el.hasClass('is-active')) {
293
                gl.issueBoards.BoardsStore.state.filters['label_name'].push(label.title);
294
              } else {
295
                var filters = gl.issueBoards.BoardsStore.state.filters['label_name'];
296 297
                filters = filters.filter(function (filteredLabel) {
                  return filteredLabel !== label.title;
298
                });
299
                gl.issueBoards.BoardsStore.state.filters['label_name'] = filters;
300 301
              }

302
              gl.issueBoards.BoardsStore.updateFiltersUrl();
303
              e.preventDefault();
304 305
              return;
            } else if ($dropdown.hasClass('js-filter-submit') && (isIssueIndex || isMRIndex)) {
Fatih Acet committed
306 307 308 309 310 311 312 313 314 315 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
              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;
      }
343
      // Remove inputs
Fatih Acet committed
344
      $('.issues_bulk_update .labels-filter input[type="hidden"]').remove();
345
      // Also restore button text
Fatih Acet committed
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
      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);