summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/search_settings/components/search_settings.vue
blob: 3e23b8a3435cf239500542e2045b3f39cbcaf9f7 (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
<script>
import { GlSearchBoxByType } from '@gitlab/ui';
import { uniq, escapeRegExp } from 'lodash';
import {
  EXCLUDED_NODES,
  HIDE_CLASS,
  HIGHLIGHT_CLASS,
  NONE_PADDING_CLASS,
  TYPING_DELAY,
} from '../constants';

const origExpansions = new Map();

const findSettingsSection = (sectionSelector, node) => {
  return node.parentElement.closest(sectionSelector);
};

const restoreExpansionState = ({ expandSection, collapseSection }) => {
  origExpansions.forEach((isExpanded, section) => {
    if (isExpanded) {
      expandSection(section);
    } else {
      collapseSection(section);
    }
  });

  origExpansions.clear();
};

const saveExpansionState = (sections, { isExpanded }) => {
  // If we've saved expansions before, don't override it.
  if (origExpansions.size > 0) {
    return;
  }

  sections.forEach((section) => origExpansions.set(section, isExpanded(section)));
};

const resetSections = ({ sectionSelector }) => {
  document.querySelectorAll(sectionSelector).forEach((section) => {
    section.classList.remove(HIDE_CLASS);
  });
};

const clearHighlights = () => {
  document.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach((element) => {
    const { parentNode } = element;
    const textNode = document.createTextNode(element.textContent);
    parentNode.replaceChild(textNode, element);

    parentNode.normalize();
  });
};

const hideSectionsExcept = (sectionSelector, visibleSections) => {
  Array.from(document.querySelectorAll(sectionSelector))
    .filter((section) => !visibleSections.includes(section))
    .forEach((section) => {
      section.classList.add(HIDE_CLASS);
    });
};

const transformMatchElement = (element, searchTerm) => {
  const textStr = element.textContent;
  const escapedSearchTerm = new RegExp(`(${escapeRegExp(searchTerm)})`, 'gi');

  const textList = textStr.split(escapedSearchTerm);
  const replaceFragment = document.createDocumentFragment();
  textList.forEach((text) => {
    let addElement = document.createTextNode(text);
    if (escapedSearchTerm.test(text)) {
      addElement = document.createElement('mark');
      addElement.className = `${HIGHLIGHT_CLASS} ${NONE_PADDING_CLASS}`;
      addElement.textContent = text;
      escapedSearchTerm.lastIndex = 0;
    }
    replaceFragment.appendChild(addElement);
  });

  return replaceFragment;
};

const highlightElements = (elements = [], searchTerm) => {
  elements.forEach((element) => {
    const replaceFragment = transformMatchElement(element, searchTerm);
    element.innerHTML = '';
    element.appendChild(replaceFragment);
  });
};

const displayResults = ({ sectionSelector, expandSection, searchTerm }, matches) => {
  const elements = matches.map((match) => match.parentElement);
  const sections = uniq(elements.map((element) => findSettingsSection(sectionSelector, element)));

  hideSectionsExcept(sectionSelector, sections);
  sections.forEach(expandSection);
  highlightElements(elements, searchTerm);
};

const clearResults = (params) => {
  resetSections(params);
  clearHighlights();
};

const includeNode = (node, lowerSearchTerm) =>
  node.textContent.toLowerCase().includes(lowerSearchTerm) &&
  EXCLUDED_NODES.every((excluded) => !node.parentElement.closest(excluded));

const search = (root, searchTerm) => {
  const iterator = document.createNodeIterator(root, NodeFilter.SHOW_TEXT, {
    acceptNode(node) {
      return includeNode(node, searchTerm.toLowerCase())
        ? NodeFilter.FILTER_ACCEPT
        : NodeFilter.FILTER_REJECT;
    },
  });
  const results = [];

  for (let currentNode = iterator.nextNode(); currentNode; currentNode = iterator.nextNode()) {
    results.push(currentNode);
  }

  return results;
};

export default {
  components: {
    GlSearchBoxByType,
  },
  props: {
    searchRoot: {
      type: Element,
      required: true,
    },
    sectionSelector: {
      type: String,
      required: true,
    },
    isExpandedFn: {
      type: Function,
      required: false,
      // default to a function that returns false
      default: () => () => false,
    },
  },
  data() {
    return {
      searchTerm: '',
    };
  },
  methods: {
    search(value) {
      this.searchTerm = value;
      const displayOptions = {
        sectionSelector: this.sectionSelector,
        expandSection: this.expandSection,
        collapseSection: this.collapseSection,
        isExpanded: this.isExpandedFn,
        searchTerm: this.searchTerm,
      };

      clearResults(displayOptions);

      if (value.length) {
        saveExpansionState(document.querySelectorAll(this.sectionSelector), displayOptions);

        displayResults(displayOptions, search(this.searchRoot, this.searchTerm));
      } else {
        restoreExpansionState(displayOptions);
      }
    },
    expandSection(section) {
      this.$emit('expand', section);
    },
    collapseSection(section) {
      this.$emit('collapse', section);
    },
  },
  TYPING_DELAY,
};
</script>
<template>
  <gl-search-box-by-type
    :value="searchTerm"
    :debounce="$options.TYPING_DELAY"
    :placeholder="__('Search settings')"
    @input="search"
  />
</template>