aboutsummaryrefslogtreecommitdiff
path: root/catapult/third_party/polymer/components/shadycss/src/document-watcher.js
blob: 9cf34f0541e8eff3e607eaf0ce396dfeb821d35f (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/**
@license
Copyright (c) 2017 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
*/

'use strict';

import {nativeShadow} from './style-settings.js';
import StyleTransformer from './style-transformer.js';
import {getIsExtends, elementHasBuiltCss, wrap} from './style-util.js';

export let flush = function() {};

/**
 * @param {!Element} element
 * @return {string}
 */
function getClasses(element) {
  if (element.classList && element.classList.value) {
    return element.classList.value;
  } else {
    // NOTE: className is patched to remove scoping classes in ShadyDOM
    // use getAttribute('class') instead, which is unpatched
    return element.getAttribute('class') || '';
  }
}

const scopeRegExp = new RegExp(`${StyleTransformer.SCOPE_NAME}\\s*([^\\s]*)`);

/**
 * @param {!Element} element
 * @return {string}
 */
export function getCurrentScope(element) {
  const match = getClasses(element).match(scopeRegExp);
  if (match) {
    return match[1];
  } else {
    return '';
  }
}

/**
 * @param {!Node} node
 */
export function getOwnerScope(node) {
  const ownerRoot = wrap(node).getRootNode();
  if (ownerRoot === node || ownerRoot === node.ownerDocument) {
    return '';
  }
  const host = /** @type {!ShadowRoot} */(ownerRoot).host;
  if (!host) {
    // this may actually be a document fragment
    return '';
  }
  return getIsExtends(host).is;
}

/**
 * @param {!Element} element
 */
export function ensureCorrectScope(element) {
  const currentScope = getCurrentScope(element);
  const ownerRoot = wrap(element).getRootNode();
  if (ownerRoot === element) {
    return;
  }
  if (currentScope && ownerRoot === element.ownerDocument) {
    // node was scoped, but now is in document
    StyleTransformer.domRemoveScope(element, currentScope);
  } else if (ownerRoot instanceof ShadowRoot) {
    const ownerScope = getOwnerScope(element);
    if (ownerScope !== currentScope) {
      // node was scoped, but not by its current owner
      StyleTransformer.domReplaceScope(element, currentScope, ownerScope);
    }
  }
}

/**
 * @param {!HTMLElement|!HTMLDocument} element
 */
export function ensureCorrectSubtreeScoping(element) {
  // find unscoped subtree nodes
  const unscopedNodes = window['ShadyDOM']['nativeMethods']['querySelectorAll'].call(
    element, `:not(.${StyleTransformer.SCOPE_NAME})`);

  for (let j = 0; j < unscopedNodes.length; j++) {
    // it's possible, during large batch inserts, that nodes that aren't
    // scoped within the current scope were added.
    // To make sure that any unscoped nodes that were inserted in the current batch are correctly styled,
    // query all unscoped nodes and force their style-scope to be applied.
    // This could happen if a sub-element appended an unscoped node in its shadowroot and this function
    // runs on a parent element of the host of that unscoped node:
    // parent-element -> element -> unscoped node
    // Here unscoped node should have the style-scope element, not parent-element.
    const unscopedNode = unscopedNodes[j];
    const scopeForPreviouslyUnscopedNode = getOwnerScope(unscopedNode);
    if (scopeForPreviouslyUnscopedNode) {
      StyleTransformer.element(unscopedNode, scopeForPreviouslyUnscopedNode);
    }
  }
}

/**
 * @param {HTMLElement} el
 * @return {boolean}
 */
function isElementWithBuiltCss(el) {
  if (el.localName === 'style' || el.localName === 'template') {
    return elementHasBuiltCss(el);
  }
  return false;
}

/**
 * @param {Array<MutationRecord|null>|null} mxns
 */
function handler(mxns) {
  for (let x=0; x < mxns.length; x++) {
    let mxn = mxns[x];
    if (mxn.target === document.documentElement ||
      mxn.target === document.head) {
      continue;
    }
    for (let i=0; i < mxn.addedNodes.length; i++) {
      let n = mxn.addedNodes[i];
      if (n.nodeType !== Node.ELEMENT_NODE) {
        continue;
      }
      n = /** @type {HTMLElement} */(n); // eslint-disable-line no-self-assign
      let root = n.getRootNode();
      let currentScope = getCurrentScope(n);
      // node was scoped, but now is in document
      // If this element has built css, we must not remove scoping as this node
      // will be used as a template or style without re - applying scoping as an optimization
      if (currentScope && root === n.ownerDocument && !isElementWithBuiltCss(n)) {
        StyleTransformer.domRemoveScope(n, currentScope);
      } else if (root instanceof ShadowRoot) {
        const newScope = getOwnerScope(n);
        // rescope current node and subtree if necessary
        if (newScope !== currentScope) {
          StyleTransformer.domReplaceScope(n, currentScope, newScope);
        }
        // make sure all the subtree elements are scoped correctly
        ensureCorrectSubtreeScoping(n);
      }
    }
  }
}

// if native Shadow DOM is being used, or ShadyDOM handles dynamic scoiping, do not activate the MutationObserver
if (!nativeShadow && !(window['ShadyDOM'] && window['ShadyDOM']['handlesDynamicScoping'])) {
  let observer = new MutationObserver(handler);
  let start = (node) => {
    observer.observe(node, {childList: true, subtree: true});
  }
  let nativeCustomElements = (window['customElements'] &&
    !window['customElements']['polyfillWrapFlushCallback']);
  // need to start immediately with native custom elements
  // TODO(dfreedm): with polyfilled HTMLImports and native custom elements
  // excessive mutations may be observed; this can be optimized via cooperation
  // with the HTMLImports polyfill.
  if (nativeCustomElements) {
    start(document);
  } else {
    let delayedStart = () => {
      start(document.body);
    }
    // use polyfill timing if it's available
    if (window['HTMLImports']) {
      window['HTMLImports']['whenReady'](delayedStart);
    // otherwise push beyond native imports being ready
    // which requires RAF + readystate interactive.
    } else {
      requestAnimationFrame(function() {
        if (document.readyState === 'loading') {
          let listener = function() {
            delayedStart();
            document.removeEventListener('readystatechange', listener);
          }
          document.addEventListener('readystatechange', listener);
        } else {
          delayedStart();
        }
      });
    }
  }

  flush = function() {
    handler(observer.takeRecords());
  }
}