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