summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/utils/walker-search.js
blob: 0955a391979d548e2c8111d9cf7577ab69278e98 (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
/* 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";

/**
 * 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.
 */

const {Ci, Cu} = require("chrome");

/**
 * 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
 */
function WalkerIndex(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);
}

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

  clearIndex: function () {
    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: function (type, node, value) {
    // Add an entry for this value if there isn't one
    let entry = this._data.get(value);
    if (!entry) {
      this._data.set(value, []);
    }

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

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

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

      if (node.nodeType === 1) {
        // For each element node, we get the tagname and all attributes names
        // and values
        let localName = node.localName;
        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 (let {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;

/**
 * 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
 */
function WalkerSearch(walker) {
  this.walker = walker;
  this.index = new WalkerIndex(this.walker);
}

WalkerSearch.prototype = {
  destroy: function () {
    this.index.destroy();
    this.walker = null;
  },

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

    let matches = results.get(node);

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

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

  _searchIndex: function (query, options, results) {
    for (let [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.indexOf(entry.type) !== -1;
      }).forEach(({node, type}) => {
        this._addResult(node, type, results);
      });
    }
  },

  _searchSelectors: function (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
    let isSelector = query && query.match(/[ >~.#\[\]]/);
    if (options.types.indexOf("selector") === -1 || !isSelector) {
      return;
    }

    let nodes = this.walker._multiFrameQuerySelectorAll(query);
    for (let node of nodes) {
      this._addResult(node, "selector", 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 search type)
   * - 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: function (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
    let results = new Map();

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

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

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

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

    let documents = this.walker.tabActor.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) {
        let indA = documents.indexOf(a.node.ownerDocument);
        let 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().indexOf(query.toLowerCase()) !== -1;
};

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

exports.WalkerSearch = WalkerSearch;