Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Delta Between Two Patch Sets: chrome/content/elemHideEmulation.js

Issue 29383960: Issue 3143 - Filter elements with :-abp-has() (Closed) Base URL: https://hg.adblockplus.org/adblockpluscore
Left Patch Set: Lots of cleanup. Simpler, better. Created April 3, 2017, 8:09 a.m.
Right Patch Set: Fix reportError and the error message Created June 13, 2017, 1:52 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « chrome/content/.eslintrc.json ('k') | test/browser/elemHideEmulation.js » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 // We are currently limited to ECMAScript 5 in this file, because it is being 1 /*
2 // used in the browser tests. See https://issues.adblockplus.org/ticket/4796 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 3 * Copyright (C) 2006-2017 eyeo GmbH
4 var propertySelectorRegExp = /\[\-abp\-properties=(["'])([^"']+)\1\]/; 4 *
5 var pseudoClassHasSelectorRegExp = /:has\((.*)\)/; 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 /* globals filterToRegExp */
19
20 "use strict";
21
22 const abpSelectorRegexp = /:-abp-([\w-]+)\(/i;
23
24 let reportError = () => {};
6 25
7 function splitSelector(selector) 26 function splitSelector(selector)
8 { 27 {
9 if (selector.indexOf(",") == -1) 28 if (selector.indexOf(",") == -1)
10 return [selector]; 29 return [selector];
11 30
12 var selectors = []; 31 let selectors = [];
13 var start = 0; 32 let start = 0;
14 var level = 0; 33 let level = 0;
15 var sep = ""; 34 let sep = "";
16 35
17 for (var i = 0; i < selector.length; i++) 36 for (let i = 0; i < selector.length; i++)
18 { 37 {
19 var chr = selector[i]; 38 let chr = selector[i];
20 39
21 if (chr == "\\") // ignore escaped characters 40 if (chr == "\\") // ignore escaped characters
22 i++; 41 i++;
23 else if (chr == sep) // don't split within quoted text 42 else if (chr == sep) // don't split within quoted text
24 sep = ""; // e.g. [attr=","] 43 sep = ""; // e.g. [attr=","]
25 else if (sep == "") 44 else if (sep == "")
26 { 45 {
27 if (chr == '"' || chr == "'") 46 if (chr == '"' || chr == "'")
28 sep = chr; 47 sep = chr;
29 else if (chr == "(") // don't split between parentheses 48 else if (chr == "(") // don't split between parentheses
30 level++; // e.g. :matches(div,span) 49 level++; // e.g. :matches(div,span)
31 else if (chr == ")") 50 else if (chr == ")")
32 level = Math.max(0, level - 1); 51 level = Math.max(0, level - 1);
33 else if (chr == "," && level == 0) 52 else if (chr == "," && level == 0)
34 { 53 {
35 selectors.push(selector.substring(start, i)); 54 selectors.push(selector.substring(start, i));
36 start = i + 1; 55 start = i + 1;
37 } 56 }
38 } 57 }
39 } 58 }
40 59
41 selectors.push(selector.substring(start)); 60 selectors.push(selector.substring(start));
42 return selectors; 61 return selectors;
43 } 62 }
44 63
45 const ABP_ATTR = "abp-0ac791f0-a03b-4f2c-a935-a285bc2e668e"; 64 /** Return position of node from parent.
46 const ABP_ATTR_SEL = "[" + ABP_ATTR + "] "; 65 * @param {Node} node the node to find the position of.
47 66 * @return {number} One-based index like for :nth-child(), or 0 on error.
48 function matchChildren(e, selector) 67 */
49 { 68 function positionInParent(node)
50 var subElement; 69 {
51 var newSelector = ABP_ATTR_SEL + selector; 70 let {children} = node.parentNode;
52 var parentNode = e.parentNode || document; 71 for (let i = 0; i < children.length; i++)
53 72 if (children[i] == node)
54 e.setAttribute(ABP_ATTR, ""); 73 return i + 1;
55 subElement = parentNode.querySelector(newSelector); 74 return 0;
56 e.removeAttribute(ABP_ATTR); 75 }
57 76
58 return subElement != null; 77 function makeSelector(node, selector)
59 } 78 {
60 79 if (!node.parentElement)
61 function selectChildren(e, selector) 80 {
62 { 81 let newSelector = ":root";
63 var subElements; 82 if (selector)
64 var newSelector = ABP_ATTR_SEL + selector; 83 newSelector += " > " + selector;
65 var parentNode = e.parentNode || document; 84 return newSelector;
66 85 }
67 e.setAttribute(ABP_ATTR, ""); 86 let idx = positionInParent(node);
68 subElements = parentNode.querySelectorAll(newSelector); 87 if (idx > 0)
69 e.removeAttribute(ABP_ATTR); 88 {
70 89 let newSelector = `${node.tagName}:nth-child(${idx})`;
71 return subElements; 90 if (selector)
72 } 91 newSelector += " > " + selector;
73 92 return makeSelector(node.parentElement, newSelector);
74 function parsePattern(pattern) 93 }
75 { 94
76 // we should catch the :has() pseudo class first. 95 return selector;
77 var match = pseudoClassHasSelectorRegExp.exec(pattern.selector); 96 }
78 if (match) 97
79 { 98 function parseSelectorContent(content, startIndex)
80 return { 99 {
81 type: "has", 100 let parens = 1;
82 text: pattern.text, 101 let quote = null;
83 elementMatcher: new PseudoHasMatcher(match[1]), 102 let i = startIndex;
84 prefix: pattern.selector.substr(0, match.index).trim(), 103 for (; i < content.length; i++)
85 suffix: pattern.selector.substr(match.index + match[0].length).trim() 104 {
86 }; 105 let c = content[i];
87 } 106 if (c == "\\")
88 107 {
89 match = propertySelectorRegExp.exec(pattern.selector); 108 // Ignore escaped characters
90 if (match) 109 i++;
91 { 110 }
92 var regexpString; 111 else if (quote)
93 var propertyExpression = match[2]; 112 {
94 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" && 113 if (c == quote)
95 propertyExpression[propertyExpression.length - 1] == "/") 114 quote = null;
96 regexpString = propertyExpression.slice(1, -1) 115 }
116 else if (c == "'" || c == '"')
117 quote = c;
118 else if (c == "(")
119 parens++;
120 else if (c == ")")
121 {
122 parens--;
123 if (parens == 0)
124 break;
125 }
126 }
127
128 if (parens > 0)
129 return null;
130 return {text: content.substring(startIndex, i), end: i};
131 }
132
133 /** Parse the selector
134 * @param {string} selector the selector to parse
135 * @return {Object} selectors is an array of objects,
136 * or null in case of errors. hide is true if we'll hide
137 * elements instead of styles..
138 */
139 function parseSelector(selector)
140 {
141 if (selector.length == 0)
142 return [];
143
144 let match = abpSelectorRegexp.exec(selector);
145 if (!match)
146 return [new PlainSelector(selector)];
147
148 let selectors = [];
149 if (match.index > 0)
150 selectors.push(new PlainSelector(selector.substr(0, match.index)));
151
152 let startIndex = match.index + match[0].length;
153 let content = parseSelectorContent(selector, startIndex);
154 if (!content)
155 {
156 reportError(new SyntaxError("Failed to parse Adblock Plus " +
157 `selector ${selector}, ` +
158 "due to unmatched parentheses."));
159 return null;
160 }
161 if (match[1] == "properties")
162 selectors.push(new PropsSelector(content.text));
163 else if (match[1] == "has")
164 {
165 let hasSelector = new HasSelector(content.text);
166 if (!hasSelector.valid())
167 return null;
168 selectors.push(hasSelector);
169 }
170 else
171 {
172 // this is an error, can't parse selector.
173 reportError(new SyntaxError("Failed to parse Adblock Plus " +
174 `selector ${selector}, invalid ` +
175 `pseudo-class :-abp-${match[1]}().`));
176 return null;
177 }
178
179 let suffix = parseSelector(selector.substr(content.end + 1));
180 if (suffix == null)
181 return null;
182
183 selectors.push(...suffix);
184
185 return selectors;
186 }
187
188 /** Stringified style objects
189 * @typedef {Object} StringifiedStyle
190 * @property {string} style CSS style represented by a string.
191 * @property {string[]} subSelectors selectors the CSS properties apply to.
192 */
193
194 /**
195 * Produce a string representation of the stylesheet entry.
196 * @param {CSSStyleRule} rule the CSS style rule.
197 * @return {StringifiedStyle} the stringified style.
198 */
199 function stringifyStyle(rule)
200 {
201 let styles = [];
202 for (let i = 0; i < rule.style.length; i++)
203 {
204 let property = rule.style.item(i);
205 let value = rule.style.getPropertyValue(property);
206 let priority = rule.style.getPropertyPriority(property);
207 styles.push(`${property}: ${value}${priority ? " !" + priority : ""};`);
208 }
209 styles.sort();
210 return {
211 style: styles.join(" "),
212 subSelectors: splitSelector(rule.selectorText)
213 };
214 }
215
216 function* evaluate(chain, index, prefix, subtree, styles)
217 {
218 if (index >= chain.length)
219 {
220 yield prefix;
221 return;
222 }
223 for (let [selector, element] of
224 chain[index].getSelectors(prefix, subtree, styles))
225 yield* evaluate(chain, index + 1, selector, element, styles);
226 }
227
228 function PlainSelector(selector)
229 {
230 this._selector = selector;
231 }
232
233 PlainSelector.prototype = {
234 /**
235 * Generator function returning a pair of selector
236 * string and subtree.
237 * @param {string} prefix the prefix for the selector.
238 * @param {Node} subtree the subtree we work on.
239 * @param {StringifiedStyle[]} styles the stringified style objects.
240 */
241 *getSelectors(prefix, subtree, styles)
242 {
243 yield [prefix + this._selector, subtree];
244 }
245 };
246
247 const incompletePrefixRegexp = /[\s>+~]$/;
248
249 function HasSelector(selector)
250 {
251 this._innerSelectors = parseSelector(selector);
252 }
253
254 HasSelector.prototype = {
255 requiresHiding: true,
256
257 valid()
258 {
259 return this._innerSelectors != null;
260 },
261
262 *getSelectors(prefix, subtree, styles)
263 {
264 for (let element of this.getElements(prefix, subtree, styles))
265 yield [makeSelector(element, ""), element];
266 },
267
268 /**
269 * Generator function returning selected elements.
270 * @param {string} prefix the prefix for the selector.
271 * @param {Node} subtree the subtree we work on.
272 * @param {StringifiedStyle[]} styles the stringified style objects.
273 */
274 *getElements(prefix, subtree, styles)
275 {
276 let actualPrefix = (!prefix || incompletePrefixRegexp.test(prefix)) ?
277 prefix + "*" : prefix;
278 let elements = subtree.querySelectorAll(actualPrefix);
279 for (let element of elements)
280 {
281 let newPrefix = makeSelector(element, "");
282 let iter = evaluate(this._innerSelectors, 0, newPrefix + " ",
283 element, styles);
284 for (let selector of iter)
285 // we insert a space between the two. It becomes a no-op if selector
286 // doesn't have a combinator
287 if (subtree.querySelector(selector))
288 yield element;
289 }
290 }
291 };
292
293 function PropsSelector(propertyExpression)
294 {
295 let regexpString;
296 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" &&
297 propertyExpression[propertyExpression.length - 1] == "/")
298 {
299 regexpString = propertyExpression.slice(1, -1)
97 .replace("\\x7B ", "{").replace("\\x7D ", "}"); 300 .replace("\\x7B ", "{").replace("\\x7D ", "}");
98 else 301 }
99 regexpString = filterToRegExp(propertyExpression); 302 else
100 return { 303 regexpString = filterToRegExp(propertyExpression);
101 type: "props", 304
102 text: pattern.text, 305 this._regexp = new RegExp(regexpString, "i");
103 regexp: new RegExp(regexpString, "i"), 306 }
104 prefix: pattern.selector.substr(0, match.index), 307
105 suffix: pattern.selector.substr(match.index + match[0].length) 308 PropsSelector.prototype = {
106 }; 309 *findPropsSelectors(styles, prefix, regexp)
107 } 310 {
108 } 311 for (let style of styles)
109 312 if (regexp.test(style.style))
110 function matchStyleProps(style, rule, pattern, selectors, filters) 313 for (let subSelector of style.subSelectors)
111 { 314 yield prefix + subSelector;
112 if (pattern.regexp.test(style)) 315 },
113 { 316
114 var subSelectors = splitSelector(rule.selectorText); 317 *getSelectors(prefix, subtree, styles)
115 for (var i = 0; i < subSelectors.length; i++) 318 {
116 { 319 for (let selector of this.findPropsSelectors(styles, prefix, this._regexp))
117 var subSelector = subSelectors[i]; 320 yield [selector, subtree];
118 selectors.push(pattern.prefix + subSelector + pattern.suffix);
119 filters.push(pattern.text);
120 }
121 }
122 }
123
124 function findPropsSelectors(stylesheet, patterns, selectors, filters)
125 {
126 var rules = stylesheet.cssRules;
127 if (!rules)
128 return;
129
130 for (var i = 0; i < rules.length; i++)
131 {
132 var rule = rules[i];
133 if (rule.type != rule.STYLE_RULE)
134 continue;
135
136 var style = stringifyStyle(rule.style);
137 for (var j = 0; j < patterns.length; j++)
138 {
139 matchStyleProps(style, rule, patterns[j], selectors, filters);
140 }
141 }
142 }
143
144 /**
145 * Match the selector @pattern containing :has() starting from @node.
146 */
147 function pseudoClassHasMatch(pattern, node, stylesheets, elements, filters)
148 {
149 // select element for the prefix pattern. Or just use node.
150 var haveEl = pattern.prefix ? node.querySelectorAll(pattern.prefix) : [ node ] ;
151 for (var j = 0; j < haveEl.length; j++)
152 {
153 var matched = pattern.elementMatcher.match(haveEl[j], stylesheets);
154 if (!matched)
155 continue;
156
157 if (pattern.suffix)
158 {
159 var subElements = selectChildren(haveEl[j], pattern.suffix);
160 if (subElements)
161 {
162 for (var k = 0; k < subElements.length; k++)
163 {
164 elements.push(subElements[k]);
165 filters.push(pattern.text);
166 }
167 }
168 }
169 else
170 {
171 elements.push(haveEl[j]);
172 filters.push(pattern.text);
173 }
174 }
175 }
176
177 function stringifyStyle(style)
178 {
179 var styles = [];
180 for (var i = 0; i < style.length; i++)
181 {
182 var property = style.item(i);
183 var value = style.getPropertyValue(property);
184 var priority = style.getPropertyPriority(property);
185 styles.push(property + ": " + value + (priority ? " !" + priority : "") + "; ");
186 }
187 styles.sort();
188 return styles.join(" ");
189 }
190
191 // matcher for the pseudo CSS4 class :has
192 // For those browser that don't have it yet.
193 function PseudoHasMatcher(selector)
194 {
195 this.hasSelector = selector;
196 this.parsed = parsePattern({ selector: this.hasSelector });
197 }
198
199 PseudoHasMatcher.prototype = {
200 match: function(elem, stylesheets)
201 {
202 var selectors = [];
203
204 if (this.parsed)
205 {
206 var filters = []; // don't need this, we have a partial filter.
207 if (this.parsed.type == "has")
208 {
209 var child = elem.firstChild;
210 while (child)
211 {
212 if (child.nodeType === Node.ELEMENT_NODE)
213 {
214 var matches = [];
215 pseudoClassHasMatch(this.parsed, child, stylesheets, matches, filter s)
216 if (matches.length > 0)
217 return true;
218 }
219 child = child.nextSibling;
220 }
221 return false;
222 }
223 if (this.parsed.type == "props")
224 {
225 for (var i = 0; i < stylesheets.length; i++)
226 findPropsSelectors(stylesheets[i], [this.parsed], selectors, filters);
227 }
228 }
229 else
230 {
231 selectors = [this.hasSelector];
232 }
233
234 var matched = false;
235 // look up for all elements that match the :has().
236 for (var k = 0; k < selectors.length; k++)
237 {
238 try
239 {
240 matched = matchChildren(elem, selectors[k]);
241 if (matched)
242 break;
243 }
244 catch(e)
245 {
246 console.error("Exception with querySelector()", selectors[k], e);
247 }
248 }
249 return matched;
250 } 321 }
251 }; 322 };
252 323
253 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc, hideElement sFunc) 324 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc,
325 hideElemsFunc)
254 { 326 {
255 this.window = window; 327 this.window = window;
256 this.getFiltersFunc = getFiltersFunc; 328 this.getFiltersFunc = getFiltersFunc;
257 this.addSelectorsFunc = addSelectorsFunc; 329 this.addSelectorsFunc = addSelectorsFunc;
258 this.hideElementsFunc = hideElementsFunc; 330 this.hideElemsFunc = hideElemsFunc;
259 } 331 }
260 332
261 ElemHideEmulation.prototype = { 333 ElemHideEmulation.prototype = {
262 334 isSameOrigin(stylesheet)
263 isSameOrigin: function(stylesheet)
264 { 335 {
265 try 336 try
266 { 337 {
267 return new URL(stylesheet.href).origin == this.window.location.origin; 338 return new URL(stylesheet.href).origin == this.window.location.origin;
268 } 339 }
269 catch (e) 340 catch (e)
270 { 341 {
271 // Invalid URL, assume that it is first-party. 342 // Invalid URL, assume that it is first-party.
272 return true; 343 return true;
273 } 344 }
274 }, 345 },
275 346
276 findPseudoClassHasElements: function(node, stylesheets, elements, filters) 347 addSelectors(stylesheets)
277 { 348 {
278 for (var i = 0; i < this.pseudoHasPatterns.length; i++) 349 let selectors = [];
279 { 350 let selectorFilters = [];
280 pseudoClassHasMatch(this.pseudoHasPatterns[i], node, stylesheets, elements , filters); 351
281 } 352 let elements = [];
282 }, 353 let elementFilters = [];
283 354
284 addSelectors: function(stylesheets) 355 let cssStyles = [];
285 { 356
286 var selectors = []; 357 for (let stylesheet of stylesheets)
287 var filters = [];
288 for (var i = 0; i < stylesheets.length; i++)
289 { 358 {
290 // Explicitly ignore third-party stylesheets to ensure consistent behavior 359 // Explicitly ignore third-party stylesheets to ensure consistent behavior
291 // between Firefox and Chrome. 360 // between Firefox and Chrome.
292 if (!this.isSameOrigin(stylesheets[i])) 361 if (!this.isSameOrigin(stylesheet))
293 continue; 362 continue;
294 findPropsSelectors(stylesheets[i], this.propSelPatterns, selectors, filter s); 363
295 } 364 let rules = stylesheet.cssRules;
296 this.addSelectorsFunc(selectors, filters); 365 if (!rules)
297 }, 366 continue;
298 367
299 hideElements: function(stylesheets) 368 for (let rule of rules)
300 { 369 {
301 var elements = []; 370 if (rule.type != rule.STYLE_RULE)
302 var filters = []; 371 continue;
303 this.findPseudoClassHasElements(document, stylesheets, elements, filters); 372
304 this.hideElementsFunc(elements, filters); 373 cssStyles.push(stringifyStyle(rule));
305 }, 374 }
306 375 }
307 onLoad: function(event) 376
308 { 377 let {document} = this.window;
309 var stylesheet = event.target.sheet; 378 for (let pattern of this.patterns)
379 {
380 for (let selector of evaluate(pattern.selectors,
381 0, "", document, cssStyles))
382 {
383 if (!pattern.selectors.some(s => s.requiresHiding))
384 {
385 selectors.push(selector);
386 selectorFilters.push(pattern.text);
387 }
388 else
389 {
390 for (let element of document.querySelectorAll(selector))
391 {
392 elements.push(element);
393 elementFilters.push(pattern.text);
394 }
395 }
396 }
397 }
398
399 this.addSelectorsFunc(selectors, selectorFilters);
400 this.hideElemsFunc(elements, elementFilters);
401 },
402
403 onLoad(event)
404 {
405 let stylesheet = event.target.sheet;
310 if (stylesheet) 406 if (stylesheet)
311 this.addSelectors([stylesheet]); 407 this.addSelectors([stylesheet]);
312 this.hideElements([stylesheet]); 408 },
313 }, 409
314 410 apply()
315 apply: function() 411 {
316 { 412 this.getFiltersFunc(patterns =>
317 this.getFiltersFunc(function(patterns) 413 {
318 { 414 let oldReportError = reportError;
319 this.propSelPatterns = []; 415 reportError = error => this.window.console.error(error);
320 this.pseudoHasPatterns = []; 416
321 for (var i = 0; i < patterns.length; i++) 417 this.patterns = [];
418 for (let pattern of patterns)
322 { 419 {
323 var pattern = patterns[i]; 420 let selectors = parseSelector(pattern.selector);
324 var parsed = parsePattern(pattern); 421 if (selectors != null && selectors.length > 0)
325 if (parsed == undefined) 422 this.patterns.push({selectors, text: pattern.text});
326 continue;
327 if (parsed.type == "props")
328 {
329 this.propSelPatterns.push(parsed);
330 }
331 else if (parsed.type == "has")
332 {
333 this.pseudoHasPatterns.push(parsed);
334 }
335 } 423 }
336 424
337 if (this.pseudoHasPatterns.length > 0 || this.propSelPatterns.length > 0) 425 if (this.patterns.length > 0)
338 { 426 {
339 var document = this.window.document; 427 let {document} = this.window;
340 this.addSelectors(document.styleSheets); 428 this.addSelectors(document.styleSheets);
341 this.hideElements(document.styleSheets);
342 document.addEventListener("load", this.onLoad.bind(this), true); 429 document.addEventListener("load", this.onLoad.bind(this), true);
343 } 430 }
344 }.bind(this)); 431 reportError = oldReportError;
432 });
345 } 433 }
346 }; 434 };
LEFTRIGHT

Powered by Google App Engine
This is Rietveld