summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/filtered_search/filtered_search_manager.js.es6
blob: 00b7dc195bb355e8abf413f36c110f994a58698c (plain)
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
/* eslint-disable no-param-reassign */
((global) => {
  class FilteredSearchManager {
    constructor() {
      this.tokenizer = gl.FilteredSearchTokenizer;
      this.filteredSearchInput = document.querySelector('.filtered-search');
      this.clearSearchButton = document.querySelector('.clear-search');
      this.dropdownManager = new gl.FilteredSearchDropdownManager();

      this.bindEvents();
      this.loadSearchParamsFromURL();
      this.dropdownManager.setDropdown();

      this.cleanupWrapper = this.cleanup.bind(this);
      document.addEventListener('page:fetch', this.cleanupWrapper);
    }

    cleanup() {
      this.unbindEvents();
      document.removeEventListener('page:fetch', this.cleanupWrapper);
    }

    bindEvents() {
      this.setDropdownWrapper = this.dropdownManager.setDropdown.bind(this.dropdownManager);
      this.toggleClearSearchButtonWrapper = this.toggleClearSearchButton.bind(this);
      this.checkForEnterWrapper = this.checkForEnter.bind(this);
      this.clearSearchWrapper = this.clearSearch.bind(this);
      this.checkForBackspaceWrapper = this.checkForBackspace.bind(this);

      this.filteredSearchInput.addEventListener('input', this.setDropdownWrapper);
      this.filteredSearchInput.addEventListener('input', this.toggleClearSearchButtonWrapper);
      this.filteredSearchInput.addEventListener('keydown', this.checkForEnterWrapper);
      this.filteredSearchInput.addEventListener('keyup', this.checkForBackspaceWrapper);
      this.clearSearchButton.addEventListener('click', this.clearSearchWrapper);
    }

    unbindEvents() {
      this.filteredSearchInput.removeEventListener('input', this.setDropdownWrapper);
      this.filteredSearchInput.removeEventListener('input', this.toggleClearSearchButtonWrapper);
      this.filteredSearchInput.removeEventListener('keydown', this.checkForEnterWrapper);
      this.filteredSearchInput.removeEventListener('keyup', this.checkForBackspaceWrapper);
      this.clearSearchButton.removeEventListener('click', this.clearSearchWrapper);
    }

    checkForBackspace(e) {
      // 8 = Backspace Key
      // 46 = Delete Key
      if (e.keyCode === 8 || e.keyCode === 46) {
        // Reposition dropdown so that it is aligned with cursor
        this.dropdownManager.updateCurrentDropdownOffset();
      }
    }

    checkForEnter(e) {
      if (e.keyCode === 13) {
        e.preventDefault();

        // Prevent droplab from opening dropdown
        this.dropdownManager.destroyDroplab();

        this.search();
      }
    }

    toggleClearSearchButton(e) {
      if (e.target.value) {
        this.clearSearchButton.classList.remove('hidden');
      } else {
        this.clearSearchButton.classList.add('hidden');
      }
    }

    clearSearch(e) {
      e.preventDefault();

      this.filteredSearchInput.value = '';
      this.clearSearchButton.classList.add('hidden');

      this.dropdownManager.resetDropdowns();
    }

    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];

        // Check if it matches edge conditions listed in gl.FilteredSearchTokenKeys.get()
        let conditionIndex = 0;
        const validCondition = gl.FilteredSearchTokenKeys.get()
          .filter(v => v.conditions && v.conditions.filter((c, index) => {
            // Return TokenKeys that have conditions that much the URL
            if (c.url === p) {
              conditionIndex = index;
            }
            return c.url === p;
          })[0])[0];

        if (validCondition) {
          // Parse params based on rules provided in the conditions key of gl.FilteredSearchTokenKeys.get()
          inputValue += `${validCondition.key}:${validCondition.conditions[conditionIndex].keyword}`;
          inputValue += ' ';
        } else {
          // 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 = gl.FilteredSearchTokenKeys.get().filter(t => key === `${t.key}_${t.param}`)[0];

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

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

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

      // Trim the last space value
      this.filteredSearchInput.value = inputValue.trim();

      if (inputValue.trim()) {
        this.clearSearchButton.classList.remove('hidden');
      }
    }

    search() {
      let path = '?scope=all&utf8=✓';

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

      const { tokens, searchToken } = this.tokenizer.processTokens(this.filteredSearchInput.value);

      if (stateIndex !== -1) {
        // Get currentState from url params if available
        const remaining = currentPath.slice(stateIndex + 'state='.length);
        const separatorIndex = remaining.indexOf('&');

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

      path += `&state=${currentState}`;
      tokens.forEach((token) => {
        const match = gl.FilteredSearchTokenKeys.get().filter(t => t.key === token.key)[0];
        let tokenPath = '';

        if (token.wildcard && match.conditions) {
          const condition = match.conditions
            .filter(c => c.keyword === token.value.toLowerCase())[0];

          if (condition) {
            tokenPath = `${condition.url}`;
          }
        } else if (!token.wildcard) {
          // Remove the wildcard token
          tokenPath = `${token.key}_${match.param}=${encodeURIComponent(token.value.slice(1))}`;
        } else {
          tokenPath = `${token.key}_${match.param}=${encodeURIComponent(token.value)}`;
        }

        path += `&${tokenPath}`;
      });

      if (searchToken) {
        path += `&search=${encodeURIComponent(searchToken)}`;
      }

      window.location = path;
    }
  }

  global.FilteredSearchManager = FilteredSearchManager;
})(window.gl || (window.gl = {}));