This repository has been archived by the owner on Mar 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
ShadowRenderer.js
664 lines (549 loc) · 18.5 KB
/
ShadowRenderer.js
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// Copyright 2013 The Polymer Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(function(scope) {
'use strict';
var Element = scope.wrappers.Element;
var HTMLContentElement = scope.wrappers.HTMLContentElement;
var HTMLShadowElement = scope.wrappers.HTMLShadowElement;
var Node = scope.wrappers.Node;
var ShadowRoot = scope.wrappers.ShadowRoot;
var assert = scope.assert;
var getTreeScope = scope.getTreeScope;
var mixin = scope.mixin;
var oneOf = scope.oneOf;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
/**
* Updates the fields of a wrapper to a snapshot of the logical DOM as needed.
* Up means parentNode
* Sideways means previous and next sibling.
* @param {!Node} wrapper
*/
function updateWrapperUpAndSideways(wrapper) {
wrapper.previousSibling_ = wrapper.previousSibling;
wrapper.nextSibling_ = wrapper.nextSibling;
wrapper.parentNode_ = wrapper.parentNode;
}
/**
* Updates the fields of a wrapper to a snapshot of the logical DOM as needed.
* Down means first and last child
* @param {!Node} wrapper
*/
function updateWrapperDown(wrapper) {
wrapper.firstChild_ = wrapper.firstChild;
wrapper.lastChild_ = wrapper.lastChild;
}
function updateAllChildNodes(parentNodeWrapper) {
assert(parentNodeWrapper instanceof Node);
for (var childWrapper = parentNodeWrapper.firstChild;
childWrapper;
childWrapper = childWrapper.nextSibling) {
updateWrapperUpAndSideways(childWrapper);
}
updateWrapperDown(parentNodeWrapper);
}
function insertBefore(parentNodeWrapper, newChildWrapper, refChildWrapper) {
var parentNode = unwrap(parentNodeWrapper);
var newChild = unwrap(newChildWrapper);
var refChild = refChildWrapper ? unwrap(refChildWrapper) : null;
remove(newChildWrapper);
updateWrapperUpAndSideways(newChildWrapper);
if (!refChildWrapper) {
parentNodeWrapper.lastChild_ = parentNodeWrapper.lastChild;
if (parentNodeWrapper.lastChild === parentNodeWrapper.firstChild)
parentNodeWrapper.firstChild_ = parentNodeWrapper.firstChild;
var lastChildWrapper = wrap(parentNode.lastChild);
if (lastChildWrapper)
lastChildWrapper.nextSibling_ = lastChildWrapper.nextSibling;
} else {
if (parentNodeWrapper.firstChild === refChildWrapper)
parentNodeWrapper.firstChild_ = refChildWrapper;
refChildWrapper.previousSibling_ = refChildWrapper.previousSibling;
}
scope.originalInsertBefore.call(parentNode, newChild, refChild);
}
function remove(nodeWrapper) {
var node = unwrap(nodeWrapper)
var parentNode = node.parentNode;
if (!parentNode)
return;
var parentNodeWrapper = wrap(parentNode);
updateWrapperUpAndSideways(nodeWrapper);
if (nodeWrapper.previousSibling)
nodeWrapper.previousSibling.nextSibling_ = nodeWrapper;
if (nodeWrapper.nextSibling)
nodeWrapper.nextSibling.previousSibling_ = nodeWrapper;
if (parentNodeWrapper.lastChild === nodeWrapper)
parentNodeWrapper.lastChild_ = nodeWrapper;
if (parentNodeWrapper.firstChild === nodeWrapper)
parentNodeWrapper.firstChild_ = nodeWrapper;
scope.originalRemoveChild.call(parentNode, node);
}
var distributedNodesTable = new WeakMap();
var destinationInsertionPointsTable = new WeakMap();
var rendererForHostTable = new WeakMap();
function resetDistributedNodes(insertionPoint) {
distributedNodesTable.set(insertionPoint, []);
}
function getDistributedNodes(insertionPoint) {
var rv = distributedNodesTable.get(insertionPoint);
if (!rv)
distributedNodesTable.set(insertionPoint, rv = []);
return rv;
}
function getChildNodesSnapshot(node) {
var result = [], i = 0;
for (var child = node.firstChild; child; child = child.nextSibling) {
result[i++] = child;
}
return result;
}
var request = oneOf(window, [
'requestAnimationFrame',
'mozRequestAnimationFrame',
'webkitRequestAnimationFrame',
'setTimeout'
]);
var pendingDirtyRenderers = [];
var renderTimer;
function renderAllPending() {
// TODO(arv): Order these in document order. That way we do not have to
// render something twice.
for (var i = 0; i < pendingDirtyRenderers.length; i++) {
var renderer = pendingDirtyRenderers[i];
var parentRenderer = renderer.parentRenderer;
if (parentRenderer && parentRenderer.dirty)
continue;
renderer.render();
}
pendingDirtyRenderers = [];
}
function handleRequestAnimationFrame() {
renderTimer = null;
renderAllPending();
}
/**
* Returns existing shadow renderer for a host or creates it if it is needed.
* @params {!Element} host
* @return {!ShadowRenderer}
*/
function getRendererForHost(host) {
var renderer = rendererForHostTable.get(host);
if (!renderer) {
renderer = new ShadowRenderer(host);
rendererForHostTable.set(host, renderer);
}
return renderer;
}
function getShadowRootAncestor(node) {
var root = getTreeScope(node).root;
if (root instanceof ShadowRoot)
return root;
return null;
}
function getRendererForShadowRoot(shadowRoot) {
return getRendererForHost(shadowRoot.host);
}
var spliceDiff = new ArraySplice();
spliceDiff.equals = function(renderNode, rawNode) {
return unwrap(renderNode.node) === rawNode;
};
/**
* RenderNode is used as an in memory "render tree". When we render the
* composed tree we create a tree of RenderNodes, then we diff this against
* the real DOM tree and make minimal changes as needed.
*/
function RenderNode(node) {
this.skip = false;
this.node = node;
this.childNodes = [];
}
RenderNode.prototype = {
append: function(node) {
var rv = new RenderNode(node);
this.childNodes.push(rv);
return rv;
},
sync: function(opt_added) {
if (this.skip)
return;
var nodeWrapper = this.node;
// plain array of RenderNodes
var newChildren = this.childNodes;
// plain array of real nodes.
var oldChildren = getChildNodesSnapshot(unwrap(nodeWrapper));
var added = opt_added || new WeakMap();
var splices = spliceDiff.calculateSplices(newChildren, oldChildren);
var newIndex = 0, oldIndex = 0;
var lastIndex = 0;
for (var i = 0; i < splices.length; i++) {
var splice = splices[i];
for (; lastIndex < splice.index; lastIndex++) {
oldIndex++;
newChildren[newIndex++].sync(added);
}
var removedCount = splice.removed.length;
for (var j = 0; j < removedCount; j++) {
var wrapper = wrap(oldChildren[oldIndex++]);
if (!added.get(wrapper))
remove(wrapper);
}
var addedCount = splice.addedCount;
var refNode = oldChildren[oldIndex] && wrap(oldChildren[oldIndex]);
for (var j = 0; j < addedCount; j++) {
var newChildRenderNode = newChildren[newIndex++];
var newChildWrapper = newChildRenderNode.node;
insertBefore(nodeWrapper, newChildWrapper, refNode);
// Keep track of added so that we do not remove the node after it
// has been added.
added.set(newChildWrapper, true);
newChildRenderNode.sync(added);
}
lastIndex += addedCount;
}
for (var i = lastIndex; i < newChildren.length; i++) {
newChildren[i].sync(added);
}
}
};
function ShadowRenderer(host) {
this.host = host;
this.dirty = false;
this.invalidateAttributes();
this.associateNode(host);
}
ShadowRenderer.prototype = {
// http://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#rendering-shadow-trees
render: function(opt_renderNode) {
if (!this.dirty)
return;
this.invalidateAttributes();
var host = this.host;
this.distribution(host);
var renderNode = opt_renderNode || new RenderNode(host);
this.buildRenderTree(renderNode, host);
var topMostRenderer = !opt_renderNode;
if (topMostRenderer)
renderNode.sync();
this.dirty = false;
},
get parentRenderer() {
return getTreeScope(this.host).renderer;
},
invalidate: function() {
if (!this.dirty) {
this.dirty = true;
var parentRenderer = this.parentRenderer;
if (parentRenderer)
parentRenderer.invalidate();
pendingDirtyRenderers.push(this);
if (renderTimer)
return;
renderTimer = window[request](handleRequestAnimationFrame, 0);
}
},
// http://w3c.github.io/webcomponents/spec/shadow/#distribution-algorithms
distribution: function(root) {
this.resetAllSubtrees(root);
this.distributionResolution(root);
},
resetAll: function(node) {
if (isInsertionPoint(node))
resetDistributedNodes(node);
else
resetDestinationInsertionPoints(node);
this.resetAllSubtrees(node);
},
resetAllSubtrees: function(node) {
for (var child = node.firstChild; child; child = child.nextSibling) {
this.resetAll(child);
}
if (node.shadowRoot)
this.resetAll(node.shadowRoot);
if (node.olderShadowRoot)
this.resetAll(node.olderShadowRoot);
},
// http://w3c.github.io/webcomponents/spec/shadow/#distribution-results
distributionResolution: function(node) {
if (isShadowHost(node)) {
var shadowHost = node;
// 1.1
var pool = poolPopulation(shadowHost);
var shadowTrees = getShadowTrees(shadowHost);
// 1.2
for (var i = 0; i < shadowTrees.length; i++) {
// 1.2.1
this.poolDistribution(shadowTrees[i], pool);
}
// 1.3
for (var i = shadowTrees.length - 1; i >= 0; i--) {
var shadowTree = shadowTrees[i];
// 1.3.1
// TODO(arv): We should keep the shadow insertion points on the
// shadow root (or renderer) so we don't have to search the tree
// every time.
var shadow = getShadowInsertionPoint(shadowTree);
// 1.3.2
if (shadow) {
// 1.3.2.1
var olderShadowRoot = shadowTree.olderShadowRoot;
if (olderShadowRoot) {
// 1.3.2.1.1
pool = poolPopulation(olderShadowRoot);
}
// 1.3.2.2
for (var j = 0; j < pool.length; j++) {
// 1.3.2.2.1
destributeNodeInto(pool[j], shadow);
}
}
// 1.3.3
this.distributionResolution(shadowTree);
}
}
for (var child = node.firstChild; child; child = child.nextSibling) {
this.distributionResolution(child);
}
},
// http://w3c.github.io/webcomponents/spec/shadow/#dfn-pool-distribution-algorithm
poolDistribution: function (node, pool) {
if (node instanceof HTMLShadowElement)
return;
if (node instanceof HTMLContentElement) {
var content = node;
this.updateDependentAttributes(content.getAttribute('select'));
var anyDistributed = false;
// 1.1
for (var i = 0; i < pool.length; i++) {
var node = pool[i];
if (!node)
continue;
if (matches(node, content)) {
destributeNodeInto(node, content);
pool[i] = undefined;
anyDistributed = true;
}
}
// 1.2
// Fallback content
if (!anyDistributed) {
for (var child = content.firstChild;
child;
child = child.nextSibling) {
destributeNodeInto(child, content);
}
}
return;
}
for (var child = node.firstChild; child; child = child.nextSibling) {
this.poolDistribution(child, pool);
}
},
buildRenderTree: function(renderNode, node) {
var children = this.compose(node);
for (var i = 0; i < children.length; i++) {
var child = children[i];
var childRenderNode = renderNode.append(child);
this.buildRenderTree(childRenderNode, child);
}
if (isShadowHost(node)) {
var renderer = getRendererForHost(node);
renderer.dirty = false;
}
},
compose: function(node) {
var children = [];
var p = node.shadowRoot || node;
for (var child = p.firstChild; child; child = child.nextSibling) {
if (isInsertionPoint(child)) {
this.associateNode(p);
var distributedNodes = getDistributedNodes(child);
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;
},
/**
* Invalidates the attributes used to keep track of which attributes may
* cause the renderer to be invalidated.
*/
invalidateAttributes: function() {
this.attributes = Object.create(null);
},
/**
* Parses the selector and makes this renderer dependent on the attribute
* being used in the selector.
* @param {string} selector
*/
updateDependentAttributes: function(selector) {
if (!selector)
return;
var attributes = this.attributes;
// .class
if (/\.\w+/.test(selector))
attributes['class'] = true;
// #id
if (/#\w+/.test(selector))
attributes['id'] = true;
selector.replace(/\[\s*([^\s=\|~\]]+)/g, function(_, name) {
attributes[name] = true;
});
// Pseudo selectors have been removed from the spec.
},
dependsOnAttribute: function(name) {
return this.attributes[name];
},
associateNode: function(node) {
unsafeUnwrap(node).polymerShadowRenderer_ = this;
}
};
// http://w3c.github.io/webcomponents/spec/shadow/#dfn-pool-population-algorithm
function poolPopulation(node) {
var pool = [];
for (var child = node.firstChild; child; child = child.nextSibling) {
if (isInsertionPoint(child)) {
pool.push.apply(pool, getDistributedNodes(child));
} else {
pool.push(child);
}
}
return pool;
}
function getShadowInsertionPoint(node) {
if (node instanceof HTMLShadowElement)
return node;
if (node instanceof HTMLContentElement)
return null;
for (var child = node.firstChild; child; child = child.nextSibling) {
var res = getShadowInsertionPoint(child);
if (res)
return res;
}
return null;
}
function destributeNodeInto(child, insertionPoint) {
getDistributedNodes(insertionPoint).push(child);
var points = destinationInsertionPointsTable.get(child);
if (!points)
destinationInsertionPointsTable.set(child, [insertionPoint]);
else
points.push(insertionPoint);
}
function getDestinationInsertionPoints(node) {
return destinationInsertionPointsTable.get(node);
}
function resetDestinationInsertionPoints(node) {
// IE11 crashes when delete is used.
destinationInsertionPointsTable.set(node, undefined);
}
// AllowedSelectors :
// TypeSelector
// *
// ClassSelector
// IDSelector
// AttributeSelector
// negation
var selectorStartCharRe = /^(:not\()?[*.#[a-zA-Z_|]/;
function matches(node, contentElement) {
var select = contentElement.getAttribute('select');
if (!select)
return true;
// Here we know the select attribute is a non empty string.
select = select.trim();
if (!select)
return true;
if (!(node instanceof Element))
return false;
if (!selectorStartCharRe.test(select))
return false;
try {
return node.matches(select);
} catch (ex) {
// Invalid selector.
return false;
}
}
function isFinalDestination(insertionPoint, node) {
var points = getDestinationInsertionPoints(node);
return points && points[points.length - 1] === insertionPoint;
}
function isInsertionPoint(node) {
return node instanceof HTMLContentElement ||
node instanceof HTMLShadowElement;
}
function isShadowHost(shadowHost) {
return shadowHost.shadowRoot;
}
// Returns the shadow trees as an array, with the youngest tree at the
// beginning of the array.
function getShadowTrees(host) {
var trees = [];
for (var tree = host.shadowRoot; tree; tree = tree.olderShadowRoot) {
trees.push(tree);
}
return trees;
}
function render(host) {
new ShadowRenderer(host).render();
};
// Need to rerender shadow host when:
//
// - a direct child to the ShadowRoot is added or removed
// - a direct child to the host is added or removed
// - a new shadow root is created
// - a direct child to a content/shadow element is added or removed
// - a sibling to a content/shadow element is added or removed
// - content[select] is changed
// - an attribute in a direct child to a host is modified
/**
* This gets called when a node was added or removed to it.
*/
Node.prototype.invalidateShadowRenderer = function(force) {
var renderer = unsafeUnwrap(this).polymerShadowRenderer_;
if (renderer) {
renderer.invalidate();
return true;
}
return false;
};
HTMLContentElement.prototype.getDistributedNodes =
HTMLShadowElement.prototype.getDistributedNodes = function() {
// TODO(arv): We should only rerender the dirty ancestor renderers (from
// the root and down).
renderAllPending();
return getDistributedNodes(this);
};
Element.prototype.getDestinationInsertionPoints = function() {
renderAllPending();
return getDestinationInsertionPoints(this) || [];
};
HTMLContentElement.prototype.nodeIsInserted_ =
HTMLShadowElement.prototype.nodeIsInserted_ = function() {
// Invalidate old renderer if any.
this.invalidateShadowRenderer();
var shadowRoot = getShadowRootAncestor(this);
var renderer;
if (shadowRoot)
renderer = getRendererForShadowRoot(shadowRoot);
unsafeUnwrap(this).polymerShadowRenderer_ = renderer;
if (renderer)
renderer.invalidate();
};
scope.getRendererForHost = getRendererForHost;
scope.getShadowTrees = getShadowTrees;
scope.renderAllPending = renderAllPending;
scope.getDestinationInsertionPoints = getDestinationInsertionPoints;
// Exposed for testing
scope.visual = {
insertBefore: insertBefore,
remove: remove,
};
})(window.ShadowDOMPolyfill);