summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/utils/walker-search.js
blob: a5ffb48fadfe81562a08f305b1a410d975da0ffb (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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

loader.lazyRequireGetter(
  this,
  "isWhitespaceTextNode",
  "resource://devtools/server/actors/inspector/utils.js",
  true
);

/**
 * The walker-search module provides a simple API to index and search strings
 * and elements inside a given document.
 * It indexes tag names, attribute names and values, and text contents.
 * It provides a simple search function that returns a list of nodes that
 * matched.
 */

class WalkerIndex {
  /**
   * The WalkerIndex class indexes the document (and all subdocs) from
   * a given walker.
   *
   * It is only indexed the first time the data is accessed and will be
   * re-indexed if a mutation happens between requests.
   *
   * @param {Walker} walker The walker to be indexed
   */
  constructor(walker) {
    this.walker = walker;
    this.clearIndex = this.clearIndex.bind(this);

    // Kill the index when mutations occur, the next data get will re-index.
    this.walker.on("any-mutation", this.clearIndex);
  }

  /**
   * Destroy this instance, releasing all data and references
   */
  destroy() {
    this.walker.off("any-mutation", this.clearIndex);
  }

  clearIndex() {
    if (!this.currentlyIndexing) {
      this._data = null;
    }
  }

  get doc() {
    return this.walker.rootDoc;
  }

  /**
   * Get the indexed data
   * This getter also indexes if it hasn't been done yet or if the state is
   * dirty
   *
   * @returns Map<String, Array<{type:String, node:DOMNode}>>
   *          A Map keyed on the searchable value, containing an array with
   *          objects containing the 'type' (one of ALL_RESULTS_TYPES), and
   *          the DOM Node.
   */
  get data() {
    if (!this._data) {
      this._data = new Map();
      this.index();
    }

    return this._data;
  }

  _addToIndex(type, node, value) {
    // Add an entry for this value if there isn't one
    const entry = this._data.get(value);
    if (!entry) {
      this._data.set(value, []);
    }

    // Add the type/node to the list
    this._data.get(value).push({
      type,
      node,
    });
  }

  index() {
    // Handle case where iterating nextNode() with the deepTreeWalker triggers
    // a mutation (Bug 1222558)
    this.currentlyIndexing = true;

    const documentWalker = this.walker.getDocumentWalker(this.doc);
    while (documentWalker.nextNode()) {
      const node = documentWalker.currentNode;

      if (
        this.walker.targetActor.ignoreSubFrames &&
        node.ownerDocument !== this.doc
      ) {
        continue;
      }

      if (node.nodeType === 1) {
        // For each element node, we get the tagname and all attributes names
        // and values
        const localName = node.localName;
        if (localName === "_moz_generated_content_marker") {
          this._addToIndex("tag", node, "::marker");
          this._addToIndex("text", node, node.textContent.trim());
        } else if (localName === "_moz_generated_content_before") {
          this._addToIndex("tag", node, "::before");
          this._addToIndex("text", node, node.textContent.trim());
        } else if (localName === "_moz_generated_content_after") {
          this._addToIndex("tag", node, "::after");
          this._addToIndex("text", node, node.textContent.trim());
        } else {
          this._addToIndex("tag", node, node.localName);
        }

        for (const { name, value } of node.attributes) {
          this._addToIndex("attributeName", node, name);
          this._addToIndex("attributeValue", node, value);
        }
      } else if (node.textContent && node.textContent.trim().length) {
        // For comments and text nodes, we get the text
        this._addToIndex("text", node, node.textContent.trim());
      }
    }

    this.currentlyIndexing = false;
  }
}

exports.WalkerIndex = WalkerIndex;

class WalkerSearch {
  /**
   * The WalkerSearch class provides a way to search an indexed document as well
   * as find elements that match a given css selector.
   *
   * Usage example:
   * let s = new WalkerSearch(doc);
   * let res = s.search("lang", index);
   * for (let {matched, results} of res) {
   *   for (let {node, type} of results) {
   *     console.log("The query matched a node's " + type);
   *     console.log("Node that matched", node);
   *    }
   * }
   * s.destroy();
   *
   * @param {Walker} the walker to be searched
   */
  constructor(walker) {
    this.walker = walker;
    this.index = new WalkerIndex(this.walker);
  }

  destroy() {
    this.index.destroy();
    this.walker = null;
  }

  _addResult(node, type, results) {
    if (!results.has(node)) {
      results.set(node, []);
    }

    const matches = results.get(node);

    // Do not add if the exact same result is already in the list
    let isKnown = false;
    for (const match of matches) {
      if (match.type === type) {
        isKnown = true;
        break;
      }
    }

    if (!isKnown) {
      matches.push({ type });
    }
  }

  _searchIndex(query, options, results) {
    for (const [matched, res] of this.index.data) {
      if (!options.searchMethod(query, matched)) {
        continue;
      }

      // Add any relevant results (skipping non-requested options).
      res
        .filter(entry => {
          return options.types.includes(entry.type);
        })
        .forEach(({ node, type }) => {
          this._addResult(node, type, results);
        });
    }
  }

  _searchSelectors(query, options, results) {
    // If the query is just one "word", no need to search because _searchIndex
    // will lead the same results since it has access to tagnames anyway
    const isSelector = query && query.match(/[ >~.#\[\]]/);
    if (!options.types.includes("selector") || !isSelector) {
      return;
    }

    const nodes = this.walker._multiFrameQuerySelectorAll(query);
    for (const node of nodes) {
      this._addResult(node, "selector", results);
    }
  }

  _searchXPath(query, options, results) {
    if (!options.types.includes("xpath")) {
      return;
    }

    const nodes = this.walker._multiFrameXPath(query);
    for (const node of nodes) {
      // Exclude text nodes that only contain whitespace
      // because they are not displayed in the Inspector.
      if (!isWhitespaceTextNode(node)) {
        this._addResult(node, "xpath", results);
      }
    }
  }

  /**
   * Search the document
   * @param {String} query What to search for
   * @param {Object} options The following options are accepted:
   * - searchMethod {String} one of WalkerSearch.SEARCH_METHOD_*
   *   defaults to WalkerSearch.SEARCH_METHOD_CONTAINS (does not apply to
   *   selector and XPath search types)
   * - types {Array} a list of things to search for (tag, text, attributes, etc)
   *   defaults to WalkerSearch.ALL_RESULTS_TYPES
   * @return {Array} An array is returned with each item being an object like:
   * {
   *   node: <the dom node that matched>,
   *   type: <the type of match: one of WalkerSearch.ALL_RESULTS_TYPES>
   * }
   */
  search(query, options = {}) {
    options.searchMethod =
      options.searchMethod || WalkerSearch.SEARCH_METHOD_CONTAINS;
    options.types = options.types || WalkerSearch.ALL_RESULTS_TYPES;

    // Empty strings will return no results, as will non-string input
    if (typeof query !== "string") {
      query = "";
    }

    // Store results in a map indexed by nodes to avoid duplicate results
    const results = new Map();

    // Search through the indexed data
    this._searchIndex(query, options, results);

    // Search with querySelectorAll
    this._searchSelectors(query, options, results);

    // Search with XPath
    this._searchXPath(query, options, results);

    // Concatenate all results into an Array to return
    const resultList = [];
    for (const [node, matches] of results) {
      for (const { type } of matches) {
        resultList.push({
          node,
          type,
        });

        // For now, just do one result per node since the frontend
        // doesn't have a way to highlight each result individually
        // yet.
        break;
      }
    }

    const documents = this.walker.targetActor.windows.map(win => win.document);

    // Sort the resulting nodes by order of appearance in the DOM
    resultList.sort((a, b) => {
      // Disconnected nodes won't get good results from compareDocumentPosition
      // so check the order of their document instead.
      if (a.node.ownerDocument != b.node.ownerDocument) {
        const indA = documents.indexOf(a.node.ownerDocument);
        const indB = documents.indexOf(b.node.ownerDocument);
        return indA - indB;
      }
      // If the same document, then sort on DOCUMENT_POSITION_FOLLOWING (4)
      // which means B is after A.
      return a.node.compareDocumentPosition(b.node) & 4 ? -1 : 1;
    });

    return resultList;
  }
}

WalkerSearch.SEARCH_METHOD_CONTAINS = (query, candidate) => {
  return query && candidate.toLowerCase().includes(query.toLowerCase());
};

WalkerSearch.ALL_RESULTS_TYPES = [
  "tag",
  "text",
  "attributeName",
  "attributeValue",
  "selector",
  "xpath",
];

exports.WalkerSearch = WalkerSearch;