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: Reworked the pseudo class to generate selectors. Created May 3, 2017, 1:42 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 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2017 eyeo GmbH 3 * Copyright (C) 2006-2017 eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 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 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 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/>. 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */ 16 */
17 17
18 /* globals filterToRegExp */ 18 /* globals filterToRegExp */
19 19
20 "use strict"; 20 "use strict";
21 21
22 let pseudoClassHasSelectorRegExp = /:-abp-has\((.*)\)/; 22 const abpSelectorRegexp = /:-abp-([\w-]+)\(/i;
23 let pseudoClassPropsSelectorRegExp = /:-abp-properties\((["'])([^"']+)\1\)/; 23
24 let reportError = () => {};
24 25
25 function splitSelector(selector) 26 function splitSelector(selector)
26 { 27 {
27 if (selector.indexOf(",") == -1) 28 if (selector.indexOf(",") == -1)
28 return [selector]; 29 return [selector];
29 30
30 let selectors = []; 31 let selectors = [];
31 let start = 0; 32 let start = 0;
32 let level = 0; 33 let level = 0;
33 let sep = ""; 34 let sep = "";
(...skipping 19 matching lines...) Expand all
53 selectors.push(selector.substring(start, i)); 54 selectors.push(selector.substring(start, i));
54 start = i + 1; 55 start = i + 1;
55 } 56 }
56 } 57 }
57 } 58 }
58 59
59 selectors.push(selector.substring(start)); 60 selectors.push(selector.substring(start));
60 return selectors; 61 return selectors;
61 } 62 }
62 63
63 // Return position of node from parent. 64 /** Return position of node from parent.
64 // 1 base index like for :nth-child() 65 * @param {Node} node the node to find the position of.
66 * @return {number} One-based index like for :nth-child(), or 0 on error.
67 */
65 function positionInParent(node) 68 function positionInParent(node)
66 { 69 {
67 let parentNode = node ? node.parentNode : null; 70 let {children} = node.parentNode;
68 if (parentNode == null) 71 for (let i = 0; i < children.length; i++)
69 return 0;
70
71 let {children} = parentNode;
72 if (!children)
73 return 0;
74 let i = 0;
75 for (i = 0; i < children.length; i++)
76 if (children[i] == node) 72 if (children[i] == node)
77 break; 73 return i + 1;
78 return i + 1; 74 return 0;
79 } 75 }
80 76
81 function makeSelector(node, selector) 77 function makeSelector(node, selector)
82 { 78 {
83 if (node && node.id && node.id != "") 79 if (!node.parentElement)
84 { 80 {
85 let newSelector = "#" + node.id; 81 let newSelector = ":root";
86 if (selector != "") 82 if (selector)
87 newSelector += " > "; 83 newSelector += " > " + selector;
88 return newSelector + selector; 84 return newSelector;
89 } 85 }
90 let idx = positionInParent(node); 86 let idx = positionInParent(node);
91 if (idx > 0) 87 if (idx > 0)
92 { 88 {
93 let newSelector = `${node.tagName}:nth-child(${idx}) `; 89 let newSelector = `${node.tagName}:nth-child(${idx})`;
94 if (selector != "") 90 if (selector)
95 newSelector += "> "; 91 newSelector += " > " + selector;
96 return makeSelector(node.parentNode, newSelector + selector); 92 return makeSelector(node.parentElement, newSelector);
97 } 93 }
98 94
99 return selector; 95 return selector;
100 } 96 }
101 97
102 // return the regexString for the properties 98 function parseSelectorContent(content, startIndex)
103 function parsePropSelPattern(propertyExpression) 99 {
100 let parens = 1;
101 let quote = null;
102 let i = startIndex;
103 for (; i < content.length; i++)
104 {
105 let c = content[i];
106 if (c == "\\")
107 {
108 // Ignore escaped characters
109 i++;
110 }
111 else if (quote)
112 {
113 if (c == quote)
114 quote = null;
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)
104 { 294 {
105 let regexpString; 295 let regexpString;
106 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" && 296 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" &&
107 propertyExpression[propertyExpression.length - 1] == "/") 297 propertyExpression[propertyExpression.length - 1] == "/")
298 {
108 regexpString = propertyExpression.slice(1, -1) 299 regexpString = propertyExpression.slice(1, -1)
109 .replace("\\x7B ", "{").replace("\\x7D ", "}"); 300 .replace("\\x7B ", "{").replace("\\x7D ", "}");
301 }
110 else 302 else
111 regexpString = filterToRegExp(propertyExpression); 303 regexpString = filterToRegExp(propertyExpression);
112 return regexpString; 304
113 } 305 this._regexp = new RegExp(regexpString, "i");
114 306 }
115 function parseSelector(selector) 307
116 { 308 PropsSelector.prototype = {
117 if (selector.length == 0) 309 *findPropsSelectors(styles, prefix, regexp)
118 return []; 310 {
119 311 for (let style of styles)
120 let abpSelectorIndex = selector.indexOf(":-abp-"); 312 if (regexp.test(style.style))
121 if (abpSelectorIndex == -1) 313 for (let subSelector of style.subSelectors)
122 return [new PlainSelector(selector)]; 314 yield prefix + subSelector;
123 315 },
124 let selectors = []; 316
125 317 *getSelectors(prefix, subtree, styles)
126 let match = pseudoClassHasSelectorRegExp.exec(selector); 318 {
127 if (match) 319 for (let selector of this.findPropsSelectors(styles, prefix, this._regexp))
128 { 320 yield [selector, subtree];
129 selectors.push(...parseSelector(selector.substr(0, match.index)));
130 selectors.push(new HasSelector(match[1]));
131 selectors.push(...parseSelector(selector.substr(match.index +
132 match[0].length)));
133
134 return selectors;
135 }
136
137 match = pseudoClassPropsSelectorRegExp.exec(selector);
138 if (match)
139 {
140 selectors.push(...parseSelector(selector.substr(0, match.index)));
141 selectors.push(new PropsSelector(match[2]));
142 selectors.push(...parseSelector(selector.substr(match.index +
143 match[0].length)));
144
145 return selectors;
146 }
147
148 selectors.push(new PlainSelector(selector));
149 return selectors;
150 }
151
152 function matchStyleProps(style, rule, pattern, selectors, filters)
153 {
154 if (pattern.regexp.test(style))
155 {
156 let subSelectors = splitSelector(rule.selectorText);
157 for (let i = 0; i < subSelectors.length; i++)
158 {
159 let subSelector = subSelectors[i];
160 selectors.push(pattern.prefix + subSelector + pattern.suffix);
161 filters.push(pattern.text);
162 }
163 }
164 }
165
166 function findPropsSelectors(stylesheet, pattern, selectors, filters)
167 {
168 let rules = stylesheet.cssRules;
169 if (!rules)
170 return;
171
172 for (let rule of rules)
173 {
174 if (rule.type != rule.STYLE_RULE)
175 continue;
176
177 let style = stringifyStyle(rule.style);
178 matchStyleProps(style, rule, pattern, selectors, filters);
179 }
180 }
181
182 function stringifyStyle(style)
183 {
184 let styles = [];
185 for (let i = 0; i < style.length; i++)
186 {
187 let property = style.item(i);
188 let value = style.getPropertyValue(property);
189 let priority = style.getPropertyPriority(property);
190 styles.push(property + ": " + value + (priority ? " !" + priority : "") +
191 ";");
192 }
193 styles.sort();
194 return styles.join(" ");
195 }
196
197 function* evaluate(chain, index, prefix, subtree, stylesheet)
198 {
199 if (index >= chain.length)
200 {
201 yield prefix;
202 return;
203 }
204 for (let [selector, element] of
205 chain[index].getSelectors(prefix, subtree, stylesheet))
206 yield* evaluate(chain, index + 1, selector, element, stylesheet);
207 }
208
209 /*
210 * getSelector() is a generator function returning a pair of selector
211 * string and subtree.
212 * getElements() is a generator function returning elements selected.
213 */
214 function PlainSelector(selector)
215 {
216 this._selector = selector;
217 }
218
219 PlainSelector.prototype = {
220 *getSelectors(prefix, subtree, stylesheet)
221 {
222 yield [prefix + this._selector, subtree];
223 },
224
225 *getElements(prefix, subtree, stylesheet)
226 {
227 for (let selector of this.getSelectors(prefix, subtree, stylesheet))
228 for (let element of subtree.querySelectorAll(selector[0]))
229 yield element;
230 } 321 }
231 }; 322 };
232 323
233 function HasSelector(selector) 324 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc,
234 { 325 hideElemsFunc)
235 this._innerSelectors = parseSelector(selector);
236 }
237
238 HasSelector.prototype = {
239 *getSelectors(prefix, subtree, stylesheet)
240 {
241 for (let element of this.getElements(prefix, subtree, stylesheet))
242 {
243 let selector = makeSelector(element, "");
244 yield [prefix + selector, subtree];
245 }
246 },
247
248 *getElements(prefix, subtree, stylesheet)
249 {
250 let elements = subtree.querySelectorAll(prefix ? prefix : "*");
251 for (let element of elements)
252 {
253 let newPrefix = makeSelector(element, "");
254 let iter = evaluate(this._innerSelectors, 0, "", element, stylesheet);
255 for (let selector of iter) {
256 // we insert a space between the two. It becomes a no-op if selector
257 // doesn't have a combinator
258 if (subtree.querySelector(newPrefix + " " + selector))
259 yield element;
260 }
261 }
262 }
263 };
264
265 function PropsSelector(selector)
266 {
267 this._regexp = new RegExp(parsePropSelPattern(selector), "i");
268 }
269
270 PropsSelector.prototype = {
271 *getSelectors(prefix, subtree, stylesheet)
272 {
273 let selectors = [];
274 let filters = [];
275 let selPattern = {
276 prefix,
277 suffix: "",
278 regexp: this._regexp
279 };
280
281 findPropsSelectors(stylesheet, selPattern, selectors, filters);
282 for (let selector of selectors)
283 yield [selector, subtree];
284 },
285
286 *getElements(prefix, subtree, stylesheet)
287 {
288 for (let [selector, element] of
289 this.getSelectors(prefix, subtree, stylesheet))
290 {
291 for (let subElement of element.querySelectorAll(selector))
292 yield subElement;
293 }
294 }
295 };
296
297 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc)
298 { 326 {
299 this.window = window; 327 this.window = window;
300 this.getFiltersFunc = getFiltersFunc; 328 this.getFiltersFunc = getFiltersFunc;
301 this.addSelectorsFunc = addSelectorsFunc; 329 this.addSelectorsFunc = addSelectorsFunc;
330 this.hideElemsFunc = hideElemsFunc;
302 } 331 }
303 332
304 ElemHideEmulation.prototype = { 333 ElemHideEmulation.prototype = {
305
306 isSameOrigin(stylesheet) 334 isSameOrigin(stylesheet)
307 { 335 {
308 try 336 try
309 { 337 {
310 return new URL(stylesheet.href).origin == this.window.location.origin; 338 return new URL(stylesheet.href).origin == this.window.location.origin;
311 } 339 }
312 catch (e) 340 catch (e)
313 { 341 {
314 // Invalid URL, assume that it is first-party. 342 // Invalid URL, assume that it is first-party.
315 return true; 343 return true;
316 } 344 }
317 }, 345 },
318 346
319 addSelectors(stylesheet) 347 addSelectors(stylesheets)
320 { 348 {
321 let selectors = []; 349 let selectors = [];
322 let filters = []; 350 let selectorFilters = [];
323 351
324 // Explicitly ignore third-party stylesheets to ensure consistent behavior 352 let elements = [];
325 // between Firefox and Chrome. 353 let elementFilters = [];
326 if (!this.isSameOrigin(stylesheet)) 354
327 return; 355 let cssStyles = [];
328 356
329 for (let patterns of this.selPatterns) 357 for (let stylesheet of stylesheets)
330 selectors.push(...evaluate(patterns, 0, "", document, stylesheet)); 358 {
331 359 // Explicitly ignore third-party stylesheets to ensure consistent behavior
332 this.addSelectorsFunc(selectors, filters); 360 // between Firefox and Chrome.
361 if (!this.isSameOrigin(stylesheet))
362 continue;
363
364 let rules = stylesheet.cssRules;
365 if (!rules)
366 continue;
367
368 for (let rule of rules)
369 {
370 if (rule.type != rule.STYLE_RULE)
371 continue;
372
373 cssStyles.push(stringifyStyle(rule));
374 }
375 }
376
377 let {document} = this.window;
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);
333 }, 401 },
334 402
335 onLoad(event) 403 onLoad(event)
336 { 404 {
337 let stylesheet = event.target.sheet; 405 let stylesheet = event.target.sheet;
338 if (stylesheet) 406 if (stylesheet)
339 this.addSelectors(stylesheet); 407 this.addSelectors([stylesheet]);
340 }, 408 },
341 409
342 apply() 410 apply()
343 { 411 {
344 this.getFiltersFunc(patterns => 412 this.getFiltersFunc(patterns =>
345 { 413 {
346 this.selPatterns = []; 414 let oldReportError = reportError;
347 415 reportError = error => this.window.console.error(error);
416
417 this.patterns = [];
348 for (let pattern of patterns) 418 for (let pattern of patterns)
349 { 419 {
350 let selectors = parseSelector(pattern.selector); 420 let selectors = parseSelector(pattern.selector);
351 if (selectors.length > 0) 421 if (selectors != null && selectors.length > 0)
352 this.selPatterns.push(selectors); 422 this.patterns.push({selectors, text: pattern.text});
353 } 423 }
354 424
355 if (this.selPatterns.length > 0) 425 if (this.patterns.length > 0)
356 { 426 {
357 let {document} = this.window; 427 let {document} = this.window;
358 for (let stylesheet of document.styleSheets) 428 this.addSelectors(document.styleSheets);
359 this.addSelectors(stylesheet);
360 document.addEventListener("load", this.onLoad.bind(this), true); 429 document.addEventListener("load", this.onLoad.bind(this), true);
361 } 430 }
431 reportError = oldReportError;
362 }); 432 });
363 } 433 }
364 }; 434 };
LEFTRIGHT

Powered by Google App Engine
This is Rietveld