filtered_search_manager.js.es6 6.3 KB
Newer Older
C
Clement Ho 已提交
1
/* eslint-disable no-param-reassign */
C
Clement Ho 已提交
2 3 4 5
((global) => {
  const validTokenKeys = [{
    key: 'author',
    type: 'string',
6
    param: 'username',
C
Clement Ho 已提交
7
  }, {
C
Clement Ho 已提交
8
    key: 'assignee',
C
Clement Ho 已提交
9
    type: 'string',
10
    param: 'username',
C
Clement Ho 已提交
11
  }, {
C
Clement Ho 已提交
12
    key: 'milestone',
C
Clement Ho 已提交
13 14
    type: 'string',
    param: 'title',
C
Clement Ho 已提交
15
  }, {
C
Clement Ho 已提交
16
    key: 'label',
C
Clement Ho 已提交
17
    type: 'array',
C
Clement Ho 已提交
18
    param: 'name[]',
C
Clement Ho 已提交
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
  }];

  function toggleClearSearchButton(event) {
    const clearSearch = document.querySelector('.clear-search');

    if (event.target.value) {
      clearSearch.classList.remove('hidden');
    } else {
      clearSearch.classList.add('hidden');
    }
  }

  function loadSearchParamsFromURL() {
    // We can trust that each param has one & since values containing & will be encoded
    // Remove the first character of search as it is always ?
    const params = window.location.search.slice(1).split('&');
    let inputValue = '';

    params.forEach((p) => {
      const split = p.split('=');
      const key = decodeURIComponent(split[0]);
      const value = split[1];

      // Sanitize value since URL converts spaces into +
      // Replace before decode so that we know what was originally + versus the encoded +
      const sanitizedValue = value ? decodeURIComponent(value.replace(/[+]/g, ' ')) : value;
      const match = validTokenKeys.find(t => key === `${t.key}_${t.param}`);

      if (match) {
        const sanitizedKey = key.slice(0, key.indexOf('_'));
        const valueHasSpace = sanitizedValue.indexOf(' ') !== -1;

        const preferredQuotations = '"';
        let quotationsToUse = preferredQuotations;

        if (valueHasSpace) {
          // Prefer ", but use ' if required
          quotationsToUse = sanitizedValue.indexOf(preferredQuotations) === -1 ? preferredQuotations : '\'';
        }

        inputValue += valueHasSpace ? `${sanitizedKey}:${quotationsToUse}${sanitizedValue}${quotationsToUse}` : `${sanitizedKey}:${sanitizedValue}`;
        inputValue += ' ';
      } else if (!match && key === 'search') {
        inputValue += sanitizedValue;
        inputValue += ' ';
      }
    });

    // Trim the last space value
    document.querySelector('.filtered-search').value = inputValue.trim();

    if (inputValue.trim()) {
      document.querySelector('.clear-search').classList.remove('hidden');
    }
  }
C
Clement Ho 已提交
74 75 76 77

  class FilteredSearchManager {
    constructor() {
      this.bindEvents();
C
Clement Ho 已提交
78
      loadSearchParamsFromURL();
C
Clement Ho 已提交
79 80 81 82 83
      this.clearTokens();
    }

    bindEvents() {
      const input = document.querySelector('.filtered-search');
C
Clement Ho 已提交
84
      const clearSearch = document.querySelector('.clear-search');
C
Clement Ho 已提交
85 86

      input.addEventListener('input', this.tokenize.bind(this));
C
Clement Ho 已提交
87
      input.addEventListener('input', toggleClearSearchButton);
C
Clement Ho 已提交
88
      input.addEventListener('keydown', this.checkForEnter.bind(this));
C
Clement Ho 已提交
89 90 91 92 93 94 95 96 97

      clearSearch.addEventListener('click', this.clearSearch.bind(this));
    }

    clearSearch(event) {
      event.stopPropagation();
      event.preventDefault();

      this.clearTokens();
98 99
      document.querySelector('.filtered-search').value = '';
      document.querySelector('.clear-search').classList.add('hidden');
C
Clement Ho 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113
    }

    clearTokens() {
      this.tokens = [];
      this.searchToken = '';
    }

    tokenize(event) {
      // Re-calculate tokens
      this.clearTokens();

      const input = event.target.value;
      const inputs = input.split(' ');
      let searchTerms = '';
C
Clement Ho 已提交
114 115
      let lastQuotation = '';
      let incompleteToken = false;
C
Clement Ho 已提交
116

117
      const addSearchTerm = function addSearchTerm(term) {
C
Clement Ho 已提交
118 119 120
        // Add space for next term
        searchTerms += `${term} `;
      };
121

C
Clement Ho 已提交
122
      inputs.forEach((i) => {
C
Clement Ho 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        if (incompleteToken) {
          const prevToken = this.tokens[this.tokens.length - 1];
          prevToken.value += ` ${i}`;

          // Remove last quotation
          const lastQuotationRegex = new RegExp(lastQuotation, 'g');
          prevToken.value = prevToken.value.replace(lastQuotationRegex, '');
          this.tokens[this.tokens.length - 1] = prevToken;

          // Check to see if this quotation completes the token value
          if (i.indexOf(lastQuotation)) {
            incompleteToken = !incompleteToken;
          }

          return;
        }

C
Clement Ho 已提交
140 141 142 143 144
        const colonIndex = i.indexOf(':');

        if (colonIndex !== -1) {
          const tokenKey = i.slice(0, colonIndex).toLowerCase();
          const tokenValue = i.slice(colonIndex + 1);
C
Clement Ho 已提交
145
          const match = validTokenKeys.find(v => v.key === tokenKey);
C
Clement Ho 已提交
146 147 148 149 150 151 152 153

          if (tokenValue.indexOf('"') !== -1) {
            lastQuotation = '"';
            incompleteToken = true;
          } else if (tokenValue.indexOf('\'') !== -1) {
            lastQuotation = '\'';
            incompleteToken = true;
          }
C
Clement Ho 已提交
154

C
Clement Ho 已提交
155 156 157 158 159
          if (match && tokenValue.length > 0) {
            this.tokens.push({
              key: match.key,
              value: tokenValue,
            });
160 161
          } else {
            addSearchTerm(i);
C
Clement Ho 已提交
162 163
          }
        } else {
164
          addSearchTerm(i);
C
Clement Ho 已提交
165 166 167 168 169 170 171 172
        }
      }, this);

      this.searchToken = searchTerms.trim();
      this.printTokens();
    }

    printTokens() {
C
Clement Ho 已提交
173 174 175
      console.log('tokens:');
      this.tokens.forEach(token => console.log(token));
      console.log(`search: ${this.searchToken}`);
C
Clement Ho 已提交
176 177 178 179 180 181 182 183 184 185 186 187
    }

    checkForEnter(event) {
      if (event.key === 'Enter') {
        event.stopPropagation();
        event.preventDefault();
        this.search();
      }
    }

    search() {
      console.log('search');
C
Clement Ho 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
      let path = '?scope=all&utf8=✓';

      // Check current state
      const currentPath = window.location.search;
      const stateIndex = currentPath.indexOf('state=');
      const defaultState = 'opened';
      let currentState = defaultState;

      if (stateIndex !== -1) {
        const remaining = currentPath.slice(stateIndex + 6);
        const separatorIndex = remaining.indexOf('&');

        currentState = separatorIndex === -1 ? remaining : remaining.slice(0, separatorIndex);
      }

C
Clement Ho 已提交
203
      path += `&state=${currentState}`;
C
Clement Ho 已提交
204
      this.tokens.forEach((token) => {
C
Clement Ho 已提交
205
        const param = validTokenKeys.find(t => t.key === token.key).param;
C
Clement Ho 已提交
206
        path += `&${token.key}_${param}=${encodeURIComponent(token.value)}`;
C
Clement Ho 已提交
207 208 209
      });

      if (this.searchToken) {
C
Clement Ho 已提交
210
        path += `&search=${encodeURIComponent(this.searchToken)}`;
C
Clement Ho 已提交
211 212 213 214 215 216 217
      }

      window.location = path;
    }
  }

  global.FilteredSearchManager = FilteredSearchManager;
C
Clement Ho 已提交
218
})(window.gl || (window.gl = {}));