aboutsummaryrefslogtreecommitdiff
path: root/catapult/third_party/polymer/components/shadycss/examples/document-style-lib.js
blob: a1c032c0fdf43a5cca90db94c0a351043eec26b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

/*
Example library for adding document-level styles to ShadyCSS

After DOMContentLoaded, synchronously add all document document level styles.
Then, start a MutationObserver for dynamically added styles.

Caveat: ShadyCSS will add a `scope` attribute to styles it controls, so do not add those styles.
*/
(function() {
  'use strict';

  const CustomStyleInterface = window.ShadyCSS.CustomStyleInterface;

  function shouldAddDocumentStyle(n) {
    return n.nodeType === Node.ELEMENT_NODE && n.localName === 'style' && !n.hasAttribute('scope');
  }

  function handler(mxns) {
    for (let i = 0; i < mxns.length; i++) {
      let mxn = mxns[i];
      for (let j = 0; j < mxn.addedNodes.length; j++) {
        let n = mxn.addedNodes[j];
        if (shouldAddDocumentStyle(n)) {
          CustomStyleInterface.addCustomStyle(n);
        }
      }
    }
  }

  const observer = new MutationObserver(handler);

  document.addEventListener('DOMContentLoaded', () => {
    const candidates = document.querySelectorAll('custom-style');
    for (let i = 0; i < candidates.length; i++) {
      const candidate = candidates[i];
      if (shouldAddDocumentStyle(candidate)) {
        CustomStyleInterface.addCustomStyle(candidate);
      }
    }
    observer.observe(document, {childList: true, subtree: true});
  });

  window.documentStyleFlush = () => {handler(observer.takeRecords())};
})();