All files / app/assets/javascripts gfm_auto_complete.js

66.66% Statements 316/474
52.46% Branches 149/284
75.86% Functions 88/116
66.51% Lines 294/442

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 93 94 95 96 97 98 99 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 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 168 169 170 171 172 173 174 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 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 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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 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 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183                                130x 130x 130x 130x 130x 130x 130x 130x   130x 130x   130x 130x 130x 130x   130x                                   190x 190x   190x 7x 7x     190x       44x 9x   44x               4x       6x 6x   6x 6x 2x   4x 4x 2x     4x   4x 4x 4x 4x       4x                     130x     80x 77x   3x 3x 3x     130x                                 575x 575x 575x 575x         573x 573x 573x       573x 534x 534x   534x 534x     534x 534x 534x           36x 36x 36x 36x 36x 36x 36x 36x 36x   36x                   1x   1x                                                                                                                           3x 1x 1x 1x                             2x 2x 2x 1x   1x               1x                             1x             3x   3x           11x     11x                                                                                     11x       1x 1x 1x               1x 1x 1x     1x                                                                                                                                                                                                         1x       1x                                   1x 1x 1x                       1x       1x                                   1x 1x 1x                               1x                           1x       1x       1x                                   1x 1x 1x                       1x       16x 16x 16x           16x   16x             64x 64x     64x               31x 80x               30x     30x 30x 24x   6x           30x 30x 30x       30x       30x 30x 20x       10x 10x     30x 15x 15x     15x           15x   32x   9x   16x     6x       16x       1x                                   1x 1x 1x                     1x       1x                                                 1x 1x 1x                   1x       7x 7x   7x             10x 10x 10x   10x               13x 29x 7x   22x                       12x   12x 12x 12x         12x 12x     12x 6x 6x     6x       6x   11x   3x   11x             7x       86x   86x   19x 19x 1x 1x   18x     14x 8x 6x 6x 6x       8x 5x 5x     3x     13x 13x   13x 13x 13x 10x           13x 13x           13x     416x   416x 332x   84x             30x   29x 29x   29x 4x 1x   3x     1x     3x     25x 23x 2x   2x 2x   1x 1x   1x     2x               25x   25x             25x     25x     24x       2x   2x   2x               481x 480x 480x         182x 182x 92x     182x 182x             438x           438x 438x 438x   438x 438x     438x         438x       130x   130x   130x                               130x   130x       130x 43x     130x 130x   1x     1x       1x 1x       1x                                     130x   4x           26x       17x         1x 1x   1x 9x 7x       130x   65x           130x     2x     5x       130x   1x         1x     130x   11x     130x   2x   2x 2x       130x         130x          
import $ from 'jquery';
import '~/lib/utils/jquery_at_who';
import { escape as lodashEscape, sortBy, template, escapeRegExp } from 'lodash';
import * as Emoji from '~/emoji';
import axios from '~/lib/utils/axios_utils';
import { DEFAULT_DEBOUNCE_AND_THROTTLE_MS } from '~/lib/utils/constants';
import { loadingIconForLegacyJS } from '~/loading_icon_for_legacy_js';
import { s__, __, sprintf } from '~/locale';
import { isUserBusy } from '~/set_status_modal/utils';
import SidebarMediator from '~/sidebar/sidebar_mediator';
import { state } from '~/sidebar/components/reviewers/sidebar_reviewers.vue';
import AjaxCache from './lib/utils/ajax_cache';
import { spriteIcon } from './lib/utils/common_utils';
import { parsePikadayDate } from './lib/utils/datetime_utility';
import { unicodeLetters } from './lib/utils/regexp';
 
const USERS_ALIAS = 'users';
const ISSUES_ALIAS = 'issues';
const MILESTONES_ALIAS = 'milestones';
const MERGEREQUESTS_ALIAS = 'mergerequests';
const LABELS_ALIAS = 'labels';
const SNIPPETS_ALIAS = 'snippets';
const CONTACTS_ALIAS = 'contacts';
const WIKIS_ALIAS = 'wikis';
 
const CADENCE_REFERENCE_PREFIX = '[cadence:';
const ITERATION_REFERENCE_PREFIX = '*iteration:';
 
export const AT_WHO_ACTIVE_CLASS = 'at-who-active';
export const CONTACT_STATE_ACTIVE = 'active';
export const CONTACTS_ADD_COMMAND = '/add_contacts';
export const CONTACTS_REMOVE_COMMAND = '/remove_contacts';
 
const useMentionsBackendFiltering = window.gon.features?.mentionAutocompleteBackendFiltering;
 
/**
 * Escapes user input before we pass it to at.js, which
 * renders it as HTML in the autocomplete dropdown.
 *
 * at.js allows you to reference data using `${}` syntax
 * (e.g. ${search}) which it replaces with the actual data
 * before rendering it in the autocomplete dropdown.
 * To prevent user input from executing this `${}` syntax,
 * we also need to escape the $ character.
 *
 * @param string user input
 * @return {string} escaped user input
 */
export function escape(string) {
  // To prevent double (or multiple) enconding attack
  // Decode the user input repeatedly prior to escaping the final decoded string.
  let encodedString = string;
  let decodedString = decodeURIComponent(encodedString);
 
  while (decodedString !== encodedString) {
    encodedString = decodeURIComponent(decodedString);
    decodedString = decodeURIComponent(encodedString);
  }
 
  return lodashEscape(decodedString.replace(/\$/g, '$'));
}
 
export function showAndHideHelper($input, alias = '') {
  $input.on(`hidden${alias ? '-' : ''}${alias}.atwho`, () => {
    $input.removeClass(AT_WHO_ACTIVE_CLASS);
  });
  $input.on(`shown${alias ? '-' : ''}${alias}.atwho`, () => {
    $input.addClass(AT_WHO_ACTIVE_CLASS);
  });
}
 
// This should be kept in sync with the backend filtering in
// `User#gfm_autocomplete_search` and `Namespace#gfm_autocomplete_search`
function createMemberSearchString(member) {
  return `${member.name.replace(/ /g, '')} ${member.username}`;
}
 
export function membersBeforeSave(members) {
  return members.map((member) => {
    const GROUP_TYPE = 'Group';
 
    let title = '';
    if (member.username == null) {
      return member;
    }
    title = member.name;
    if (member.count && !member.mentionsDisabled) {
      title += ` (${member.count})`;
    }
 
    const autoCompleteAvatar = member.avatar_url || member.username.charAt(0).toUpperCase();
 
    const rectAvatarClass = member.type === GROUP_TYPE ? 'rect-avatar' : '';
    const imgAvatar = `<img src="${member.avatar_url}" alt="${member.username}" class="avatar ${rectAvatarClass} avatar-inline s24 gl-mr-2"/>`;
    const txtAvatar = `<div class="avatar ${rectAvatarClass} avatar-inline s24 gl-mr-2">${autoCompleteAvatar}</div>`;
    const avatarIcon = member.mentionsDisabled
      ? spriteIcon('notifications-off', 's16 vertical-align-middle gl-ml-2')
      : '';
 
    return {
      username: member.username,
      avatarTag: autoCompleteAvatar.length === 1 ? txtAvatar : imgAvatar,
      title,
      search: createMemberSearchString(member),
      icon: avatarIcon,
      availability: member?.availability,
    };
  });
}
 
export const highlighter = (li, query) => {
  // override default behaviour to escape dot character
  // see https://github.com/ichord/At.js/pull/576
  if (!query) {
    return li;
  }
  const escapedQuery = escapeRegExp(query);
  const regexp = new RegExp(`>\\s*([^<]*?)(${escapedQuery})([^<]*)\\s*<`, 'ig');
  return li.replace(regexp, (str, $1, $2, $3) => `> ${$1}<strong>${$2}</strong>${$3} <`);
};
 
export const defaultAutocompleteConfig = {
  emojis: true,
  members: true,
  issues: true,
  mergeRequests: true,
  epics: true,
  iterations: true,
  milestones: true,
  labels: true,
  snippets: true,
  vulnerabilities: true,
  contacts: true,
  wikis: true,
};
 
class GfmAutoComplete {
  constructor(dataSources = {}) {
    this.dataSources = dataSources;
    this.cachedData = {};
    this.isLoadingData = {};
    this.previousQuery = undefined;
  }
 
  setup(input, enableMap = defaultAutocompleteConfig) {
    // Add GFM auto-completion to all input fields, that accept GFM input.
    this.input = input || $('.js-gfm-input');
    this.enableMap = enableMap;
    this.setupLifecycle();
  }
 
  setupLifecycle() {
    this.input.each((i, input) => {
      const $input = $(input);
      Eif (!$input.hasClass('js-gfm-input-initialized')) {
        // eslint-disable-next-line @gitlab/no-global-event-off
        $input.off('focus.setupAtWho').on('focus.setupAtWho', this.setupAtWho.bind(this, $input));
        $input.on('change.atwho', () => input.dispatchEvent(new Event('input')));
        // This triggers at.js again
        // Needed for quick actions with suffixes (ex: /label ~)
        $input.on('inserted-commands.atwho', $input.trigger.bind($input, 'keyup'));
        $input.on('clear-commands-cache.atwho', () => this.clearCache());
        $input.addClass('js-gfm-input-initialized');
      }
    });
  }
 
  setupAtWho($input) {
    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);
    if (this.enableMap.snippets) this.setupSnippets($input);
    if (this.enableMap.contacts) this.setupContacts($input);
    if (this.enableMap.wikis) this.setupWikis($input);
 
    $input.filter('[data-supports-quick-actions="true"]').atwho({
      at: '/',
      alias: 'commands',
      searchKey: 'search',
      limit: 100,
      skipSpecialCharacterTest: true,
      skipMarkdownCharacterTest: true,
      data: GfmAutoComplete.defaultLoadingData,
      maxLen: 100,
      displayTpl(value) {
        const cssClasses = [];
 
        Eif (GfmAutoComplete.isLoading(value)) return GfmAutoComplete.Loading.template;
        // eslint-disable-next-line no-template-curly-in-string
        let tpl = '<li class="<%- className %>"><span class="name">/${name}</span>';
        if (value.aliases.length > 0) {
          tpl += ' <small class="aliases">(or /<%- aliases.join(", /") %>)</small>';
        }
        if (value.params.length > 0) {
          tpl += ' <small class="params"><%- params.join(" ") %></small>';
        }
        if (value.warning && value.icon && value.icon === 'confidential') {
          tpl += `<small class="description gl-display-flex gl-align-items-center">${spriteIcon(
            'eye-slash',
            's16 gl-mr-2',
          )}<em><%- warning %></em></small>`;
        } else if (value.warning) {
          tpl += '<small class="description"><em><%- warning %></em></small>';
        } else if (value.description !== '') {
          tpl += '<small class="description"><em><%- description %></em></small>';
        }
        tpl += '</li>';
 
        if (value.warning) {
          cssClasses.push('has-warning');
        }
 
        return template(tpl)({
          ...value,
          className: cssClasses.join(' '),
        });
      },
      insertTpl(value) {
        // eslint-disable-next-line no-template-curly-in-string
        let tpl = '/${name} ';
        let referencePrefix = null;
        if (value.params.length > 0) {
          const regexp = /^<\[[a-z]+:/;
          const match = regexp.exec(value.params);
          if (match) {
            [referencePrefix] = match;
 
            // EE-ONLY; iteration quick action should autocomplete iteration reference only
            if (referencePrefix === CADENCE_REFERENCE_PREFIX)
              referencePrefix = ITERATION_REFERENCE_PREFIX;
 
            tpl += '<%- referencePrefix %>';
          } else {
            [[referencePrefix]] = value.params;
            if (/^[@%~]/.test(referencePrefix)) {
              tpl += '<%- referencePrefix %>';
            } else if (/^[*]/.test(referencePrefix)) {
              // EE-ONLY
              referencePrefix = ITERATION_REFERENCE_PREFIX;
              tpl += '<%- referencePrefix %>';
            }
          }
        }
        return template(tpl, { interpolate: /<%=([\s\S]+?)%>/g })({ referencePrefix });
      },
      suffix: '',
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(commands) {
          if (GfmAutoComplete.isLoading(commands)) return commands;
          return $.map(commands, (c) => {
            let 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,
              warning: c.warning,
              icon: c.icon,
              search,
            };
          });
        },
        matcher(flag, subtext) {
          const regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi;
          const match = regexp.exec(subtext);
          if (match) {
            return match[1];
          }
          return null;
        },
      },
    });
  }
 
  // eslint-disable-next-line class-methods-use-this
  setSubmitReviewStates($input) {
    const REVIEW_STATES = {
      reviewed: {
        header: __('Comment'),
        description: __('Submit general feedback without explicit approval.'),
      },
      approve: {
        header: __('Approve'),
        description: __('Submit feedback and approve these changes.'),
      },
      requested_changes: {
        header: __('Request changes'),
        description: __('Submit feedback that should be addressed before merging.'),
      },
    };
 
    $input.filter('[data-supports-quick-actions="true"]').atwho({
      // Always keep the trailing space otherwise the command won't display correctly
      at: '/submit_review ',
      alias: 'submit_review',
      data: Object.keys(REVIEW_STATES),
      maxLen: 100,
      displayTpl({ name }) {
        const reviewState = REVIEW_STATES[name];
 
        return `<li><span class="name gl-font-weight-bold">${reviewState.header}</span><small class="description"><em>${reviewState.description}</em></small></li>`;
      },
    });
  }
 
  setupEmoji($input) {
    const fetchData = this.fetchData.bind(this);
 
    // Emoji
    $input.atwho({
      at: ':',
      displayTpl: GfmAutoComplete.Emoji.templateFunction,
      insertTpl: GfmAutoComplete.Emoji.insertTemplateFunction,
      skipSpecialCharacterTest: true,
      data: GfmAutoComplete.defaultLoadingData,
      maxLen: 100,
      callbacks: {
        ...this.getDefaultCallbacks(),
        matcher(flag, subtext) {
          const regexp = new RegExp(`(?:[^${unicodeLetters}0-9:]|\n|^):([^ :][^:]*)?$`, 'gi');
          const match = regexp.exec(subtext);
 
          if (match && match.length) {
            // Since we have "?" on the group, it's possible it is undefined
            return match[1] || '';
          }
 
          return null;
        },
        filter(query, items) {
          if (GfmAutoComplete.isLoading(items)) {
            fetchData(this.$inputor, this.at);
            return items;
          }
 
          return GfmAutoComplete.Emoji.filter(query);
        },
        sorter(query, items) {
          this.setting.highlightFirst = this.setting.alwaysHighlightFirst || query.length > 0;
          if (GfmAutoComplete.isLoading(items)) {
            this.setting.highlightFirst = false;
            return items;
          }
 
          if (query.length === 0) {
            return items;
          }
 
          return GfmAutoComplete.Emoji.sorter(items);
        },
      },
    });
    showAndHideHelper($input);
  }
 
  setupMembers($input) {
    const instance = this;
    const fetchData = this.fetchData.bind(this);
    const MEMBER_COMMAND = {
      ASSIGN: '/assign',
      UNASSIGN: '/unassign',
      ASSIGN_REVIEWER: '/assign_reviewer',
      UNASSIGN_REVIEWER: '/unassign_reviewer',
      REASSIGN: '/reassign',
      CC: '/cc',
    };
    let assignees = [];
    let reviewers = [];
    let command = '';
 
    // Team Members
    $input.atwho({
      at: '@',
      alias: USERS_ALIAS,
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        const { avatarTag, username, title, icon, availability } = value;
        if (username != null) {
          tmpl = GfmAutoComplete.Members.templateFunction({
            avatarTag,
            username,
            title,
            icon,
            availabilityStatus:
              availability && isUserBusy(availability)
                ? `<span class="badge badge-warning badge-pill gl-badge sm gl-ml-2"> ${s__(
                    'UserProfile|Busy',
                  )}</span>`
                : '',
          });
        }
        return tmpl;
      },
      // eslint-disable-next-line no-template-curly-in-string
      insertTpl: '${atwho-at}${username}',
      limit: 10,
      delay: useMentionsBackendFiltering ? DEFAULT_DEBOUNCE_AND_THROTTLE_MS : null,
      searchKey: 'search',
      alwaysHighlightFirst: true,
      skipSpecialCharacterTest: true,
      data: GfmAutoComplete.defaultLoadingData,
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave: membersBeforeSave,
        matcher(flag, subtext) {
          const subtextNodes = subtext.split(/\n+/g).pop().split(GfmAutoComplete.regexSubtext);
 
          // Check if @ is followed by '/assign', '/reassign', '/unassign' or '/cc' commands.
          command = subtextNodes.find((node) => {
            if (Object.values(MEMBER_COMMAND).includes(node)) {
              return node;
            }
            return null;
          });
 
          // Cache assignees & reviewers list for easier filtering later
          assignees =
            SidebarMediator.singleton?.store?.assignees?.map(createMemberSearchString) || [];
          reviewers = state.issuable?.reviewers?.nodes?.map(createMemberSearchString) || [];
 
          const match = GfmAutoComplete.defaultMatcher(flag, subtext, this.app.controllers);
          return match && match.length ? match[1] : null;
        },
        filter(query, data) {
          if (useMentionsBackendFiltering) {
            if (GfmAutoComplete.isLoading(data) || instance.previousQuery !== query) {
              instance.previousQuery = query;
 
              fetchData(this.$inputor, this.at, query);
              return data;
            }
          } else if (GfmAutoComplete.isLoading(data)) {
            fetchData(this.$inputor, this.at);
            return data;
          }
 
          if (command === MEMBER_COMMAND.ASSIGN) {
            // Only include members which are not assigned to Issuable currently
            return data.filter((member) => !assignees.includes(member.search));
          }
          if (command === MEMBER_COMMAND.UNASSIGN) {
            // Only include members which are assigned to Issuable currently
            return data.filter((member) => assignees.includes(member.search));
          }
          if (command === MEMBER_COMMAND.ASSIGN_REVIEWER) {
            // Only include members which are not assigned as a reviewer to Issuable currently
            return data.filter((member) => !reviewers.includes(member.search));
          }
          if (command === MEMBER_COMMAND.UNASSIGN_REVIEWER) {
            // Only include members which are not assigned as a reviewer to Issuable currently
            return data.filter((member) => reviewers.includes(member.search));
          }
 
          return data;
        },
        sorter(query, items) {
          // Disable auto-selecting the loading icon
          this.setting.highlightFirst = this.setting.alwaysHighlightFirst;
          if (GfmAutoComplete.isLoading(items)) {
            this.setting.highlightFirst = false;
            return items;
          }
 
          if (!query) {
            return items;
          }
 
          return GfmAutoComplete.Members.sort(query, items);
        },
      },
    });
    showAndHideHelper($input, USERS_ALIAS);
  }
 
  setupIssues($input) {
    $input.atwho({
      at: '#',
      alias: ISSUES_ALIAS,
      searchKey: 'search',
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Issues.templateFunction(value);
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      insertTpl: GfmAutoComplete.Issues.insertTemplateFunction,
      skipSpecialCharacterTest: true,
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(issues) {
          return $.map(issues, (i) => {
            Eif (i.title == null) {
              return i;
            }
            return {
              id: i.iid,
              title: i.title,
              reference: i.reference,
              search: `${i.iid} ${i.title}`,
            };
          });
        },
      },
    });
    showAndHideHelper($input, ISSUES_ALIAS);
  }
 
  setupMilestones($input) {
    $input.atwho({
      at: '%',
      alias: MILESTONES_ALIAS,
      searchKey: 'search',
      // eslint-disable-next-line no-template-curly-in-string
      insertTpl: '${atwho-at}${title}',
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Milestones.templateFunction(value.title, value.expired);
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(milestones) {
          const parsedMilestones = $.map(milestones, (m) => {
            Eif (m.title == null) {
              return m;
            }
 
            const dueDate = m.due_date ? parsePikadayDate(m.due_date) : null;
            const expired = dueDate ? Date.now() > dueDate.getTime() : false;
 
            return {
              id: m.iid,
              title: m.title,
              search: m.title,
              expired,
              dueDate,
            };
          });
 
          // Sort milestones by due date when present.
          Iif (typeof parsedMilestones[0] === 'object') {
            return parsedMilestones.sort((mA, mB) => {
              // Move all expired milestones to the bottom.
              if (mA.expired) return 1;
              if (mB.expired) return -1;
 
              // Move milestones without due dates just above expired milestones.
              if (!mA.dueDate) return 1;
              if (!mB.dueDate) return -1;
 
              // Sort by due date in ascending order.
              return mA.dueDate - mB.dueDate;
            });
          }
          return parsedMilestones;
        },
      },
    });
    showAndHideHelper($input, MILESTONES_ALIAS);
  }
 
  setupMergeRequests($input) {
    $input.atwho({
      at: '!',
      alias: MERGEREQUESTS_ALIAS,
      searchKey: 'search',
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Issues.templateFunction(value);
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      insertTpl: GfmAutoComplete.Issues.insertTemplateFunction,
      skipSpecialCharacterTest: true,
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(merges) {
          return $.map(merges, (m) => {
            Eif (m.title == null) {
              return m;
            }
            return {
              id: m.iid,
              title: m.title,
              reference: m.reference,
              search: `${m.iid} ${m.title}`,
            };
          });
        },
      },
    });
    showAndHideHelper($input, MERGEREQUESTS_ALIAS);
  }
 
  setupLabels($input) {
    const instance = this;
    const fetchData = this.fetchData.bind(this);
    const LABEL_COMMAND = {
      LABEL: '/label',
      LABELS: '/labels',
      UNLABEL: '/unlabel',
      RELABEL: '/relabel',
    };
    let command = '';
 
    $input.atwho({
      at: '~',
      alias: LABELS_ALIAS,
      searchKey: 'search',
      data: GfmAutoComplete.defaultLoadingData,
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Labels.templateFunction(value.color, value.title);
        Iif (GfmAutoComplete.isLoading(value)) {
          tmpl = GfmAutoComplete.Loading.template;
        }
        return tmpl;
      },
      // eslint-disable-next-line no-template-curly-in-string
      insertTpl: '${atwho-at}${title}',
      limit: 20,
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(merges) {
          if (GfmAutoComplete.isLoading(merges)) return merges;
          return $.map(merges, (m) => ({
            title: m.title,
            color: m.color,
            search: m.title,
            set: m.set,
          }));
        },
        matcher(flag, subtext) {
          const subtextNodes = subtext.split(/\n+/g).pop().split(GfmAutoComplete.regexSubtext);
 
          // Check if ~ is followed by '/label', '/labels', '/relabel' or '/unlabel' commands.
          command = subtextNodes.find((node) => {
            if (Object.values(LABEL_COMMAND).includes(node)) {
              return node;
            }
            return null;
          });
 
          // If any label matches the inserted text after the last `~`, suggest those labels,
          // even if any spaces or funky characters were typed.
          // This allows matching labels like "Accepting merge requests".
          const labels = instance.cachedData[flag];
          Eif (labels) {
            Iif (!subtext.includes(flag)) {
              // Do not match if there is no `~` before the cursor
              return null;
            }
            Iif (subtext.endsWith('~~')) {
              // Do not match if there are two consecutive `~` characters (strikethrough) before the cursor
              return null;
            }
            const lastCandidate = subtext.split(flag).pop();
            if (labels.find((label) => label.title.startsWith(lastCandidate))) {
              return lastCandidate;
            }
          }
 
          const match = GfmAutoComplete.defaultMatcher(flag, subtext, this.app.controllers);
          return match && match.length ? match[1] : null;
        },
        filter(query, data, searchKey) {
          if (GfmAutoComplete.isLoading(data)) {
            fetchData(this.$inputor, this.at);
            return data;
          }
 
          Iif (data === GfmAutoComplete.defaultLoadingData) {
            return $.fn.atwho.default.callbacks.filter(query, data, searchKey);
          }
 
          // The `LABEL_COMMAND.RELABEL` is intentionally skipped
          // because we want to return all the labels (unfiltered) for that command.
          if (command === LABEL_COMMAND.LABEL || command === LABEL_COMMAND.LABELS) {
            // Return labels with set: undefined.
            return data.filter((label) => !label.set);
          }
          if (command === LABEL_COMMAND.UNLABEL) {
            // Return labels with set: true.
            return data.filter((label) => label.set);
          }
 
          return data;
        },
      },
    });
    showAndHideHelper($input, LABELS_ALIAS);
  }
 
  setupSnippets($input) {
    $input.atwho({
      at: '$',
      alias: SNIPPETS_ALIAS,
      searchKey: 'search',
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Issues.templateFunction(value);
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      // eslint-disable-next-line no-template-curly-in-string
      insertTpl: '${atwho-at}${id}',
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(snippets) {
          return $.map(snippets, (m) => {
            Eif (m.title == null) {
              return m;
            }
            return {
              id: m.id,
              title: m.title,
              search: `${m.id} ${m.title}`,
            };
          });
        },
      },
    });
    showAndHideHelper($input, SNIPPETS_ALIAS);
  }
 
  setupWikis($input) {
    $input.atwho({
      at: '[[',
      suffix: ']]',
      alias: WIKIS_ALIAS,
      searchKey: 'title',
      data: GfmAutoComplete.defaultLoadingData,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        if (value.title != null) {
          tmpl = GfmAutoComplete.Wikis.templateFunction(value);
        }
        return tmpl;
      },
      // eslint-disable-next-line no-template-curly-in-string
      insertTpl: '${atwho-at}${title}|${slug}',
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeInsert(value) {
          const [title, slug] = value.substr(2).split('|');
          if (title.toLowerCase() === slug.toLowerCase()) {
            return `[[${slug}`;
          }
          return `[[${title}|${slug}`;
        },
        beforeSave(wikis) {
          return $.map(wikis, (m) => {
            Eif (m.title == null) {
              return m;
            }
            return {
              title: m.title,
              slug: m.slug,
            };
          });
        },
      },
    });
    showAndHideHelper($input, WIKIS_ALIAS);
  }
 
  setupContacts($input) {
    const fetchData = this.fetchData.bind(this);
    let command = '';
 
    $input.atwho({
      at: '[contact:',
      suffix: ']',
      alias: CONTACTS_ALIAS,
      searchKey: 'search',
      maxLen: 100,
      displayTpl(value) {
        let tmpl = GfmAutoComplete.Loading.template;
        Eif (value.email != null) {
          tmpl = GfmAutoComplete.Contacts.templateFunction(value);
        }
        return tmpl;
      },
      data: GfmAutoComplete.defaultLoadingData,
      // eslint-disable-next-line no-template-curly-in-string
      insertTpl: '${atwho-at}${email}',
      callbacks: {
        ...this.getDefaultCallbacks(),
        beforeSave(contacts) {
          return $.map(contacts, (m) => {
            if (m.email == null) {
              return m;
            }
            return {
              id: m.id,
              email: m.email,
              firstName: m.first_name,
              lastName: m.last_name,
              search: `${m.email}`,
              state: m.state,
              set: m.set,
            };
          });
        },
        matcher(flag, subtext) {
          const subtextNodes = subtext.split(/\n+/g).pop().split(GfmAutoComplete.regexSubtext);
 
          command = subtextNodes.find((node) => {
            Eif (node === CONTACTS_ADD_COMMAND || node === CONTACTS_REMOVE_COMMAND) {
              return node;
            }
            return null;
          });
 
          const match = GfmAutoComplete.defaultMatcher(flag, subtext, this.app.controllers);
          return match?.length ? match[1] : null;
        },
        filter(query, data, searchKey) {
          if (GfmAutoComplete.isLoading(data)) {
            fetchData(this.$inputor, this.at);
            return data;
          }
 
          Iif (data === GfmAutoComplete.defaultLoadingData) {
            return $.fn.atwho.default.callbacks.filter(query, data, searchKey);
          }
 
          if (command === CONTACTS_ADD_COMMAND) {
            // Return contacts that are active and not already on the issue
            return data.filter((contact) => contact.state === CONTACT_STATE_ACTIVE && !contact.set);
          }
          Eif (command === CONTACTS_REMOVE_COMMAND) {
            // Return contacts already on the issue
            return data.filter((contact) => contact.set);
          }
 
          return data;
        },
      },
    });
    showAndHideHelper($input, CONTACTS_ALIAS);
  }
 
  getDefaultCallbacks() {
    const self = 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.isTypeWithBackendFiltering(this.at)) {
          if (GfmAutoComplete.isLoading(data) || self.previousQuery !== query) {
            self.previousQuery = query;
            self.fetchData(this.$inputor, this.at, query);
            return data;
          }
        }
 
        if (GfmAutoComplete.isLoading(data)) {
          self.fetchData(this.$inputor, this.at);
          return data;
        }
 
        return $.fn.atwho.default.callbacks.filter(query, data, searchKey);
      },
      beforeInsert(value) {
        let withoutAt = value.substring(1);
        const at = value.charAt();
 
        Eif (value && !this.setting.skipSpecialCharacterTest) {
          const regex = at === '~' ? /\W|^\d+$/ : /\W/;
          if (withoutAt && regex.test(withoutAt)) {
            withoutAt = `"${withoutAt}"`;
          }
        }
 
        // We can ignore this for quick actions because they are processed
        // before Markdown.
        Eif (!this.setting.skipMarkdownCharacterTest) {
          withoutAt = withoutAt
            .replace(/(~~|`|\*)/g, '\\$1')
            .replace(/(\b)(_+)/g, '$1\\$2') // only escape underscores at the start
            .replace(/(_+)(\b)/g, '\\$1$2'); // or end of words
        }
 
        return `${at}${withoutAt}`;
      },
      matcher(flag, subtext) {
        const match = GfmAutoComplete.defaultMatcher(flag, subtext, this.app.controllers);
 
        if (match) {
          return match[1];
        }
        return null;
      },
      highlighter,
    };
  }
 
  fetchData($input, at, search) {
    if (this.isLoadingData[at]) return;
 
    this.isLoadingData[at] = true;
    const dataSource = this.dataSources[GfmAutoComplete.atTypeMap[at]];
 
    if (GfmAutoComplete.isTypeWithBackendFiltering(at)) {
      if (this.cachedData[at]?.[search]) {
        this.loadData($input, at, this.cachedData[at][search], { search });
      } else {
        axios
          .get(dataSource, { params: { search } })
          .then(({ data }) => {
            this.loadData($input, at, data, { search });
          })
          .catch(() => {
            this.isLoadingData[at] = false;
          });
      }
    } else if (this.cachedData[at]) {
      this.loadData($input, at, this.cachedData[at]);
    } else Iif (GfmAutoComplete.atTypeMap[at] === 'emojis') {
      this.loadEmojiData($input, at).catch(() => {});
    } else if (dataSource) {
      AjaxCache.retrieve(dataSource, true)
        .then((data) => {
          Eif (data.some((c) => c.name === 'submit_review')) {
            this.setSubmitReviewStates($input);
          }
          this.loadData($input, at, data);
        })
        .catch(() => {
          this.isLoadingData[at] = false;
        });
    } else E{
      this.isLoadingData[at] = false;
    }
  }
 
  loadData($input, at, data, { search } = {}) {
    this.isLoadingData[at] = false;
 
    Iif (search !== undefined) {
      if (this.cachedData[at] === undefined) {
        this.cachedData[at] = {};
      }
 
      this.cachedData[at][search] = data;
    } else {
      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');
  }
 
  async loadEmojiData($input, at) {
    await Emoji.initEmojiMap();
 
    this.loadData($input, at, ['loaded']);
 
    GfmAutoComplete.glEmojiTag = Emoji.glEmojiTag;
  }
 
  clearCache() {
    this.cachedData = {};
  }
 
  destroy() {
    this.input.each((i, input) => {
      const $input = $(input);
      $input.atwho('destroy');
    });
  }
 
  static isLoading(data) {
    let dataToInspect = data;
    if (data && data.length > 0) {
      [dataToInspect] = data;
    }
 
    const loadingState = GfmAutoComplete.defaultLoadingData[0];
    return dataToInspect && (dataToInspect === loadingState || dataToInspect.name === loadingState);
  }
 
  static defaultMatcher(flag, subtext, controllers) {
    // 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(controllers)
      .join('|')
      .replace(/[$]/, '\\$&')
      .replace(/([[\]:])/g, '\\$1')
      .replace(/([*])/g, '\\$1');
 
    const atSymbolsWithoutBar = Object.keys(controllers).join('');
    const targetSubtext = subtext.split(GfmAutoComplete.regexSubtext).pop();
    const resultantFlag = flag.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
 
    const accentAChar = decodeURI('%C3%80');
    const accentYChar = decodeURI('%C3%BF');
 
    // Holy regex, batman!
    const regexp = new RegExp(
      `^(?:\\B|[^a-zA-Z0-9_\`${atSymbolsWithoutBar}]|\\s)${resultantFlag}(?!${atSymbolsWithBar})((?:[A-Za-z${accentAChar}-${accentYChar}0-9_'.+-:]|[^\\x00-\\x7a])*)$`,
      'gi',
    );
 
    return regexp.exec(targetSubtext);
  }
}
 
GfmAutoComplete.regexSubtext = /\s+/g;
 
GfmAutoComplete.defaultLoadingData = ['loading'];
 
GfmAutoComplete.atTypeMap = {
  ':': 'emojis',
  '@': 'members',
  '#': 'issues',
  '!': 'mergeRequests',
  '&': 'epics',
  '*iteration:': 'iterations',
  '~': 'labels',
  '%': 'milestones',
  '/': 'commands',
  '[vulnerability:': 'vulnerabilities',
  $: 'snippets',
  '[contact:': 'contacts',
  '[[': 'wikis',
};
 
GfmAutoComplete.typesWithBackendFiltering = ['vulnerabilities'];
 
Iif (useMentionsBackendFiltering) {
  GfmAutoComplete.typesWithBackendFiltering.push('members');
}
 
GfmAutoComplete.isTypeWithBackendFiltering = (type) =>
  GfmAutoComplete.typesWithBackendFiltering.includes(GfmAutoComplete.atTypeMap[type]);
 
// Emoji
GfmAutoComplete.glEmojiTag = null;
GfmAutoComplete.Emoji = {
  insertTemplateFunction(value) {
    return `:${value.emoji.name}:`;
  },
  templateFunction(item) {
    Iif (GfmAutoComplete.isLoading(item)) {
      return GfmAutoComplete.Loading.template;
    }
 
    const escapedFieldValue = escape(item.fieldValue);
    Iif (!GfmAutoComplete.glEmojiTag) {
      return `<li>${escapedFieldValue}</li>`;
    }
 
    return `<li>${GfmAutoComplete.glEmojiTag(item.emoji.name)} ${escapedFieldValue}</li>`;
  },
  filter(query) {
    if (query.length === 0) {
      return Emoji.getAllEmoji()
        .map((emoji) => ({
          emoji,
          fieldValue: emoji.name,
        }))
        .slice(0, 20);
    }
 
    return Emoji.searchEmoji(query);
  },
  sorter(items) {
    return items.sort(Emoji.sortEmoji);
  },
};
// Team Members
GfmAutoComplete.Members = {
  templateFunction({ avatarTag, username, title, icon, availabilityStatus }) {
    return `<li>${avatarTag} ${username} <small>${escape(
      title,
    )}${availabilityStatus}</small> ${icon}</li>`;
  },
  nameOrUsernameStartsWith(member, query) {
    // `member.search` is a name:username string like `MargeSimpson msimpson`
    return member.search.split(' ').some((name) => name.toLowerCase().startsWith(query));
  },
  nameOrUsernameIncludes(member, query) {
    // `member.search` is a name:username string like `MargeSimpson msimpson`
    return member.search.toLowerCase().includes(query);
  },
  // This should be kept in sync with the backend sorting in
  // `User#gfm_autocomplete_search` and `Namespace#gfm_autocomplete_search`
  sort(query, members) {
    const lowercaseQuery = query.toLowerCase();
    const { nameOrUsernameStartsWith, nameOrUsernameIncludes } = GfmAutoComplete.Members;
 
    return sortBy(
      members.filter((member) => nameOrUsernameIncludes(member, lowercaseQuery)),
      (member) => (nameOrUsernameStartsWith(member, lowercaseQuery) ? -1 : 0),
    );
  },
};
GfmAutoComplete.Labels = {
  templateFunction(color, title) {
    return `<li><span class="dropdown-label-box" style="background: ${escape(
      color,
    )}"></span> ${escape(title)}</li>`;
  },
};
// Issues, MergeRequests and Snippets
GfmAutoComplete.Issues = {
  insertTemplateFunction(value) {
    // eslint-disable-next-line no-template-curly-in-string
    return value.reference || '${atwho-at}${id}';
  },
  templateFunction({ id, title, reference }) {
    return `<li><small>${escape(reference || id)}</small> ${escape(title)}</li>`;
  },
};
// Milestones
GfmAutoComplete.Milestones = {
  templateFunction(title, expired) {
    Iif (expired) {
      return `<li>${sprintf(__('%{milestone} (expired)'), {
        milestone: escape(title),
      })}</li>`;
    }
    return `<li>${escape(title)}</li>`;
  },
};
GfmAutoComplete.Contacts = {
  templateFunction({ email, firstName, lastName }) {
    return `<li><small>${escape(firstName)} ${escape(lastName)}</small> ${escape(email)}</li>`;
  },
};
GfmAutoComplete.Wikis = {
  templateFunction({ title, slug }) {
    const icon = spriteIcon('document', 's16 vertical-align-middle gl-mr-2');
    const slugSpan =
      title.toLowerCase() !== slug.toLowerCase() ? ` <small>(${escape(slug)})</small>` : '';
    return `<li>${icon} ${escape(title)} ${slugSpan}</li>`;
  },
};
 
const loadingSpinner = loadingIconForLegacyJS({
  inline: true,
  classes: ['gl-mr-2'],
}).outerHTML;
 
GfmAutoComplete.Loading = {
  template: `<li style="pointer-events: none;">${loadingSpinner}Loading...</li>`,
};
 
export default GfmAutoComplete;