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

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

Issue 29559743: Issue 5650 - Apply emulation filters to shadow DOMs Base URL: https://hg.adblockplus.org/adblockpluscore/
Patch Set: Terminate loop Created Oct. 19, 2017, 2:13 a.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-present eyeo GmbH 3 * Copyright (C) 2006-present 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 22 matching lines...) Expand all
33 for (let i = 0; i < children.length; i++) 33 for (let i = 0; i < children.length; i++)
34 if (children[i] == node) 34 if (children[i] == node)
35 return i + 1; 35 return i + 1;
36 return 0; 36 return 0;
37 } 37 }
38 38
39 function makeSelector(node, selector) 39 function makeSelector(node, selector)
40 { 40 {
41 if (node == null) 41 if (node == null)
42 return null; 42 return null;
43 if (!node.parentElement) 43
44 // If this is the topmost element in a shadow DOM, climb up one more level
45 // and then use a ":host" prefix.
46 if (!node.parentElement && !(node.parentNode instanceof ShadowRoot))
44 { 47 {
45 let newSelector = ":root"; 48 let newSelector = node instanceof ShadowRoot ? ":host" : ":root";
46 if (selector) 49 if (selector)
47 newSelector += " > " + selector; 50 newSelector += " > " + selector;
48 return newSelector; 51 return newSelector;
49 } 52 }
50 let idx = positionInParent(node); 53 let idx = positionInParent(node);
51 if (idx > 0) 54 if (idx > 0)
52 { 55 {
53 let newSelector = `${node.tagName}:nth-child(${idx})`; 56 let newSelector = `${node.tagName}:nth-child(${idx})`;
54 if (selector) 57 if (selector)
55 newSelector += " > " + selector; 58 newSelector += " > " + selector;
56 return makeSelector(node.parentElement, newSelector); 59 return makeSelector(node.parentElement || node.parentNode, newSelector);
57 } 60 }
58 61
59 return selector; 62 return selector;
60 } 63 }
61 64
62 function parseSelectorContent(content, startIndex) 65 function parseSelectorContent(content, startIndex)
63 { 66 {
64 let parens = 1; 67 let parens = 1;
65 let quote = null; 68 let quote = null;
66 let i = startIndex; 69 let i = startIndex;
(...skipping 69 matching lines...) Expand 10 before | Expand all | Expand 10 after
136 yield null; 139 yield null;
137 else 140 else
138 yield* evaluate(chain, index + 1, selector, element, styles); 141 yield* evaluate(chain, index + 1, selector, element, styles);
139 } 142 }
140 // Just in case the getSelectors() generator above had to run some heavy 143 // Just in case the getSelectors() generator above had to run some heavy
141 // document.querySelectorAll() call which didn't produce any results, make 144 // document.querySelectorAll() call which didn't produce any results, make
142 // sure there is at least one point where execution can pause. 145 // sure there is at least one point where execution can pause.
143 yield null; 146 yield null;
144 } 147 }
145 148
149 function removeRedundantNodes(nodes)
150 {
151 let nodesInfo = [];
152 for (let node of nodes)
153 {
154 let nodeInfo = {node};
155 nodesInfo.push(nodeInfo);
156
157 let link = node;
158 while (link = link.parentNode)
159 {
160 // Since a node's ancestors are always added to the DOM before it, they
161 // will likely also appear before it in the list (at least on Chromium).
162 // If we encounter an ancestor here that has already been marked
163 // redundant, we can mark this node redundant too. This is an
164 // optimization that saves us having to do a lookup in the set and keep
165 // walking up the tree.
166 if (link.redundant || nodes.has(link))
167 {
168 nodeInfo.redundant = true;
169 break;
170 }
171 }
172 }
173
174 for (let nodeInfo of nodesInfo)
175 {
176 if (nodeInfo.redundant)
177 nodes.delete(nodeInfo.node);
178 }
179
180 return nodes;
181 }
182
183 function* traverse(nodes)
184 {
185 for (let node of nodes)
186 {
187 yield* traverse(node.children);
188 yield node;
189 }
190 }
191
192 function niceLoop(iterator, callback)
193 {
194 let loop = () =>
195 {
196 let cycleStart = performance.now();
197
198 for (let next = iterator.next(); !next.done; next = iterator.next())
199 {
200 callback(next.value);
201
202 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME)
203 {
204 setTimeout(loop, 0);
205 return;
206 }
207 }
208 };
209
210 loop();
211 }
212
146 function PlainSelector(selector) 213 function PlainSelector(selector)
147 { 214 {
148 this._selector = selector; 215 this._selector = selector;
149 } 216 }
150 217
151 PlainSelector.prototype = { 218 PlainSelector.prototype = {
152 /** 219 /**
153 * Generator function returning a pair of selector 220 * Generator function returning a pair of selector
154 * string and subtree. 221 * string and subtree.
155 * @param {string} prefix the prefix for the selector. 222 * @param {string} prefix the prefix for the selector.
(...skipping 139 matching lines...) Expand 10 before | Expand all | Expand 10 after
295 yield [selector, subtree]; 362 yield [selector, subtree];
296 } 363 }
297 }; 364 };
298 365
299 function isSelectorHidingOnlyPattern(pattern) 366 function isSelectorHidingOnlyPattern(pattern)
300 { 367 {
301 return pattern.selectors.some(s => s.preferHideWithSelector) && 368 return pattern.selectors.some(s => s.preferHideWithSelector) &&
302 !pattern.selectors.some(s => s.requiresHiding); 369 !pattern.selectors.some(s => s.requiresHiding);
303 } 370 }
304 371
305 function ElemHideEmulation(addSelectorsFunc, hideElemsFunc) 372 function ElemHideEmulation(document, root, addSelectorsFunc, hideElemsFunc)
306 { 373 {
307 this.document = document; 374 this.document = document;
375 this.root = root || document;
308 this.addSelectorsFunc = addSelectorsFunc; 376 this.addSelectorsFunc = addSelectorsFunc;
309 this.hideElemsFunc = hideElemsFunc; 377 this.hideElemsFunc = hideElemsFunc;
378 this.patterns = [];
310 this.observer = new MutationObserver(this.observe.bind(this)); 379 this.observer = new MutationObserver(this.observe.bind(this));
380 this.shadowEmulations = new WeakMap();
381
382 if (this.root == this.document)
383 {
384 this.document.addEventListener("load", this.onLoad.bind(this), true);
385 this.document.addEventListener("shadowAttached",
386 this.onShadowAttached.bind(this), true);
387 }
311 } 388 }
312 389
313 ElemHideEmulation.prototype = { 390 ElemHideEmulation.prototype = {
314 isSameOrigin(stylesheet) 391 isSameOrigin(stylesheet)
315 { 392 {
316 try 393 try
317 { 394 {
318 return new URL(stylesheet.href).origin == this.document.location.origin; 395 return new URL(stylesheet.href).origin == this.document.location.origin;
319 } 396 }
320 catch (e) 397 catch (e)
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after
402 let selectors = []; 479 let selectors = [];
403 let selectorFilters = []; 480 let selectorFilters = [];
404 481
405 let elements = []; 482 let elements = [];
406 let elementFilters = []; 483 let elementFilters = [];
407 484
408 let cssStyles = []; 485 let cssStyles = [];
409 486
410 let stylesheetOnlyChange = !!stylesheets; 487 let stylesheetOnlyChange = !!stylesheets;
411 if (!stylesheets) 488 if (!stylesheets)
412 stylesheets = this.document.styleSheets; 489 stylesheets = this.root.styleSheets;
413 490
414 for (let stylesheet of stylesheets) 491 for (let stylesheet of stylesheets)
415 { 492 {
416 // Explicitly ignore third-party stylesheets to ensure consistent behavior 493 // Explicitly ignore third-party stylesheets to ensure consistent behavior
417 // between Firefox and Chrome. 494 // between Firefox and Chrome.
418 if (!this.isSameOrigin(stylesheet)) 495 if (!this.isSameOrigin(stylesheet))
419 continue; 496 continue;
420 497
421 let rules = stylesheet.cssRules; 498 let rules = stylesheet.cssRules;
422 if (!rules) 499 if (!rules)
(...skipping 29 matching lines...) Expand all
452 529
453 pattern = patterns.shift(); 530 pattern = patterns.shift();
454 531
455 if (stylesheetOnlyChange && 532 if (stylesheetOnlyChange &&
456 !pattern.selectors.some(selector => selector.dependsOnStyles)) 533 !pattern.selectors.some(selector => selector.dependsOnStyles))
457 { 534 {
458 pattern = null; 535 pattern = null;
459 return processPatterns(); 536 return processPatterns();
460 } 537 }
461 generator = evaluate(pattern.selectors, 0, "", 538 generator = evaluate(pattern.selectors, 0, "",
462 this.document, cssStyles); 539 this.root, cssStyles);
463 } 540 }
464 for (let selector of generator) 541 for (let selector of generator)
465 { 542 {
466 if (selector != null) 543 if (selector != null)
467 { 544 {
468 if (isSelectorHidingOnlyPattern(pattern)) 545 if (isSelectorHidingOnlyPattern(pattern))
469 { 546 {
470 selectors.push(selector); 547 selectors.push(selector);
471 selectorFilters.push(pattern.text); 548 selectorFilters.push(pattern.text);
472 } 549 }
473 else 550 else
474 { 551 {
475 for (let element of this.document.querySelectorAll(selector)) 552 for (let element of this.root.querySelectorAll(selector))
476 { 553 {
477 elements.push(element); 554 elements.push(element);
478 elementFilters.push(pattern.text); 555 elementFilters.push(pattern.text);
479 } 556 }
480 } 557 }
481 } 558 }
482 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME) 559 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME)
483 { 560 {
484 setTimeout(processPatterns, 0); 561 setTimeout(processPatterns, 0);
485 return; 562 return;
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
553 } 630 }
554 else 631 else
555 { 632 {
556 this._filteringInProgress = true; 633 this._filteringInProgress = true;
557 this._addSelectors(stylesheets, completion); 634 this._addSelectors(stylesheets, completion);
558 } 635 }
559 }, 636 },
560 637
561 onLoad(event) 638 onLoad(event)
562 { 639 {
640 if (this.patterns.length == 0)
641 return;
642
563 let stylesheet = event.target.sheet; 643 let stylesheet = event.target.sheet;
564 if (stylesheet) 644 if (stylesheet)
565 this.queueFiltering([stylesheet]); 645 this.queueFiltering([stylesheet]);
566 }, 646 },
567 647
648 onShadowAttached(event)
649 {
650 event.stopImmediatePropagation();
651
652 if (this.patterns.length == 0)
653 return;
654
655 // The shadow root may not be available if it's a closed shadow root.
656 let shadowRoot = event.target.shadowRoot;
657 if (!shadowRoot)
658 return;
659
660 this.addShadowRoot(shadowRoot);
661 },
662
663 addShadowRoot(shadowRoot)
664 {
665 if (!this.shadowEmulations.has(shadowRoot))
666 {
667 let emulation = new ElemHideEmulation(this.document,
668 shadowRoot,
669 this.addSelectorsFunc,
670 this.hideElemsFunc);
671 this.shadowEmulations.set(shadowRoot, emulation);
672 emulation.apply(this.patterns, true);
673 }
674 },
675
568 observe(mutations) 676 observe(mutations)
569 { 677 {
678 let allAddedElements = new Set();
679 for (let mutation of mutations)
680 {
681 for (let node of mutation.addedNodes)
682 {
683 if (node instanceof Element)
684 allAddedElements.add(node);
685 }
686 }
687
688 // Find any preattached shadows.
689 niceLoop(traverse(removeRedundantNodes(allAddedElements)), node =>
690 {
691 let shadowRoot = node.shadowRoot;
692 if (shadowRoot)
693 this.addShadowRoot(shadowRoot);
694 });
695
570 this.queueFiltering(); 696 this.queueFiltering();
571 }, 697 },
572 698
573 apply(patterns) 699 apply(patterns, parsed)
574 { 700 {
575 this.patterns = []; 701 if (parsed)
576 for (let pattern of patterns)
577 { 702 {
578 let selectors = this.parseSelector(pattern.selector); 703 this.patterns = patterns;
579 if (selectors != null && selectors.length > 0) 704 }
580 this.patterns.push({selectors, text: pattern.text}); 705 else
706 {
707 this.patterns = [];
708 for (let pattern of patterns)
709 {
710 let selectors = this.parseSelector(pattern.selector);
711 if (selectors != null && selectors.length > 0)
712 this.patterns.push({selectors, text: pattern.text});
713 }
581 } 714 }
582 715
583 if (this.patterns.length > 0) 716 if (this.patterns.length > 0)
584 { 717 {
585 this.queueFiltering(); 718 this.queueFiltering();
586 this.observer.observe( 719 this.observer.observe(
587 this.document, 720 this.root,
588 { 721 {
589 childList: true, 722 childList: true,
590 attributes: true, 723 attributes: true,
591 characterData: true, 724 characterData: true,
592 subtree: true 725 subtree: true
593 } 726 }
594 ); 727 );
595 this.document.addEventListener("load", this.onLoad.bind(this), true);
596 } 728 }
597 } 729 }
598 }; 730 };
599 731
600 exports.ElemHideEmulation = ElemHideEmulation; 732 exports.ElemHideEmulation = ElemHideEmulation;
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