BigW Consortium Gitlab

gfm_auto_complete.js 13.5 KB
Newer Older
1 2 3
import emojiMap from 'emojis/digests.json';
import emojiAliases from 'emojis/aliases.json';
import { glEmojiTag } from '~/behaviors/gl_emoji';
4
import glRegexp from '~/lib/utils/regexp';
5

6 7 8
function sanitize(str) {
  return str.replace(/<(?:.|\n)*?>/gm, '');
}
9

10 11 12 13 14 15
class GfmAutoComplete {
  constructor(dataSources) {
    this.dataSources = dataSources || {};
    this.cachedData = {};
    this.isLoadingData = {};
  }
16

17
  setup(input, enableMap = {
18 19 20 21 22
    emojis: true,
    members: true,
    issues: true,
    milestones: true,
    mergeRequests: true,
23
    labels: true,
24
  }) {
25 26
    // Add GFM auto-completion to all input fields, that accept GFM input.
    this.input = input || $('.js-gfm-input');
27
    this.enableMap = enableMap;
28
    this.setupLifecycle();
29 30
  }

31 32 33 34 35 36 37 38
  setupLifecycle() {
    this.input.each((i, input) => {
      const $input = $(input);
      $input.off('focus.setupAtWho').on('focus.setupAtWho', this.setupAtWho.bind(this, $input));
      // This triggers at.js again
      // Needed for slash commands with suffixes (ex: /label ~)
      $input.on('inserted-commands.atwho', $input.trigger.bind($input, 'keyup'));
    });
39
  }
40

41
  setupAtWho($input) {
42 43 44 45 46 47 48 49 50 51 52 53 54
    if (this.enableMap.emojis) this.setupEmoji($input);
    if (this.enableMap.members) this.setupMembers($input);
    if (this.enableMap.issues) this.setupIssues($input);
    if (this.enableMap.milestones) this.setupMilestones($input);
    if (this.enableMap.mergeRequests) this.setupMergeRequests($input);
    if (this.enableMap.labels) this.setupLabels($input);

    // We don't instantiate the slash commands autocomplete for note and issue/MR edit forms
    $input.filter('[data-supports-slash-commands="true"]').atwho({
      at: '/',
      alias: 'commands',
      searchKey: 'search',
      skipSpecialCharacterTest: true,
55 56 57 58 59
      data: GfmAutoComplete.defaultLoadingData,
      displayTpl(value) {
        if (GfmAutoComplete.isLoading(value)) return GfmAutoComplete.Loading.template;
        // eslint-disable-next-line no-template-curly-in-string
        let tpl = '<li>/${name}';
60 61 62 63 64 65 66 67 68 69 70
        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);
71 72 73 74 75
      },
      insertTpl(value) {
        // eslint-disable-next-line no-template-curly-in-string
        let tpl = '/${name} ';
        let referencePrefix = null;
76
        if (value.params.length > 0) {
77 78 79
          referencePrefix = value.params[0][0];
          if (/^[@%~]/.test(referencePrefix)) {
            tpl += '<%- referencePrefix %>';
80 81
          }
        }
82
        return _.template(tpl)({ referencePrefix });
83 84 85
      },
      suffix: '',
      callbacks: {
86 87 88 89 90
        ...this.getDefaultCallbacks(),
        beforeSave(commands) {
          if (GfmAutoComplete.isLoading(commands)) return commands;
          return $.map(commands, (c) => {
            let search = c.name;
91
            if (c.aliases.length > 0) {
92
              search = `${search} ${c.aliases.join(' ')}`;
93 94 95 96 97 98
            }
            return {
              name: c.name,
              aliases: c.aliases,
              params: c.params,
              description: c.description,
99
              search,
100 101 102
            };
          });
        },
103 104 105
        matcher(flag, subtext) {
          const regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi;
          const match = regexp.exec(subtext);
106 107 108
          if (match) {
            return match[1];
          }
109 110 111
          return null;
        },
      },
112
    });
113
  }
114 115

  setupEmoji($input) {
116 117 118
    // Emoji
    $input.atwho({
      at: ':',
119 120 121 122 123 124 125 126
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value && value.name) {
          tmpl = GfmAutoComplete.Emoji.templateFunction(value.name);
        }
        return tmpl;
      },
      // eslint-disable-next-line no-template-curly-in-string
127 128
      insertTpl: ':${name}:',
      skipSpecialCharacterTest: true,
129
      data: GfmAutoComplete.defaultLoadingData,
130
      callbacks: {
131 132
        ...this.getDefaultCallbacks(),
        matcher(flag, subtext) {
133 134 135 136 137
          const relevantText = subtext.trim().split(/\s/).pop();
          const regexp = new RegExp(`(?:[^${glRegexp.unicodeLetters}0-9:]|\n|^):([^:]*)$`, 'gi');
          const match = regexp.exec(relevantText);

          return match && match.length ? match[1] : null;
138 139
        },
      },
140
    });
141
  }
142 143

  setupMembers($input) {
144 145 146
    // Team Members
    $input.atwho({
      at: '@',
147 148 149 150 151 152 153 154
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.username != null) {
          tmpl = GfmAutoComplete.Members.template;
        }
        return tmpl;
      },
      // eslint-disable-next-line no-template-curly-in-string
155 156 157 158
      insertTpl: '${atwho-at}${username}',
      searchKey: 'search',
      alwaysHighlightFirst: true,
      skipSpecialCharacterTest: true,
159
      data: GfmAutoComplete.defaultLoadingData,
160
      callbacks: {
161 162 163
        ...this.getDefaultCallbacks(),
        beforeSave(members) {
          return $.map(members, (m) => {
164 165 166 167 168 169
            let title = '';
            if (m.username == null) {
              return m;
            }
            title = m.name;
            if (m.count) {
170
              title += ` (${m.count})`;
171
            }
172

173 174 175
            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>`;
176

177 178 179 180
            return {
              username: m.username,
              avatarTag: autoCompleteAvatar.length === 1 ? txtAvatar : imgAvatar,
              title: sanitize(title),
181
              search: sanitize(`${m.username} ${m.name}`),
182 183
            };
          });
184 185
        },
      },
186
    });
187
  }
188 189

  setupIssues($input) {
190 191 192 193
    $input.atwho({
      at: '#',
      alias: 'issues',
      searchKey: 'search',
194 195 196 197 198 199 200 201 202
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Issues.template;
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      // eslint-disable-next-line no-template-curly-in-string
203 204
      insertTpl: '${atwho-at}${id}',
      callbacks: {
205 206 207
        ...this.getDefaultCallbacks(),
        beforeSave(issues) {
          return $.map(issues, (i) => {
208 209 210 211 212 213
            if (i.title == null) {
              return i;
            }
            return {
              id: i.iid,
              title: sanitize(i.title),
214
              search: `${i.iid} ${i.title}`,
215 216
            };
          });
217 218
        },
      },
219
    });
220
  }
221 222

  setupMilestones($input) {
223 224 225 226
    $input.atwho({
      at: '%',
      alias: 'milestones',
      searchKey: 'search',
227
      // eslint-disable-next-line no-template-curly-in-string
228
      insertTpl: '${atwho-at}${title}',
229 230 231 232 233 234 235 236
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Milestones.template;
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
237
      callbacks: {
238 239 240
        ...this.getDefaultCallbacks(),
        beforeSave(milestones) {
          return $.map(milestones, (m) => {
241 242 243 244 245 246
            if (m.title == null) {
              return m;
            }
            return {
              id: m.iid,
              title: sanitize(m.title),
247
              search: m.title,
248 249
            };
          });
250 251
        },
      },
252
    });
253
  }
254 255

  setupMergeRequests($input) {
256 257 258 259
    $input.atwho({
      at: '!',
      alias: 'mergerequests',
      searchKey: 'search',
260 261 262 263 264 265 266 267 268
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Issues.template;
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      // eslint-disable-next-line no-template-curly-in-string
269 270
      insertTpl: '${atwho-at}${id}',
      callbacks: {
271 272 273
        ...this.getDefaultCallbacks(),
        beforeSave(merges) {
          return $.map(merges, (m) => {
274 275 276 277 278 279
            if (m.title == null) {
              return m;
            }
            return {
              id: m.iid,
              title: sanitize(m.title),
280
              search: `${m.iid} ${m.title}`,
281 282
            };
          });
283 284
        },
      },
285
    });
286
  }
287 288

  setupLabels($input) {
289 290 291 292
    $input.atwho({
      at: '~',
      alias: 'labels',
      searchKey: 'search',
293 294 295 296 297 298 299 300 301
      data: GfmAutoComplete.defaultLoadingData,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Labels.template;
        if (GfmAutoComplete.isLoading(value)) {
          tmpl = GfmAutoComplete.Loading.template;
        }
        return tmpl;
      },
      // eslint-disable-next-line no-template-curly-in-string
302 303
      insertTpl: '${atwho-at}${title}',
      callbacks: {
304 305 306 307 308 309 310 311 312 313
        ...this.getDefaultCallbacks(),
        beforeSave(merges) {
          if (GfmAutoComplete.isLoading(merges)) return merges;
          return $.map(merges, m => ({
            title: sanitize(m.title),
            color: m.color,
            search: m.title,
          }));
        },
      },
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 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
  getDefaultCallbacks() {
    const fetchData = this.fetchData.bind(this);

    return {
      sorter(query, items, searchKey) {
        this.setting.highlightFirst = this.setting.alwaysHighlightFirst || query.length > 0;
        if (GfmAutoComplete.isLoading(items)) {
          this.setting.highlightFirst = false;
          return items;
        }
        return $.fn.atwho.default.callbacks.sorter(query, items, searchKey);
      },
      filter(query, data, searchKey) {
        if (GfmAutoComplete.isLoading(data)) {
          fetchData(this.$inputor, this.at);
          return data;
        }
        return $.fn.atwho.default.callbacks.filter(query, data, searchKey);
      },
      beforeInsert(value) {
        let resultantValue = value;
        if (value && !this.setting.skipSpecialCharacterTest) {
          const withoutAt = value.substring(1);
          if (withoutAt && /[^\w\d]/.test(withoutAt)) {
            resultantValue = `${value.charAt()}"${withoutAt}"`;
          }
        }
        return resultantValue;
      },
      matcher(flag, subtext) {
        // The below is taken from At.js source
        // Tweaked to commands to start without a space only if char before is a non-word character
        // https://github.com/ichord/At.js
        const atSymbolsWithBar = Object.keys(this.app.controllers).join('|');
        const atSymbolsWithoutBar = Object.keys(this.app.controllers).join('');
        const targetSubtext = subtext.split(/\s+/g).pop();
        const resultantFlag = flag.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');

        const accentAChar = decodeURI('%C3%80');
        const accentYChar = decodeURI('%C3%BF');

        const regexp = new RegExp(`^(?:\\B|[^a-zA-Z0-9_${atSymbolsWithoutBar}]|\\s)${resultantFlag}(?!${atSymbolsWithBar})((?:[A-Za-z${accentAChar}-${accentYChar}0-9_'.+-]|[^\\x00-\\x7a])*)$`, 'gi');

        const match = regexp.exec(targetSubtext);

        if (match) {
          return match[1];
        }
        return null;
      },
    };
  }

  fetchData($input, at) {
371 372 373 374
    if (this.isLoadingData[at]) return;
    this.isLoadingData[at] = true;
    if (this.cachedData[at]) {
      this.loadData($input, at, this.cachedData[at]);
375
    } else if (GfmAutoComplete.atTypeMap[at] === 'emojis') {
376 377
      this.loadData($input, at, Object.keys(emojiMap).concat(Object.keys(emojiAliases)));
    } else {
378
      $.getJSON(this.dataSources[GfmAutoComplete.atTypeMap[at]], (data) => {
379 380 381
        this.loadData($input, at, data);
      }).fail(() => { this.isLoadingData[at] = false; });
    }
382 383
  }
  loadData($input, at, data) {
384 385 386 387 388 389
    this.isLoadingData[at] = false;
    this.cachedData[at] = data;
    $input.atwho('load', at, data);
    // This trigger at.js again
    // otherwise we would be stuck with loading until the user types
    return $input.trigger('keyup');
390 391 392 393
  }

  static isLoading(data) {
    let dataToInspect = data;
394 395
    if (data && data.length > 0) {
      dataToInspect = data[0];
396
    }
397

398
    const loadingState = GfmAutoComplete.defaultLoadingData[0];
399 400 401
    return dataToInspect &&
      (dataToInspect === loadingState || dataToInspect.name === loadingState);
  }
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
}

GfmAutoComplete.defaultLoadingData = ['loading'];

GfmAutoComplete.atTypeMap = {
  ':': 'emojis',
  '@': 'members',
  '#': 'issues',
  '!': 'mergeRequests',
  '~': 'labels',
  '%': 'milestones',
  '/': 'commands',
};

// Emoji
GfmAutoComplete.Emoji = {
  templateFunction(name) {
    return `<li>
      ${name} ${glEmojiTag(name)}
    </li>
    `;
  },
424
};
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
// Team Members
GfmAutoComplete.Members = {
  // eslint-disable-next-line no-template-curly-in-string
  template: '<li>${avatarTag} ${username} <small>${title}</small></li>',
};
GfmAutoComplete.Labels = {
  // eslint-disable-next-line no-template-curly-in-string
  template: '<li><span class="dropdown-label-box" style="background: ${color}"></span> ${title}</li>',
};
// Issues and MergeRequests
GfmAutoComplete.Issues = {
  // eslint-disable-next-line no-template-curly-in-string
  template: '<li><small>${id}</small> ${title}</li>',
};
// Milestones
GfmAutoComplete.Milestones = {
  // eslint-disable-next-line no-template-curly-in-string
  template: '<li>${title}</li>',
};
GfmAutoComplete.Loading = {
  template: '<li style="pointer-events: none;"><i class="fa fa-spinner fa-spin"></i> Loading...</li>',
};

export default GfmAutoComplete;