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: Revised patch Created June 8, 2017, 3:45 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 | « no previous file | 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
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
52 selectors.push(selector.substring(start, i)); 52 selectors.push(selector.substring(start, i));
53 start = i + 1; 53 start = i + 1;
54 } 54 }
55 } 55 }
56 } 56 }
57 57
58 selectors.push(selector.substring(start)); 58 selectors.push(selector.substring(start));
59 return selectors; 59 return selectors;
60 } 60 }
61 61
62 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc) 62 /** Return position of node from parent.
63 * @param {Node} node the node to find the position of.
64 * @return {number} One-based index like for :nth-child(), or 0 on error.
65 */
66 function positionInParent(node)
67 {
68 let {children} = node.parentNode;
69 for (let i = 0; i < children.length; i++)
70 if (children[i] == node)
71 return i + 1;
72 return 0;
73 }
74
75 function makeSelector(node, selector)
76 {
77 if (!node.parentElement)
78 {
79 let newSelector = ":root";
80 if (selector)
81 newSelector += " > " + selector;
82 return newSelector;
83 }
84 let idx = positionInParent(node);
85 if (idx > 0)
86 {
87 let newSelector = `${node.tagName}:nth-child(${idx})`;
88 if (selector)
89 newSelector += " > " + selector;
90 return makeSelector(node.parentElement, newSelector);
91 }
92
93 return selector;
94 }
95
96 function parseSelectorContent(content, startIndex)
97 {
98 let parens = 1;
99 let quote = null;
100 let i = startIndex;
101 for (; i < content.length; i++)
102 {
103 let c = content[i];
104 if (c == "\\")
105 {
106 // Ignore escaped characters
107 i++;
108 }
109 else if (quote)
110 {
111 if (c == quote)
112 quote = null;
113 }
114 else if (c == "'" || c == '"')
115 quote = c;
116 else if (c == "(")
117 parens++;
118 else if (c == ")")
119 {
120 parens--;
121 if (parens == 0)
122 break;
123 }
124 }
125
126 if (parens > 0)
127 return null;
128 return {text: content.substring(startIndex, i), end: i};
129 }
130
131 /** Parse the selector
132 * @param {string} selector the selector to parse
133 * @return {Object} selectors is an array of objects,
134 * or null in case of errors. hide is true if we'll hide
135 * elements instead of styles..
136 */
137 function parseSelector(selector)
138 {
139 if (selector.length == 0)
140 return [];
141
142 let match = abpSelectorRegexp.exec(selector);
143 if (!match)
144 return [new PlainSelector(selector)];
145
146 let selectors = [];
147 if (match.index > 0)
148 selectors.push(new PlainSelector(selector.substr(0, match.index)));
149
150 let startIndex = match.index + match[0].length;
151 let content = parseSelectorContent(selector, startIndex);
152 if (!content)
153 {
154 console.error(new SyntaxError("Failed parsing content filter " +
155 `selector ${selector}, didn't ` +
156 "find closing parenthesis."));
157 return null;
158 }
159 if (match[1] == "properties")
160 selectors.push(new PropsSelector(content.text));
161 else if (match[1] == "has")
162 {
163 let hasSelector = new HasSelector(content.text);
164 if (!hasSelector.valid())
165 return null;
166 selectors.push(hasSelector);
167 }
168 else
169 {
170 // this is an error, can't parse selector.
171 console.error(new SyntaxError("Failed parsing content filter " +
172 `selector ${selector}, invalid ` +
173 `pseudo-class -abp-${match[1]}().`));
174 return null;
175 }
176
177 let suffix = parseSelector(selector.substr(content.end + 1));
178 if (suffix == null)
179 return null;
180
181 selectors.push(...suffix);
182
183 return selectors;
184 }
185
186 /** Stringified style objects
187 * @typedef {Object} StringifiedStyle
188 * @property {string} style CSS style represented by a string.
189 * @property {string[]} subSelectors selectors the CSS properties apply to.
190 */
191
192 /**
193 * Stringify a CSS style rule object.
194 * @param {CSSStyleRule} rule the CSS style rule.
195 * @return {StringifiedStyle} the stringified style.
196 */
197 function stringifyStyle(rule)
198 {
199 let styles = [];
200 for (let i = 0; i < rule.style.length; i++)
201 {
202 let property = rule.style.item(i);
203 let value = rule.style.getPropertyValue(property);
204 let priority = rule.style.getPropertyPriority(property);
205 styles.push(`${property}: ${value}${priority ? " !" + priority : ""};`);
206 }
207 styles.sort();
208 return {
209 style: styles.join(" "),
210 subSelectors: splitSelector(rule.selectorText)
211 };
212 }
213
214 function* evaluate(chain, index, prefix, subtree, styles)
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, styles))
223 yield* evaluate(chain, index + 1, selector, element, styles);
224 }
225
226 function PlainSelector(selector)
227 {
228 this._selector = selector;
229 }
230
231 PlainSelector.prototype = {
232 /**
233 * Generator function returning a pair of selector
234 * string and subtree.
235 * @param {string} prefix the prefix for the selector.
236 * @param {Node} subtree the subtree we work on.
237 * @param {StringifiedStyle[]} styles the stringified style objects.
238 */
239 *getSelectors(prefix, subtree, styles)
240 {
241 yield [prefix + this._selector, subtree];
242 }
243 };
244
245 const incompletePrefixRegexp = /[\s>+~]$/;
246
247 function HasSelector(selector)
248 {
249 this._innerSelectors = parseSelector(selector);
250 }
251
252 HasSelector.prototype = {
253 requiresHiding: true,
254
255 valid()
256 {
257 return this._innerSelectors != null;
258 },
259
260 *getSelectors(prefix, subtree, styles)
261 {
262 for (let element of this.getElements(prefix, subtree, styles))
263 yield [makeSelector(element, ""), element];
264 },
265
266 /**
267 * Generator function returning selected elements.
268 * @param {string} prefix the prefix for the selector.
269 * @param {Node} subtree the subtree we work on.
270 * @param {StringifiedStyle[]} styles the stringified style objects.
271 */
272 *getElements(prefix, subtree, styles)
273 {
274 let actualPrefix = (!prefix || incompletePrefixRegexp.test(prefix)) ?
275 prefix + "*" : prefix;
276 let elements = subtree.querySelectorAll(actualPrefix);
277 for (let element of elements)
278 {
279 let newPrefix = makeSelector(element, "");
280 let iter = evaluate(this._innerSelectors, 0, newPrefix + " ",
281 element, styles);
282 for (let selector of iter)
283 // we insert a space between the two. It becomes a no-op if selector
284 // doesn't have a combinator
285 if (subtree.querySelector(selector))
286 yield element;
287 }
288 }
289 };
290
291 function PropsSelector(propertyExpression)
292 {
293 let regexpString;
294 if (propertyExpression.length >= 2 && propertyExpression[0] == "/" &&
295 propertyExpression[propertyExpression.length - 1] == "/")
296 {
297 regexpString = propertyExpression.slice(1, -1)
298 .replace("\\x7B ", "{").replace("\\x7D ", "}");
299 }
300 else
301 regexpString = filterToRegExp(propertyExpression);
302
303 this._regexp = new RegExp(regexpString, "i");
304 }
305
306 PropsSelector.prototype = {
307 *findPropsSelectors(styles, prefix, regexp)
308 {
309 for (let style of styles)
310 if (regexp.test(style.style))
311 for (let subSelector of style.subSelectors)
312 yield prefix + subSelector;
313 },
314
315 *getSelectors(prefix, subtree, styles)
316 {
317 for (let selector of this.findPropsSelectors(styles, prefix, this._regexp))
318 yield [selector, subtree];
319 }
320 };
321
322 function ElemHideEmulation(window, getFiltersFunc, addSelectorsFunc,
323 hideElemsFunc)
63 { 324 {
64 this.window = window; 325 this.window = window;
65 this.getFiltersFunc = getFiltersFunc; 326 this.getFiltersFunc = getFiltersFunc;
66 this.addSelectorsFunc = addSelectorsFunc; 327 this.addSelectorsFunc = addSelectorsFunc;
328 this.hideElemsFunc = hideElemsFunc;
67 } 329 }
68 330
69 ElemHideEmulation.prototype = { 331 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) 332 isSameOrigin(stylesheet)
86 { 333 {
87 try 334 try
88 { 335 {
89 return new URL(stylesheet.href).origin == this.window.location.origin; 336 return new URL(stylesheet.href).origin == this.window.location.origin;
90 } 337 }
91 catch (e) 338 catch (e)
92 { 339 {
93 // Invalid URL, assume that it is first-party. 340 // Invalid URL, assume that it is first-party.
94 return true; 341 return true;
95 } 342 }
96 }, 343 },
97 344
98 findSelectors(stylesheet, selectors, filters) 345 addSelectors(stylesheets)
99 { 346 {
100 // Explicitly ignore third-party stylesheets to ensure consistent behavior 347 let selectors = [];
101 // between Firefox and Chrome. 348 let selectorFilters = [];
102 if (!this.isSameOrigin(stylesheet)) 349
103 return; 350 let elements = [];
104 351 let elementFilters = [];
105 let rules = stylesheet.cssRules; 352
106 if (!rules) 353 let cssStyles = [];
107 return; 354
108 355 for (let stylesheet of stylesheets)
109 for (let rule of rules) 356 {
110 { 357 // Explicitly ignore third-party stylesheets to ensure consistent behavior
111 if (rule.type != rule.STYLE_RULE) 358 // between Firefox and Chrome.
359 if (!this.isSameOrigin(stylesheet))
112 continue; 360 continue;
113 361
114 let style = this.stringifyStyle(rule.style); 362 let rules = stylesheet.cssRules;
115 for (let pattern of this.patterns) 363 if (!rules)
364 continue;
365
366 for (let rule of rules)
116 { 367 {
117 if (pattern.regexp.test(style)) 368 if (rule.type != rule.STYLE_RULE)
369 continue;
370
371 cssStyles.push(stringifyStyle(rule));
372 }
373 }
374
375 for (let pattern of this.patterns)
376 {
377 for (let selector of evaluate(pattern.selectors,
378 0, "", document, cssStyles))
379 {
380 if (!pattern.selectors.some(s => s.requiresHiding))
118 { 381 {
119 let subSelectors = splitSelector(rule.selectorText); 382 selectors.push(selector);
120 for (let subSelector of subSelectors) 383 selectorFilters.push(pattern.text);
384 }
385 else
386 {
387 for (let element of document.querySelectorAll(selector))
121 { 388 {
122 selectors.push(pattern.prefix + subSelector + pattern.suffix); 389 elements.push(element);
123 filters.push(pattern.text); 390 elementFilters.push(pattern.text);
124 } 391 }
125 } 392 }
126 } 393 }
127 } 394 }
128 }, 395
129 396 this.addSelectorsFunc(selectors, selectorFilters);
130 addSelectors(stylesheets) 397 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 }, 398 },
138 399
139 onLoad(event) 400 onLoad(event)
140 { 401 {
141 let stylesheet = event.target.sheet; 402 let stylesheet = event.target.sheet;
142 if (stylesheet) 403 if (stylesheet)
143 this.addSelectors([stylesheet]); 404 this.addSelectors([stylesheet]);
144 }, 405 },
145 406
146 apply() 407 apply()
147 { 408 {
148 this.getFiltersFunc(patterns => 409 this.getFiltersFunc(patterns =>
149 { 410 {
150 this.patterns = []; 411 this.patterns = [];
151 for (let pattern of patterns) 412 for (let pattern of patterns)
152 { 413 {
153 let match = abpSelectorRegexp.exec(pattern.selector); 414 let selectors = parseSelector(pattern.selector);
154 if (!match || match[1] != "properties") 415 if (selectors != null && selectors.length > 0)
155 { 416 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 } 417 }
219 418
220 if (this.patterns.length > 0) 419 if (this.patterns.length > 0)
221 { 420 {
222 let {document} = this.window; 421 let {document} = this.window;
223 this.addSelectors(document.styleSheets); 422 this.addSelectors(document.styleSheets);
224 document.addEventListener("load", this.onLoad.bind(this), true); 423 document.addEventListener("load", this.onLoad.bind(this), true);
225 } 424 }
226 }); 425 });
227 } 426 }
228 }; 427 };
OLDNEW
« no previous file with comments | « no previous file | test/browser/elemHideEmulation.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld