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: Optimize removeRedundantNodes based on node order Created Oct. 20, 2017, 2:22 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-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";
hub 2017/10/20 15:37:57 In Firefox Nightly `document.querySelector("div"
Manish Jethani 2017/10/20 16:16:41 Done.
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 extractSubtrees(nodes)
150 {
151 return nodes.filter(
152 (node, index) => !nodes.some(
153 // The index comparison is based on the fact that a node always appears
154 // in the list before any of its descendants.
155 (otherNode, otherIndex) => otherIndex < index && otherNode.contains(node)
156 )
157 );
158 }
159
160 function* traverse(nodes)
161 {
162 for (let node of nodes)
163 {
164 yield* traverse(node.children);
165 yield node;
166 }
167 }
168
169 function niceLoop(iterator, callback)
170 {
171 let loop = () =>
172 {
173 let cycleStart = performance.now();
174
175 for (let next = iterator.next(); !next.done; next = iterator.next())
176 {
177 callback(next.value);
178
179 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME)
180 {
181 setTimeout(loop, 0);
182 return;
183 }
184 }
185 };
186
187 loop();
188 }
189
146 function PlainSelector(selector) 190 function PlainSelector(selector)
147 { 191 {
148 this._selector = selector; 192 this._selector = selector;
149 } 193 }
150 194
151 PlainSelector.prototype = { 195 PlainSelector.prototype = {
152 /** 196 /**
153 * Generator function returning a pair of selector 197 * Generator function returning a pair of selector
154 * string and subtree. 198 * string and subtree.
155 * @param {string} prefix the prefix for the selector. 199 * @param {string} prefix the prefix for the selector.
(...skipping 139 matching lines...) Expand 10 before | Expand all | Expand 10 after
295 yield [selector, subtree]; 339 yield [selector, subtree];
296 } 340 }
297 }; 341 };
298 342
299 function isSelectorHidingOnlyPattern(pattern) 343 function isSelectorHidingOnlyPattern(pattern)
300 { 344 {
301 return pattern.selectors.some(s => s.preferHideWithSelector) && 345 return pattern.selectors.some(s => s.preferHideWithSelector) &&
302 !pattern.selectors.some(s => s.requiresHiding); 346 !pattern.selectors.some(s => s.requiresHiding);
303 } 347 }
304 348
305 function ElemHideEmulation(addSelectorsFunc, hideElemsFunc) 349 function ElemHideEmulation(document, root, addSelectorsFunc, hideElemsFunc,
350 shadowAttachedEventType)
306 { 351 {
307 this.document = document; 352 this.document = document;
353 this.root = root || document;
308 this.addSelectorsFunc = addSelectorsFunc; 354 this.addSelectorsFunc = addSelectorsFunc;
309 this.hideElemsFunc = hideElemsFunc; 355 this.hideElemsFunc = hideElemsFunc;
356 this.shadowAttachedEventType = shadowAttachedEventType;
357 this.patterns = [];
310 this.observer = new MutationObserver(this.observe.bind(this)); 358 this.observer = new MutationObserver(this.observe.bind(this));
359 this.shadowEmulations = new WeakMap();
360
361 if (shadowAttachedEventType)
362 {
363 this.root.addEventListener(shadowAttachedEventType,
364 this.onShadowAttached.bind(this), true);
365 }
366
367 if (this.root == this.document)
368 this.document.addEventListener("load", this.onLoad.bind(this), true);
369 else
370 this.findShadowRoots(this.root.children);
311 } 371 }
312 372
313 ElemHideEmulation.prototype = { 373 ElemHideEmulation.prototype = {
314 isSameOrigin(stylesheet) 374 isSameOrigin(stylesheet)
315 { 375 {
316 try 376 try
317 { 377 {
318 return new URL(stylesheet.href).origin == this.document.location.origin; 378 return new URL(stylesheet.href).origin == this.document.location.origin;
319 } 379 }
320 catch (e) 380 catch (e)
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after
402 let selectors = []; 462 let selectors = [];
403 let selectorFilters = []; 463 let selectorFilters = [];
404 464
405 let elements = []; 465 let elements = [];
406 let elementFilters = []; 466 let elementFilters = [];
407 467
408 let cssStyles = []; 468 let cssStyles = [];
409 469
410 let stylesheetOnlyChange = !!stylesheets; 470 let stylesheetOnlyChange = !!stylesheets;
411 if (!stylesheets) 471 if (!stylesheets)
412 stylesheets = this.document.styleSheets; 472 stylesheets = this.root.styleSheets;
413 473
414 for (let stylesheet of stylesheets) 474 for (let stylesheet of stylesheets)
415 { 475 {
416 // Explicitly ignore third-party stylesheets to ensure consistent behavior 476 // Explicitly ignore third-party stylesheets to ensure consistent behavior
417 // between Firefox and Chrome. 477 // between Firefox and Chrome.
418 if (!this.isSameOrigin(stylesheet)) 478 if (!this.isSameOrigin(stylesheet))
419 continue; 479 continue;
420 480
421 let rules = stylesheet.cssRules; 481 let rules = stylesheet.cssRules;
422 if (!rules) 482 if (!rules)
(...skipping 29 matching lines...) Expand all
452 512
453 pattern = patterns.shift(); 513 pattern = patterns.shift();
454 514
455 if (stylesheetOnlyChange && 515 if (stylesheetOnlyChange &&
456 !pattern.selectors.some(selector => selector.dependsOnStyles)) 516 !pattern.selectors.some(selector => selector.dependsOnStyles))
457 { 517 {
458 pattern = null; 518 pattern = null;
459 return processPatterns(); 519 return processPatterns();
460 } 520 }
461 generator = evaluate(pattern.selectors, 0, "", 521 generator = evaluate(pattern.selectors, 0, "",
462 this.document, cssStyles); 522 this.root, cssStyles);
463 } 523 }
464 for (let selector of generator) 524 for (let selector of generator)
465 { 525 {
466 if (selector != null) 526 if (selector != null)
467 { 527 {
468 if (isSelectorHidingOnlyPattern(pattern)) 528 if (isSelectorHidingOnlyPattern(pattern))
469 { 529 {
470 selectors.push(selector); 530 selectors.push(selector);
471 selectorFilters.push(pattern.text); 531 selectorFilters.push(pattern.text);
472 } 532 }
473 else 533 else
474 { 534 {
475 for (let element of this.document.querySelectorAll(selector)) 535 for (let element of this.root.querySelectorAll(selector))
476 { 536 {
477 elements.push(element); 537 elements.push(element);
478 elementFilters.push(pattern.text); 538 elementFilters.push(pattern.text);
479 } 539 }
480 } 540 }
481 } 541 }
482 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME) 542 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME)
483 { 543 {
484 setTimeout(processPatterns, 0); 544 setTimeout(processPatterns, 0);
485 return; 545 return;
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
553 } 613 }
554 else 614 else
555 { 615 {
556 this._filteringInProgress = true; 616 this._filteringInProgress = true;
557 this._addSelectors(stylesheets, completion); 617 this._addSelectors(stylesheets, completion);
558 } 618 }
559 }, 619 },
560 620
561 onLoad(event) 621 onLoad(event)
562 { 622 {
623 this.findShadowRoots(this.root.children);
624
625 if (this.patterns.length == 0)
626 return;
627
563 let stylesheet = event.target.sheet; 628 let stylesheet = event.target.sheet;
564 if (stylesheet) 629 if (stylesheet)
565 this.queueFiltering([stylesheet]); 630 this.queueFiltering([stylesheet]);
566 }, 631 },
567 632
633 onShadowAttached(event)
634 {
635 event.stopImmediatePropagation();
636
637 if (this.patterns.length == 0)
638 return;
639
640 // The shadow root may not be available if it's a closed shadow root.
641 let shadowRoot = event.target.shadowRoot;
642 if (!shadowRoot)
643 return;
644
645 this.addShadowRoot(shadowRoot);
646 },
647
648 addShadowRoot(shadowRoot)
649 {
650 if (!this.shadowEmulations.has(shadowRoot))
651 {
652 let emulation = new ElemHideEmulation(this.document,
653 shadowRoot,
654 this.addSelectorsFunc,
655 this.hideElemsFunc,
656 this.shadowAttachedEventType);
657 this.shadowEmulations.set(shadowRoot, emulation);
658 emulation.apply(this.patterns, true);
659 }
660 },
661
662 findShadowRoots(nodes)
663 {
664 niceLoop(traverse(nodes), node =>
665 {
666 let shadowRoot = node.shadowRoot;
667 if (shadowRoot)
668 this.addShadowRoot(shadowRoot);
669 });
670 },
671
568 observe(mutations) 672 observe(mutations)
569 { 673 {
674 let allAddedElements = [];
675 for (let mutation of mutations)
676 {
677 for (let node of mutation.addedNodes)
678 {
679 if (node instanceof Element)
lainverse 2017/10/20 15:37:07 Actually if nodes are always added in parent -> ch
Manish Jethani 2017/10/20 16:16:41 That's a very good point! While it is better in t
lainverse 2017/10/20 17:37:36 Most likely that's because arrow function were def
Manish Jethani 2017/10/22 20:01:34 Simply moving the array function out of the loop d
680 allAddedElements.push(node);
681 }
682 }
683
684 // Find any preattached shadows.
685 this.findShadowRoots(extractSubtrees(allAddedElements));
686
570 this.queueFiltering(); 687 this.queueFiltering();
571 }, 688 },
572 689
573 apply(patterns) 690 apply(patterns, parsed)
574 { 691 {
575 this.patterns = []; 692 if (parsed)
576 for (let pattern of patterns)
577 { 693 {
578 let selectors = this.parseSelector(pattern.selector); 694 this.patterns = patterns;
579 if (selectors != null && selectors.length > 0) 695 }
580 this.patterns.push({selectors, text: pattern.text}); 696 else
697 {
698 this.patterns = [];
699 for (let pattern of patterns)
700 {
701 let selectors = this.parseSelector(pattern.selector);
702 if (selectors != null && selectors.length > 0)
703 this.patterns.push({selectors, text: pattern.text});
704 }
581 } 705 }
582 706
583 if (this.patterns.length > 0) 707 if (this.patterns.length > 0)
584 { 708 {
585 this.queueFiltering(); 709 this.queueFiltering();
586 this.observer.observe( 710 this.observer.observe(
587 this.document, 711 this.root,
588 { 712 {
589 childList: true, 713 childList: true,
590 attributes: true, 714 attributes: true,
591 characterData: true, 715 characterData: true,
592 subtree: true 716 subtree: true
593 } 717 }
594 ); 718 );
595 this.document.addEventListener("load", this.onLoad.bind(this), true);
596 } 719 }
597 } 720 }
598 }; 721 };
599 722
600 exports.ElemHideEmulation = ElemHideEmulation; 723 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