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

Powered by Google App Engine
This is Rietveld