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

Side by Side Diff: chrome/content/elemHideEmulation.js

Issue 29383960: Issue 3143 - Filter elements with :-abp-has() (Closed) Base URL: https://hg.adblockplus.org/adblockpluscore
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:
View unified diff | Download patch
« no previous file with comments | « chrome/content/.eslintrc.json ('k') | test/browser/elemHideEmulation.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
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 const abpSelectorRegexp = /:-abp-([\w-]+)\(/i; 22 const abpSelectorRegexp = /:-abp-([\w-]+)\(/i;
23 23
24 let reportError = () => {};
25
24 function splitSelector(selector) 26 function splitSelector(selector)
25 { 27 {
26 if (selector.indexOf(",") == -1) 28 if (selector.indexOf(",") == -1)
27 return [selector]; 29 return [selector];
28 30
29 let selectors = []; 31 let selectors = [];
30 let start = 0; 32 let start = 0;
31 let level = 0; 33 let level = 0;
32 let sep = ""; 34 let sep = "";
33 35
(...skipping 18 matching lines...) Expand all
52 selectors.push(selector.substring(start, i)); 54 selectors.push(selector.substring(start, i));
53 start = i + 1; 55 start = i + 1;
54 } 56 }
55 } 57 }
56 } 58 }
57 59
58 selectors.push(selector.substring(start)); 60 selectors.push(selector.substring(start));
59 return selectors; 61 return selectors;
60 } 62 }
61 63
62 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc) 64 /** Return position of node from parent.
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 */
68 function positionInParent(node)
69 {
70 let {children} = node.parentNode;
71 for (let i = 0; i < children.length; i++)
72 if (children[i] == node)
73 return i + 1;
74 return 0;
75 }
76
77 function makeSelector(node, selector)
78 {
79 if (!node.parentElement)
80 {
81 let newSelector = ":root";
82 if (selector)
83 newSelector += " > " + selector;
84 return newSelector;
85 }
86 let idx = positionInParent(node);
87 if (idx > 0)
88 {
89 let newSelector = `${node.tagName}:nth-child(${idx})`;
90 if (selector)
91 newSelector += " > " + selector;
92 return makeSelector(node.parentElement, newSelector);
93 }
94
95 return selector;
96 }
97
98 function parseSelectorContent(content, startIndex)
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)
294 {
295 let regexpString;
296 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" &&
297 propertyExpression[propertyExpression.length - 1] == "/")
298 {
299 regexpString = propertyExpression.slice(1, -1)
300 .replace("\\x7B ", "{").replace("\\x7D ", "}");
301 }
302 else
303 regexpString = filterToRegExp(propertyExpression);
304
305 this._regexp = new RegExp(regexpString, "i");
306 }
307
308 PropsSelector.prototype = {
309 *findPropsSelectors(styles, prefix, regexp)
310 {
311 for (let style of styles)
312 if (regexp.test(style.style))
313 for (let subSelector of style.subSelectors)
314 yield prefix + subSelector;
315 },
316
317 *getSelectors(prefix, subtree, styles)
318 {
319 for (let selector of this.findPropsSelectors(styles, prefix, this._regexp))
320 yield [selector, subtree];
321 }
322 };
323
324 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc,
325 hideElemsFunc)
63 { 326 {
64 this.window = window; 327 this.window = window;
65 this.getFiltersFunc = getFiltersFunc; 328 this.getFiltersFunc = getFiltersFunc;
66 this.addSelectorsFunc = addSelectorsFunc; 329 this.addSelectorsFunc = addSelectorsFunc;
330 this.hideElemsFunc = hideElemsFunc;
67 } 331 }
68 332
69 ElemHideEmulation.prototype = { 333 ElemHideEmulation.prototype = {
70 stringifyStyle(style)
71 {
72 let styles = [];
73 for (let i = 0; i < style.length; i++)
74 {
75 let property = style.item(i);
76 let value = style.getPropertyValue(property);
77 let priority = style.getPropertyPriority(property);
78 styles.push(property + ": " + value + (priority ? " !" + priority : "") +
79 ";");
80 }
81 styles.sort();
82 return styles.join(" ");
83 },
84
85 isSameOrigin(stylesheet) 334 isSameOrigin(stylesheet)
86 { 335 {
87 try 336 try
88 { 337 {
89 return new URL(stylesheet.href).origin == this.window.location.origin; 338 return new URL(stylesheet.href).origin == this.window.location.origin;
90 } 339 }
91 catch (e) 340 catch (e)
92 { 341 {
93 // Invalid URL, assume that it is first-party. 342 // Invalid URL, assume that it is first-party.
94 return true; 343 return true;
95 } 344 }
96 }, 345 },
97 346
98 findSelectors(stylesheet, selectors, filters) 347 addSelectors(stylesheets)
99 { 348 {
100 // Explicitly ignore third-party stylesheets to ensure consistent behavior 349 let selectors = [];
101 // between Firefox and Chrome. 350 let selectorFilters = [];
102 if (!this.isSameOrigin(stylesheet)) 351
103 return; 352 let elements = [];
104 353 let elementFilters = [];
105 let rules = stylesheet.cssRules; 354
106 if (!rules) 355 let cssStyles = [];
107 return; 356
108 357 for (let stylesheet of stylesheets)
109 for (let rule of rules) 358 {
110 { 359 // Explicitly ignore third-party stylesheets to ensure consistent behavior
111 if (rule.type != rule.STYLE_RULE) 360 // between Firefox and Chrome.
361 if (!this.isSameOrigin(stylesheet))
112 continue; 362 continue;
113 363
114 let style = this.stringifyStyle(rule.style); 364 let rules = stylesheet.cssRules;
115 for (let pattern of this.patterns) 365 if (!rules)
366 continue;
367
368 for (let rule of rules)
116 { 369 {
117 if (pattern.regexp.test(style)) 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))
118 { 384 {
119 let subSelectors = splitSelector(rule.selectorText); 385 selectors.push(selector);
120 for (let subSelector of subSelectors) 386 selectorFilters.push(pattern.text);
387 }
388 else
389 {
390 for (let element of document.querySelectorAll(selector))
121 { 391 {
122 selectors.push(pattern.prefix + subSelector + pattern.suffix); 392 elements.push(element);
123 filters.push(pattern.text); 393 elementFilters.push(pattern.text);
124 } 394 }
125 } 395 }
126 } 396 }
127 } 397 }
128 }, 398
129 399 this.addSelectorsFunc(selectors, selectorFilters);
130 addSelectors(stylesheets) 400 this.hideElemsFunc(elements, elementFilters);
131 {
132 let selectors = [];
133 let filters = [];
134 for (let stylesheet of stylesheets)
135 this.findSelectors(stylesheet, selectors, filters);
136 this.addSelectorsFunc(selectors, filters);
137 }, 401 },
138 402
139 onLoad(event) 403 onLoad(event)
140 { 404 {
141 let stylesheet = event.target.sheet; 405 let stylesheet = event.target.sheet;
142 if (stylesheet) 406 if (stylesheet)
143 this.addSelectors([stylesheet]); 407 this.addSelectors([stylesheet]);
144 }, 408 },
145 409
146 apply() 410 apply()
147 { 411 {
148 this.getFiltersFunc(patterns => 412 this.getFiltersFunc(patterns =>
149 { 413 {
414 let oldReportError = reportError;
415 reportError = error => this.window.console.error(error);
416
150 this.patterns = []; 417 this.patterns = [];
151 for (let pattern of patterns) 418 for (let pattern of patterns)
152 { 419 {
153 let match = abpSelectorRegexp.exec(pattern.selector); 420 let selectors = parseSelector(pattern.selector);
154 if (!match || match[1] != "properties") 421 if (selectors != null && selectors.length > 0)
155 { 422 this.patterns.push({selectors, text: pattern.text});
156 console.error(new SyntaxError(
157 `Failed to parse Adblock Plus selector ${pattern.selector}, ` +
158 `invalid pseudo-class :-abp-${match[1]}().`
159 ));
160 continue;
161 }
162
163 let expressionStart = match.index + match[0].length;
164 let parens = 1;
165 let quote = null;
166 let i;
167 for (i = expressionStart; i < pattern.selector.length; i++)
168 {
169 let c = pattern.selector[i];
170 if (c == "\\")
171 {
172 // Ignore escaped characters
173 i++;
174 }
175 else if (quote)
176 {
177 if (c == quote)
178 quote = null;
179 }
180 else if (c == "'" || c == '"')
181 quote = c;
182 else if (c == "(")
183 parens++;
184 else if (c == ")")
185 {
186 parens--;
187 if (parens == 0)
188 break;
189 }
190 }
191
192 if (parens > 0)
193 {
194 console.error(new SyntaxError(
195 `Failed to parse Adblock Plus selector ${pattern.selector} ` +
196 "due to unmatched parentheses."
197 ));
198 continue;
199 }
200
201 let propertyExpression = pattern.selector.substring(expressionStart, i);
202 let regexpString;
203 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" &&
204 propertyExpression[propertyExpression.length - 1] == "/")
205 {
206 regexpString = propertyExpression.slice(1, -1)
207 .replace("\\x7B ", "{").replace("\\x7D ", "}");
208 }
209 else
210 regexpString = filterToRegExp(propertyExpression);
211
212 this.patterns.push({
213 text: pattern.text,
214 regexp: new RegExp(regexpString, "i"),
215 prefix: pattern.selector.substr(0, match.index),
216 suffix: pattern.selector.substr(i + 1)
217 });
218 } 423 }
219 424
220 if (this.patterns.length > 0) 425 if (this.patterns.length > 0)
221 { 426 {
222 let {document} = this.window; 427 let {document} = this.window;
223 this.addSelectors(document.styleSheets); 428 this.addSelectors(document.styleSheets);
224 document.addEventListener("load", this.onLoad.bind(this), true); 429 document.addEventListener("load", this.onLoad.bind(this), true);
225 } 430 }
431 reportError = oldReportError;
226 }); 432 });
227 } 433 }
228 }; 434 };
OLDNEW
« no previous file with comments | « chrome/content/.eslintrc.json ('k') | test/browser/elemHideEmulation.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld