gfm_auto_complete.js.es6 11.3 KB
Newer Older
1
/* eslint-disable */
2
// Creates the variables for setting up GFM auto-completion
Fatih Acet's avatar
Fatih Acet committed
3 4 5 6 7 8 9 10 11 12
(function() {
  if (window.GitLab == null) {
    window.GitLab = {};
  }

  GitLab.GfmAutoComplete = {
    dataLoading: false,
    dataLoaded: false,
    cachedData: {},
    dataSource: '',
13
    // Emoji
Fatih Acet's avatar
Fatih Acet committed
14 15 16
    Emoji: {
      template: '<li>${name} <img alt="${name}" height="20" src="${path}" width="20" /></li>'
    },
17
    // Team Members
Fatih Acet's avatar
Fatih Acet committed
18
    Members: {
19
      template: '<li>${avatarTag} ${username} <small>${title}</small></li>'
Fatih Acet's avatar
Fatih Acet committed
20 21 22 23
    },
    Labels: {
      template: '<li><span class="dropdown-label-box" style="background: ${color}"></span> ${title}</li>'
    },
24
    // Issues and MergeRequests
Fatih Acet's avatar
Fatih Acet committed
25 26 27
    Issues: {
      template: '<li><small>${id}</small> ${title}</li>'
    },
28
    // Milestones
Fatih Acet's avatar
Fatih Acet committed
29 30 31 32 33 34 35 36
    Milestones: {
      template: '<li>${title}</li>'
    },
    Loading: {
      template: '<li><i class="fa fa-refresh fa-spin"></i> Loading...</li>'
    },
    DefaultOptions: {
      sorter: function(query, items, searchKey) {
Yann Gravrand's avatar
Yann Gravrand committed
37
        // Highlight first item only if at least one char was typed
38
        this.setting.highlightFirst = this.setting.alwaysHighlightFirst || query.length > 0;
Fatih Acet's avatar
Fatih Acet committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        if ((items[0].name != null) && items[0].name === 'loading') {
          return items;
        }
        return $.fn.atwho["default"].callbacks.sorter(query, items, searchKey);
      },
      filter: function(query, data, searchKey) {
        if (data[0] === 'loading') {
          return data;
        }
        return $.fn.atwho["default"].callbacks.filter(query, data, searchKey);
      },
      beforeInsert: function(value) {
        if (!GitLab.GfmAutoComplete.dataLoaded) {
          return this.at;
        } else {
          return value;
        }
      }
    },
58
    setup: _.debounce(function(input) {
59
      // Add GFM auto-completion to all input fields, that accept GFM input.
60
      this.input = input || $('.js-gfm-input');
61
      // destroy previous instances
Fatih Acet's avatar
Fatih Acet committed
62
      this.destroyAtWho();
63
      // set up instances
Fatih Acet's avatar
Fatih Acet committed
64
      this.setupAtWho();
65 66 67 68 69 70 71 72 73 74 75 76

      if (this.dataSource && !this.dataLoading && !this.cachedData) {
        this.dataLoading = true;
        return this.fetchData(this.dataSource)
          .done((data) => {
            this.dataLoading = false;
            this.loadData(data);
          });
        };

      if (this.cachedData != null) {
        return this.loadData(this.cachedData);
Fatih Acet's avatar
Fatih Acet committed
77
      }
78
    }, 1000),
Fatih Acet's avatar
Fatih Acet committed
79
    setupAtWho: function() {
80
      // Emoji
Fatih Acet's avatar
Fatih Acet committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
      this.input.atwho({
        at: ':',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.path != null) {
              return _this.Emoji.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: ':${name}:',
        data: ['loading'],
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert
        }
      });
100
      // Team Members
Fatih Acet's avatar
Fatih Acet committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114
      this.input.atwho({
        at: '@',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.username != null) {
              return _this.Members.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: '${atwho-at}${username}',
        searchKey: 'search',
        data: ['loading'],
115
        alwaysHighlightFirst: true,
Fatih Acet's avatar
Fatih Acet committed
116 117 118 119 120 121
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(members) {
            return $.map(members, function(m) {
122
              let title = '';
Fatih Acet's avatar
Fatih Acet committed
123 124 125 126 127 128 129
              if (m.username == null) {
                return m;
              }
              title = m.name;
              if (m.count) {
                title += " (" + m.count + ")";
              }
130 131 132 133 134

              const autoCompleteAvatar = m.avatar_url || m.username.charAt(0).toUpperCase();
              const imgAvatar = `<img src="${m.avatar_url}" alt="${m.username}" class="avatar avatar-inline center s26"/>`;
              const txtAvatar = `<div class="avatar center avatar-inline s26">${autoCompleteAvatar}</div>`;

Fatih Acet's avatar
Fatih Acet committed
135 136
              return {
                username: m.username,
137
                avatarTag: autoCompleteAvatar.length === 1 ?  txtAvatar : imgAvatar,
138 139
                title: gl.utils.sanitize(title),
                search: gl.utils.sanitize(m.username + " " + m.name)
Fatih Acet's avatar
Fatih Acet committed
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 168 169 170
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '#',
        alias: 'issues',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Issues.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        data: ['loading'],
        insertTpl: '${atwho-at}${id}',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(issues) {
            return $.map(issues, function(i) {
              if (i.title == null) {
                return i;
              }
              return {
                id: i.iid,
171
                title: gl.utils.sanitize(i.title),
Fatih Acet's avatar
Fatih Acet committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                search: i.iid + " " + i.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '%',
        alias: 'milestones',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Milestones.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        insertTpl: '${atwho-at}"${title}"',
        data: ['loading'],
        callbacks: {
Yann Gravrand's avatar
Yann Gravrand committed
194
          sorter: this.DefaultOptions.sorter,
Fatih Acet's avatar
Fatih Acet committed
195 196 197 198 199 200 201
          beforeSave: function(milestones) {
            return $.map(milestones, function(m) {
              if (m.title == null) {
                return m;
              }
              return {
                id: m.iid,
202
                title: gl.utils.sanitize(m.title),
Fatih Acet's avatar
Fatih Acet committed
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
                search: "" + m.title
              };
            });
          }
        }
      });
      this.input.atwho({
        at: '!',
        alias: 'mergerequests',
        searchKey: 'search',
        displayTpl: (function(_this) {
          return function(value) {
            if (value.title != null) {
              return _this.Issues.template;
            } else {
              return _this.Loading.template;
            }
          };
        })(this),
        data: ['loading'],
        insertTpl: '${atwho-at}${id}',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
          beforeInsert: this.DefaultOptions.beforeInsert,
          beforeSave: function(merges) {
            return $.map(merges, function(m) {
              if (m.title == null) {
                return m;
              }
              return {
                id: m.iid,
235
                title: gl.utils.sanitize(m.title),
Fatih Acet's avatar
Fatih Acet committed
236 237 238 239 240 241
                search: m.iid + " " + m.title
              };
            });
          }
        }
      });
242
      this.input.atwho({
Fatih Acet's avatar
Fatih Acet committed
243 244 245 246 247 248
        at: '~',
        alias: 'labels',
        searchKey: 'search',
        displayTpl: this.Labels.template,
        insertTpl: '${atwho-at}${title}',
        callbacks: {
Yann Gravrand's avatar
Yann Gravrand committed
249
          sorter: this.DefaultOptions.sorter,
Fatih Acet's avatar
Fatih Acet committed
250 251 252 253
          beforeSave: function(merges) {
            var sanitizeLabelTitle;
            sanitizeLabelTitle = function(title) {
              if (/[\w\?&]+\s+[\w\?&]+/g.test(title)) {
254
                return "\"" + (gl.utils.sanitize(title)) + "\"";
Fatih Acet's avatar
Fatih Acet committed
255
              } else {
256
                return gl.utils.sanitize(title);
Fatih Acet's avatar
Fatih Acet committed
257 258 259 260 261 262 263 264 265 266 267 268
              }
            };
            return $.map(merges, function(m) {
              return {
                title: sanitizeLabelTitle(m.title),
                color: m.color,
                search: "" + m.title
              };
            });
          }
        }
      });
269 270
      // We don't instantiate the slash commands autocomplete for note and issue/MR edit forms
      this.input.filter('[data-supports-slash-commands="true"]').atwho({
271 272
        at: '/',
        alias: 'commands',
273
        searchKey: 'search',
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        displayTpl: function(value) {
          var tpl = '<li>/${name}';
          if (value.aliases.length > 0) {
            tpl += ' <small>(or /<%- aliases.join(", /") %>)</small>';
          }
          if (value.params.length > 0) {
            tpl += ' <small><%- params.join(" ") %></small>';
          }
          if (value.description !== '') {
            tpl += '<small class="description"><i><%- description %></i></small>';
          }
          tpl += '</li>';
          return _.template(tpl)(value);
        },
        insertTpl: function(value) {
289
          var tpl = "/${name} ";
290 291 292 293 294 295 296 297 298 299 300 301 302
          var reference_prefix = null;
          if (value.params.length > 0) {
            reference_prefix = value.params[0][0];
            if (/^[@%~]/.test(reference_prefix)) {
              tpl += '<%- reference_prefix %>';
            }
          }
          return _.template(tpl)({ reference_prefix: reference_prefix });
        },
        suffix: '',
        callbacks: {
          sorter: this.DefaultOptions.sorter,
          filter: this.DefaultOptions.filter,
303
          beforeInsert: this.DefaultOptions.beforeInsert,
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
          beforeSave: function(commands) {
            return $.map(commands, function(c) {
              var search = c.name;
              if (c.aliases.length > 0) {
                search = search + " " + c.aliases.join(" ");
              }
              return {
                name: c.name,
                aliases: c.aliases,
                params: c.params,
                description: c.description,
                search: search
              };
            });
          },
319 320 321 322 323 324 325 326 327
          matcher: function(flag, subtext, should_startWithSpace, acceptSpaceBar) {
            var regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi
            var match = regexp.exec(subtext);
            if (match) {
              return match[1];
            } else {
              return null;
            }
          }
328 329
        }
      });
330
      return;
Fatih Acet's avatar
Fatih Acet committed
331 332 333 334 335 336 337 338 339 340
    },
    destroyAtWho: function() {
      return this.input.atwho('destroy');
    },
    fetchData: function(dataSource) {
      return $.getJSON(dataSource);
    },
    loadData: function(data) {
      this.cachedData = data;
      this.dataLoaded = true;
341
      // load members
Fatih Acet's avatar
Fatih Acet committed
342
      this.input.atwho('load', '@', data.members);
343
      // load issues
Fatih Acet's avatar
Fatih Acet committed
344
      this.input.atwho('load', 'issues', data.issues);
345
      // load milestones
Fatih Acet's avatar
Fatih Acet committed
346
      this.input.atwho('load', 'milestones', data.milestones);
347
      // load merge requests
Fatih Acet's avatar
Fatih Acet committed
348
      this.input.atwho('load', 'mergerequests', data.mergerequests);
349
      // load emojis
Fatih Acet's avatar
Fatih Acet committed
350
      this.input.atwho('load', ':', data.emojis);
351
      // load labels
Fatih Acet's avatar
Fatih Acet committed
352
      this.input.atwho('load', '~', data.labels);
353
      // load commands
354
      this.input.atwho('load', '/', data.commands);
355 356
      // This trigger at.js again
      // otherwise we would be stuck with loading until the user types
Fatih Acet's avatar
Fatih Acet committed
357 358 359 360 361
      return $(':focus').trigger('keyup');
    }
  };

}).call(this);