-
Notifications
You must be signed in to change notification settings - Fork 2k
/
shady.html
485 lines (447 loc) · 17.5 KB
/
shady.html
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<!--
@license
Copyright (c) 2014 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
-->
<link rel="import" href="../lib/array-splice.html">
<link rel="import" href="../lib/dom-tree-api.html">
<link rel="import" href="../lib/dom-api.html">
<link rel="import" href="../lib/dom-api-shady.html">
<link rel="import" href="../lib/dom-api-shadow.html">
<link rel="import" href="../lib/dom-api-flush.html">
<link rel="import" href="../lib/dom-api-event.html">
<link rel="import" href="../lib/dom-api-classlist.html">
<link rel="import" href="../lib/dom-api-effective-nodes-observer.html">
<link rel="import" href="../lib/dom-api-distributed-nodes-observer.html">
<script>
(function() {
/**
Implements a pared down version of ShadowDOM's scoping, which is easy to
polyfill across browsers.
*/
var DomApi = Polymer.DomApi;
var TreeApi = Polymer.TreeApi;
Polymer.Base._addFeature({
_prepShady: function() {
// Use this system iff localDom is needed.
this._useContent = this._useContent || Boolean(this._template);
},
_setupShady: function() {
// object shaping...
this.shadyRoot = null;
if (!this.__domApi) {
this.__domApi = null;
}
if (!this._ownerShadyRoot) {
this._ownerShadyRoot = undefined;
}
// TODO(sorvell): these could be on the domApi object?
// there are a bunch of `__` properties that get put on the node
// from logicalizing. These could be on `__domApi`. Initializing
// them here is problematic because they may have been set prior
// to upgrading.
},
// called as part of content initialization, prior to template stamping
_poolContent: function() {
if (this._useContent) {
// capture lightChildren to help reify dom scoping
TreeApi.Logical.saveChildNodes(this);
}
},
// called as part of content initialization, after template stamping
_setupRoot: function() {
if (this._useContent) {
this._createLocalRoot();
// light elements may not be upgraded if they are light children
// and there is no configuration flow (no dataHost) and they are
// removed from document by shadyDOM distribution
// so we ensure this here
if (!this.dataHost) {
upgradeLogicalChildren(TreeApi.Logical.getChildNodes(this));
}
}
},
_createLocalRoot: function() {
this.shadyRoot = this.root;
this.shadyRoot._distributionClean = false;
this.shadyRoot._hasDistributed = false;
this.shadyRoot._isShadyRoot = true;
this.shadyRoot._dirtyRoots = [];
// capture insertion point list
var i$ = this.shadyRoot._insertionPoints = !this._notes ||
this._notes._hasContent ?
this.shadyRoot.querySelectorAll('content') : [];
// save logical tree info
// a. for shadyRoot
// b. for insertion points (fallback)
// c. for parents of insertion points
TreeApi.Logical.saveChildNodes(this.shadyRoot);
for (var i=0, c; i < i$.length; i++) {
c = i$[i];
TreeApi.Logical.saveChildNodes(c);
TreeApi.Logical.saveChildNodes(c.parentNode);
}
this.shadyRoot.host = this;
},
/**
* Return the element whose local dom within which this element
* is contained. This is a shorthand for
* `Polymer.dom(this).getOwnerRoot().host`.
*/
get domHost() {
var root = Polymer.dom(this).getOwnerRoot();
return root && root.host;
},
/**
* Force this element to distribute its children to its local dom.
* A user should call `distributeContent` if distribution has been
* invalidated due to changes to selectors on child elements that
* effect distribution that were not made via `Polymer.dom`.
* For example, if an element contains an insertion point with
* `<content select=".foo">` and a `foo` class is added to a child,
* then `distributeContent` must be called to update
* local dom distribution.
* @method distributeContent
* @param {boolean} updateInsertionPoints Shady DOM does not detect
* <content> insertion that is nested in a sub-tree being appended.
* Set to true to distribute to newly added nested <content>'s.
*/
distributeContent: function(updateInsertionPoints) {
if (this.shadyRoot) {
var dom = Polymer.dom(this);
if (updateInsertionPoints) {
dom._updateInsertionPoints(this);
}
// Distribute the host that's the top of this element's distribution
// tree. Distributing that host will *always* distibute this element.
var host = getTopDistributingHost(this);
dom._lazyDistribute(host);
}
},
_distributeContent: function() {
if (this._useContent && !this.shadyRoot._distributionClean) {
// logically distribute self
this._beginDistribute();
this._distributeDirtyRoots();
this._finishDistribute();
}
},
_beginDistribute: function() {
if (this._useContent && DomApi.hasInsertionPoint(this.shadyRoot)) {
// reset distributions
this._resetDistribution();
// compute which nodes should be distributed where
// TODO(jmesserly): this is simplified because we assume a single
// ShadowRoot per host and no `<shadow>`.
this._distributePool(this.shadyRoot, this._collectPool());
}
},
_distributeDirtyRoots: function() {
var c$ = this.shadyRoot._dirtyRoots;
for (var i=0, l= c$.length, c; (i<l) && (c=c$[i]); i++) {
c._distributeContent();
}
this.shadyRoot._dirtyRoots = [];
},
_finishDistribute: function() {
// compose self
if (this._useContent) {
// note: it's important to mark this clean before distribution
// so that attachment that provokes additional distribution (e.g.
// adding something to your parentNode) works
this.shadyRoot._distributionClean = true;
if (DomApi.hasInsertionPoint(this.shadyRoot)) {
this._composeTree();
// NOTE: send a signal to insertion points that we have distributed
// which informs effective children observers
notifyContentObservers(this.shadyRoot);
} else {
if (!this.shadyRoot._hasDistributed) {
TreeApi.Composed.clearChildNodes(this);
this.appendChild(this.shadyRoot);
} else {
// simplified non-tree walk composition
var children = this._composeNode(this);
this._updateChildNodes(this, children);
}
}
// NOTE: send a signal to any Polymer.dom node observers
// to report the initial set of childNodes
if (!this.shadyRoot._hasDistributed) {
notifyInitialDistribution(this);
}
this.shadyRoot._hasDistributed = true;
}
},
/**
* Polyfill for Element.prototype.matches, which is sometimes still
* prefixed.
*
* @method elementMatches
* @param {string} selector Selector to test.
* @param {Element=} node Element to test the selector against.
* @return {boolean} Whether the element matches the selector.
*/
elementMatches: function(selector, node) {
// Alternatively we could just polyfill it somewhere.
// Note that the arguments are reversed from what you might expect.
node = node || this;
return DomApi.matchesSelector.call(node, selector);
},
// Many of the following methods are all conceptually static, but they are
// included here as "protected" methods to allow overriding.
_resetDistribution: function() {
// light children
var children = TreeApi.Logical.getChildNodes(this);
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child._destinationInsertionPoints) {
child._destinationInsertionPoints = undefined;
}
if (isInsertionPoint(child)) {
clearDistributedDestinationInsertionPoints(child);
}
}
// insertion points
var root = this.shadyRoot;
var p$ = root._insertionPoints;
for (var j = 0; j < p$.length; j++) {
p$[j]._distributedNodes = [];
}
},
// Gather the pool of nodes that should be distributed. We will combine
// these with the "content root" to arrive at the composed tree.
_collectPool: function() {
var pool = [];
var children = TreeApi.Logical.getChildNodes(this);
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (isInsertionPoint(child)) {
pool.push.apply(pool, child._distributedNodes);
} else {
pool.push(child);
}
}
return pool;
},
// perform "logical" distribution; note, no actual dom is moved here,
// instead elements are distributed into a `content._distributedNodes`
// array where applicable.
_distributePool: function(node, pool) {
var p$ = node._insertionPoints;
for (var i=0, l=p$.length, p; (i<l) && (p=p$[i]); i++) {
this._distributeInsertionPoint(p, pool);
// provoke redistribution on insertion point parents
// must do this on all candidate hosts since distribution in this
// scope invalidates their distribution.
maybeRedistributeParent(p, this);
}
},
_distributeInsertionPoint: function(content, pool) {
// distribute nodes from the pool that this selector matches
var anyDistributed = false;
for (var i=0, l=pool.length, node; i < l; i++) {
node=pool[i];
// skip nodes that were already used
if (!node) {
continue;
}
// distribute this node if it matches
if (this._matchesContentSelect(node, content)) {
distributeNodeInto(node, content);
// remove this node from the pool
pool[i] = undefined;
// since at least one node matched, we won't need fallback content
anyDistributed = true;
}
}
// Fallback content if nothing was distributed here
if (!anyDistributed) {
var children = TreeApi.Logical.getChildNodes(content);
for (var j = 0; j < children.length; j++) {
distributeNodeInto(children[j], content);
}
}
},
// Reify dom such that it is at its correct rendering position
// based on logical distribution.
_composeTree: function() {
this._updateChildNodes(this, this._composeNode(this));
var p$ = this.shadyRoot._insertionPoints;
for (var i=0, l=p$.length, p, parent; (i<l) && (p=p$[i]); i++) {
parent = Polymer.dom(p).parentNode;
if (!parent._useContent && (parent !== this) &&
(parent !== this.shadyRoot)) {
this._updateChildNodes(parent, this._composeNode(parent));
}
}
},
// Returns the list of nodes which should be rendered inside `node`.
_composeNode: function(node) {
var children = [];
var c$ = TreeApi.Logical.getChildNodes(node.shadyRoot || node);
for (var i = 0; i < c$.length; i++) {
var child = c$[i];
if (isInsertionPoint(child)) {
var distributedNodes = child._distributedNodes;
for (var j = 0; j < distributedNodes.length; j++) {
var distributedNode = distributedNodes[j];
if (isFinalDestination(child, distributedNode)) {
children.push(distributedNode);
}
}
} else {
children.push(child);
}
}
return children;
},
// Ensures that the rendered node list inside `container` is `children`.
_updateChildNodes: function(container, children) {
var composed = TreeApi.Composed.getChildNodes(container);
var splices =
Polymer.ArraySplice.calculateSplices(children, composed);
// process removals
for (var i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) {
for (var j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) {
// check if the node is still where we expect it is before trying
// to remove it; this can happen if Polymer.dom moves a node and
// then schedules its previous host for distribution resulting in
// the node being removed here.
if (TreeApi.Composed.getParentNode(n) === container) {
TreeApi.Composed.removeChild(n);
}
composed.splice(s.index + d, 1);
}
d -= s.addedCount;
}
// process adds
for (var i=0, s, next; (i<splices.length) && (s=splices[i]); i++) {
next = composed[s.index];
for (var j=s.index, n; j < s.index + s.addedCount; j++) {
n = children[j];
TreeApi.Composed.insertBefore(container, n, next);
// TODO(sorvell): is this splice strictly needed?
composed.splice(j, 0, n);
}
}
// ensure composed parent is set
TreeApi.Composed.ensureParentNodes(container, children);
},
_matchesContentSelect: function(node, contentElement) {
var select = contentElement.getAttribute('select');
// no selector matches all nodes (including text)
if (!select) {
return true;
}
select = select.trim();
// same thing if it had only whitespace
if (!select) {
return true;
}
// selectors can only match Elements
if (!(node instanceof Element)) {
return false;
}
// only valid selectors can match:
// TypeSelector
// *
// ClassSelector
// IDSelector
// AttributeSelector
// negation
var validSelectors = /^(:not\()?[*.#[a-zA-Z_|]/;
if (!validSelectors.test(select)) {
return false;
}
return this.elementMatches(select, node);
},
// system override point
_elementAdd: function() {},
// system override point
_elementRemove: function() {}
});
function distributeNodeInto(child, insertionPoint) {
insertionPoint._distributedNodes.push(child);
var points = child._destinationInsertionPoints;
if (!points) {
child._destinationInsertionPoints = [insertionPoint];
} else {
points.push(insertionPoint);
}
}
function clearDistributedDestinationInsertionPoints(content) {
var e$ = content._distributedNodes;
if (e$) {
for (var i=0; i < e$.length; i++) {
var d = e$[i]._destinationInsertionPoints;
if (d) {
// this is +1 because these insertion points are *not* in this scope
d.splice(d.indexOf(content)+1, d.length);
}
}
}
}
// dirty a shadyRoot if a change may trigger reprojection!
function maybeRedistributeParent(content, host) {
var parent = content.__parentNode;
if (parent && parent.shadyRoot &&
DomApi.hasInsertionPoint(parent.shadyRoot) &&
parent.shadyRoot._distributionClean) {
parent.shadyRoot._distributionClean = false;
host.shadyRoot._dirtyRoots.push(parent);
}
}
function isFinalDestination(insertionPoint, node) {
var points = node._destinationInsertionPoints;
return points && points[points.length - 1] === insertionPoint;
}
function isInsertionPoint(node) {
// TODO(jmesserly): we could add back 'shadow' support here.
return node.localName == 'content';
}
// returns the host that's the top of this host's distribution tree
function getTopDistributingHost(host) {
while (host && hostNeedsRedistribution(host)) {
host = host.domHost;
}
return host;
}
// Return true if a host's children includes
// an insertion point that selects selectively
function hostNeedsRedistribution(host) {
var c$ = Polymer.dom(host).children;
for (var i=0, c; i < c$.length; i++) {
c = c$[i];
if (c.localName === 'content') {
return host.domHost;
}
}
}
function notifyContentObservers(root) {
for (var i=0, c; i < root._insertionPoints.length; i++) {
c = root._insertionPoints[i];
if (DomApi.hasApi(c)) {
Polymer.dom(c).notifyObserver();
}
}
}
function notifyInitialDistribution(host) {
if (DomApi.hasApi(host)) {
Polymer.dom(host).notifyObserver();
}
}
var needsUpgrade = window.CustomElements && !CustomElements.useNative;
function upgradeLogicalChildren(children) {
if (needsUpgrade && children) {
for (var i=0; i < children.length; i++) {
CustomElements.upgrade(children[i]);
}
}
}
})();
</script>