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: Use Node.contains Created Oct. 19, 2017, 11:13 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)
306 { 348 {
307 this.document = document; 349 this.document = document;
350 this.root = root || document;
308 this.addSelectorsFunc = addSelectorsFunc; 351 this.addSelectorsFunc = addSelectorsFunc;
309 this.hideElemsFunc = hideElemsFunc; 352 this.hideElemsFunc = hideElemsFunc;
353 this.patterns = [];
310 this.observer = new MutationObserver(this.observe.bind(this)); 354 this.observer = new MutationObserver(this.observe.bind(this));
355 this.shadowEmulations = new WeakMap();
356
357 if (this.root == this.document)
358 {
359 this.document.addEventListener("load", this.onLoad.bind(this), true);
360 this.document.addEventListener("shadowAttached",
361 this.onShadowAttached.bind(this), true);
362 }
311 } 363 }
312 364
313 ElemHideEmulation.prototype = { 365 ElemHideEmulation.prototype = {
314 isSameOrigin(stylesheet) 366 isSameOrigin(stylesheet)
315 { 367 {
316 try 368 try
317 { 369 {
318 return new URL(stylesheet.href).origin == this.document.location.origin; 370 return new URL(stylesheet.href).origin == this.document.location.origin;
319 } 371 }
320 catch (e) 372 catch (e)
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after
402 let selectors = []; 454 let selectors = [];
403 let selectorFilters = []; 455 let selectorFilters = [];
404 456
405 let elements = []; 457 let elements = [];
406 let elementFilters = []; 458 let elementFilters = [];
407 459
408 let cssStyles = []; 460 let cssStyles = [];
409 461
410 let stylesheetOnlyChange = !!stylesheets; 462 let stylesheetOnlyChange = !!stylesheets;
411 if (!stylesheets) 463 if (!stylesheets)
412 stylesheets = this.document.styleSheets; 464 stylesheets = this.root.styleSheets;
413 465
414 for (let stylesheet of stylesheets) 466 for (let stylesheet of stylesheets)
415 { 467 {
416 // Explicitly ignore third-party stylesheets to ensure consistent behavior 468 // Explicitly ignore third-party stylesheets to ensure consistent behavior
417 // between Firefox and Chrome. 469 // between Firefox and Chrome.
418 if (!this.isSameOrigin(stylesheet)) 470 if (!this.isSameOrigin(stylesheet))
419 continue; 471 continue;
420 472
421 let rules = stylesheet.cssRules; 473 let rules = stylesheet.cssRules;
422 if (!rules) 474 if (!rules)
(...skipping 29 matching lines...) Expand all
452 504
453 pattern = patterns.shift(); 505 pattern = patterns.shift();
454 506
455 if (stylesheetOnlyChange && 507 if (stylesheetOnlyChange &&
456 !pattern.selectors.some(selector => selector.dependsOnStyles)) 508 !pattern.selectors.some(selector => selector.dependsOnStyles))
457 { 509 {
458 pattern = null; 510 pattern = null;
459 return processPatterns(); 511 return processPatterns();
460 } 512 }
461 generator = evaluate(pattern.selectors, 0, "", 513 generator = evaluate(pattern.selectors, 0, "",
462 this.document, cssStyles); 514 this.root, cssStyles);
463 } 515 }
464 for (let selector of generator) 516 for (let selector of generator)
465 { 517 {
466 if (selector != null) 518 if (selector != null)
467 { 519 {
468 if (isSelectorHidingOnlyPattern(pattern)) 520 if (isSelectorHidingOnlyPattern(pattern))
469 { 521 {
470 selectors.push(selector); 522 selectors.push(selector);
471 selectorFilters.push(pattern.text); 523 selectorFilters.push(pattern.text);
472 } 524 }
473 else 525 else
474 { 526 {
475 for (let element of this.document.querySelectorAll(selector)) 527 for (let element of this.root.querySelectorAll(selector))
476 { 528 {
477 elements.push(element); 529 elements.push(element);
478 elementFilters.push(pattern.text); 530 elementFilters.push(pattern.text);
479 } 531 }
480 } 532 }
481 } 533 }
482 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME) 534 if (performance.now() - cycleStart > MAX_SYNCHRONOUS_PROCESSING_TIME)
483 { 535 {
484 setTimeout(processPatterns, 0); 536 setTimeout(processPatterns, 0);
485 return; 537 return;
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
553 } 605 }
554 else 606 else
555 { 607 {
556 this._filteringInProgress = true; 608 this._filteringInProgress = true;
557 this._addSelectors(stylesheets, completion); 609 this._addSelectors(stylesheets, completion);
558 } 610 }
559 }, 611 },
560 612
561 onLoad(event) 613 onLoad(event)
562 { 614 {
615 if (this.patterns.length == 0)
616 return;
617
563 let stylesheet = event.target.sheet; 618 let stylesheet = event.target.sheet;
564 if (stylesheet) 619 if (stylesheet)
565 this.queueFiltering([stylesheet]); 620 this.queueFiltering([stylesheet]);
566 }, 621 },
567 622
623 onShadowAttached(event)
624 {
625 event.stopImmediatePropagation();
626
627 if (this.patterns.length == 0)
628 return;
629
630 // The shadow root may not be available if it's a closed shadow root.
631 let shadowRoot = event.target.shadowRoot;
632 if (!shadowRoot)
633 return;
634
635 this.addShadowRoot(shadowRoot);
636 },
637
638 addShadowRoot(shadowRoot)
639 {
640 if (!this.shadowEmulations.has(shadowRoot))
641 {
642 let emulation = new ElemHideEmulation(this.document,
643 shadowRoot,
644 this.addSelectorsFunc,
645 this.hideElemsFunc);
646 this.shadowEmulations.set(shadowRoot, emulation);
647 emulation.apply(this.patterns, true);
648 }
649 },
650
568 observe(mutations) 651 observe(mutations)
569 { 652 {
653 let allAddedElements = [];
654 for (let mutation of mutations)
655 {
656 for (let node of mutation.addedNodes)
657 {
658 if (node instanceof Element)
659 allAddedElements.push(node);
660 }
661 }
662
663 // Find any preattached shadows.
664 niceLoop(traverse(removeRedundantNodes(allAddedElements)), node =>
665 {
666 let shadowRoot = node.shadowRoot;
667 if (shadowRoot)
668 this.addShadowRoot(shadowRoot);
669 });
670
570 this.queueFiltering(); 671 this.queueFiltering();
571 }, 672 },
572 673
573 apply(patterns) 674 apply(patterns, parsed)
574 { 675 {
575 this.patterns = []; 676 if (parsed)
576 for (let pattern of patterns)
577 { 677 {
578 let selectors = this.parseSelector(pattern.selector); 678 this.patterns = patterns;
579 if (selectors != null && selectors.length > 0) 679 }
580 this.patterns.push({selectors, text: pattern.text}); 680 else
681 {
682 this.patterns = [];
683 for (let pattern of patterns)
684 {
685 let selectors = this.parseSelector(pattern.selector);
686 if (selectors != null && selectors.length > 0)
687 this.patterns.push({selectors, text: pattern.text});
688 }
581 } 689 }
582 690
583 if (this.patterns.length > 0) 691 if (this.patterns.length > 0)
584 { 692 {
585 this.queueFiltering(); 693 this.queueFiltering();
586 this.observer.observe( 694 this.observer.observe(
587 this.document, 695 this.root,
588 { 696 {
589 childList: true, 697 childList: true,
590 attributes: true, 698 attributes: true,
591 characterData: true, 699 characterData: true,
592 subtree: true 700 subtree: true
593 } 701 }
594 ); 702 );
595 this.document.addEventListener("load", this.onLoad.bind(this), true);
596 } 703 }
597 } 704 }
598 }; 705 };
599 706
600 exports.ElemHideEmulation = ElemHideEmulation; 707 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