spincycle
Version:
A reactive message router and object manager that lets clients subscribe to object property changes on the server
1,569 lines (1,533 loc) • 79.6 kB
JavaScript
/**
* @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
*/
// @version 0.7.23
(function() {
window.WebComponents = window.WebComponents || {
flags: {}
};
var file = "webcomponents-lite.js";
var script = document.querySelector('script[src*="' + file + '"]');
var flags = {};
if (!flags.noOpts) {
location.search.slice(1).split("&").forEach(function(option) {
var parts = option.split("=");
var match;
if (parts[0] && (match = parts[0].match(/wc-(.+)/))) {
flags[match[1]] = parts[1] || true;
}
});
if (script) {
for (var i = 0, a; a = script.attributes[i]; i++) {
if (a.name !== "src") {
flags[a.name] = a.value || true;
}
}
}
if (flags.log && flags.log.split) {
var parts = flags.log.split(",");
flags.log = {};
parts.forEach(function(f) {
flags.log[f] = true;
});
} else {
flags.log = {};
}
}
if (flags.register) {
window.CustomElements = window.CustomElements || {
flags: {}
};
window.CustomElements.flags.register = flags.register;
}
WebComponents.flags = flags;
})();
(function(scope) {
"use strict";
var hasWorkingUrl = false;
if (!scope.forceJURL) {
try {
var u = new URL("b", "http://a");
u.pathname = "c%20d";
hasWorkingUrl = u.href === "http://a/c%20d";
} catch (e) {}
}
if (hasWorkingUrl) return;
var relative = Object.create(null);
relative["ftp"] = 21;
relative["file"] = 0;
relative["gopher"] = 70;
relative["http"] = 80;
relative["https"] = 443;
relative["ws"] = 80;
relative["wss"] = 443;
var relativePathDotMapping = Object.create(null);
relativePathDotMapping["%2e"] = ".";
relativePathDotMapping[".%2e"] = "..";
relativePathDotMapping["%2e."] = "..";
relativePathDotMapping["%2e%2e"] = "..";
function isRelativeScheme(scheme) {
return relative[scheme] !== undefined;
}
function invalid() {
clear.call(this);
this._isInvalid = true;
}
function IDNAToASCII(h) {
if ("" == h) {
invalid.call(this);
}
return h.toLowerCase();
}
function percentEscape(c) {
var unicode = c.charCodeAt(0);
if (unicode > 32 && unicode < 127 && [ 34, 35, 60, 62, 63, 96 ].indexOf(unicode) == -1) {
return c;
}
return encodeURIComponent(c);
}
function percentEscapeQuery(c) {
var unicode = c.charCodeAt(0);
if (unicode > 32 && unicode < 127 && [ 34, 35, 60, 62, 96 ].indexOf(unicode) == -1) {
return c;
}
return encodeURIComponent(c);
}
var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
function parse(input, stateOverride, base) {
function err(message) {
errors.push(message);
}
var state = stateOverride || "scheme start", cursor = 0, buffer = "", seenAt = false, seenBracket = false, errors = [];
loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
var c = input[cursor];
switch (state) {
case "scheme start":
if (c && ALPHA.test(c)) {
buffer += c.toLowerCase();
state = "scheme";
} else if (!stateOverride) {
buffer = "";
state = "no scheme";
continue;
} else {
err("Invalid scheme.");
break loop;
}
break;
case "scheme":
if (c && ALPHANUMERIC.test(c)) {
buffer += c.toLowerCase();
} else if (":" == c) {
this._scheme = buffer;
buffer = "";
if (stateOverride) {
break loop;
}
if (isRelativeScheme(this._scheme)) {
this._isRelative = true;
}
if ("file" == this._scheme) {
state = "relative";
} else if (this._isRelative && base && base._scheme == this._scheme) {
state = "relative or authority";
} else if (this._isRelative) {
state = "authority first slash";
} else {
state = "scheme data";
}
} else if (!stateOverride) {
buffer = "";
cursor = 0;
state = "no scheme";
continue;
} else if (EOF == c) {
break loop;
} else {
err("Code point not allowed in scheme: " + c);
break loop;
}
break;
case "scheme data":
if ("?" == c) {
this._query = "?";
state = "query";
} else if ("#" == c) {
this._fragment = "#";
state = "fragment";
} else {
if (EOF != c && "\t" != c && "\n" != c && "\r" != c) {
this._schemeData += percentEscape(c);
}
}
break;
case "no scheme":
if (!base || !isRelativeScheme(base._scheme)) {
err("Missing scheme.");
invalid.call(this);
} else {
state = "relative";
continue;
}
break;
case "relative or authority":
if ("/" == c && "/" == input[cursor + 1]) {
state = "authority ignore slashes";
} else {
err("Expected /, got: " + c);
state = "relative";
continue;
}
break;
case "relative":
this._isRelative = true;
if ("file" != this._scheme) this._scheme = base._scheme;
if (EOF == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
this._query = base._query;
this._username = base._username;
this._password = base._password;
break loop;
} else if ("/" == c || "\\" == c) {
if ("\\" == c) err("\\ is an invalid code point.");
state = "relative slash";
} else if ("?" == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
this._query = "?";
this._username = base._username;
this._password = base._password;
state = "query";
} else if ("#" == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
this._query = base._query;
this._fragment = "#";
this._username = base._username;
this._password = base._password;
state = "fragment";
} else {
var nextC = input[cursor + 1];
var nextNextC = input[cursor + 2];
if ("file" != this._scheme || !ALPHA.test(c) || nextC != ":" && nextC != "|" || EOF != nextNextC && "/" != nextNextC && "\\" != nextNextC && "?" != nextNextC && "#" != nextNextC) {
this._host = base._host;
this._port = base._port;
this._username = base._username;
this._password = base._password;
this._path = base._path.slice();
this._path.pop();
}
state = "relative path";
continue;
}
break;
case "relative slash":
if ("/" == c || "\\" == c) {
if ("\\" == c) {
err("\\ is an invalid code point.");
}
if ("file" == this._scheme) {
state = "file host";
} else {
state = "authority ignore slashes";
}
} else {
if ("file" != this._scheme) {
this._host = base._host;
this._port = base._port;
this._username = base._username;
this._password = base._password;
}
state = "relative path";
continue;
}
break;
case "authority first slash":
if ("/" == c) {
state = "authority second slash";
} else {
err("Expected '/', got: " + c);
state = "authority ignore slashes";
continue;
}
break;
case "authority second slash":
state = "authority ignore slashes";
if ("/" != c) {
err("Expected '/', got: " + c);
continue;
}
break;
case "authority ignore slashes":
if ("/" != c && "\\" != c) {
state = "authority";
continue;
} else {
err("Expected authority, got: " + c);
}
break;
case "authority":
if ("@" == c) {
if (seenAt) {
err("@ already seen.");
buffer += "%40";
}
seenAt = true;
for (var i = 0; i < buffer.length; i++) {
var cp = buffer[i];
if ("\t" == cp || "\n" == cp || "\r" == cp) {
err("Invalid whitespace in authority.");
continue;
}
if (":" == cp && null === this._password) {
this._password = "";
continue;
}
var tempC = percentEscape(cp);
null !== this._password ? this._password += tempC : this._username += tempC;
}
buffer = "";
} else if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c) {
cursor -= buffer.length;
buffer = "";
state = "host";
continue;
} else {
buffer += c;
}
break;
case "file host":
if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c) {
if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ":" || buffer[1] == "|")) {
state = "relative path";
} else if (buffer.length == 0) {
state = "relative path start";
} else {
this._host = IDNAToASCII.call(this, buffer);
buffer = "";
state = "relative path start";
}
continue;
} else if ("\t" == c || "\n" == c || "\r" == c) {
err("Invalid whitespace in file host.");
} else {
buffer += c;
}
break;
case "host":
case "hostname":
if (":" == c && !seenBracket) {
this._host = IDNAToASCII.call(this, buffer);
buffer = "";
state = "port";
if ("hostname" == stateOverride) {
break loop;
}
} else if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c) {
this._host = IDNAToASCII.call(this, buffer);
buffer = "";
state = "relative path start";
if (stateOverride) {
break loop;
}
continue;
} else if ("\t" != c && "\n" != c && "\r" != c) {
if ("[" == c) {
seenBracket = true;
} else if ("]" == c) {
seenBracket = false;
}
buffer += c;
} else {
err("Invalid code point in host/hostname: " + c);
}
break;
case "port":
if (/[0-9]/.test(c)) {
buffer += c;
} else if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c || stateOverride) {
if ("" != buffer) {
var temp = parseInt(buffer, 10);
if (temp != relative[this._scheme]) {
this._port = temp + "";
}
buffer = "";
}
if (stateOverride) {
break loop;
}
state = "relative path start";
continue;
} else if ("\t" == c || "\n" == c || "\r" == c) {
err("Invalid code point in port: " + c);
} else {
invalid.call(this);
}
break;
case "relative path start":
if ("\\" == c) err("'\\' not allowed in path.");
state = "relative path";
if ("/" != c && "\\" != c) {
continue;
}
break;
case "relative path":
if (EOF == c || "/" == c || "\\" == c || !stateOverride && ("?" == c || "#" == c)) {
if ("\\" == c) {
err("\\ not allowed in relative path.");
}
var tmp;
if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
buffer = tmp;
}
if (".." == buffer) {
this._path.pop();
if ("/" != c && "\\" != c) {
this._path.push("");
}
} else if ("." == buffer && "/" != c && "\\" != c) {
this._path.push("");
} else if ("." != buffer) {
if ("file" == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == "|") {
buffer = buffer[0] + ":";
}
this._path.push(buffer);
}
buffer = "";
if ("?" == c) {
this._query = "?";
state = "query";
} else if ("#" == c) {
this._fragment = "#";
state = "fragment";
}
} else if ("\t" != c && "\n" != c && "\r" != c) {
buffer += percentEscape(c);
}
break;
case "query":
if (!stateOverride && "#" == c) {
this._fragment = "#";
state = "fragment";
} else if (EOF != c && "\t" != c && "\n" != c && "\r" != c) {
this._query += percentEscapeQuery(c);
}
break;
case "fragment":
if (EOF != c && "\t" != c && "\n" != c && "\r" != c) {
this._fragment += c;
}
break;
}
cursor++;
}
}
function clear() {
this._scheme = "";
this._schemeData = "";
this._username = "";
this._password = null;
this._host = "";
this._port = "";
this._path = [];
this._query = "";
this._fragment = "";
this._isInvalid = false;
this._isRelative = false;
}
function jURL(url, base) {
if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base));
this._url = url;
clear.call(this);
var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, "");
parse.call(this, input, null, base);
}
jURL.prototype = {
toString: function() {
return this.href;
},
get href() {
if (this._isInvalid) return this._url;
var authority = "";
if ("" != this._username || null != this._password) {
authority = this._username + (null != this._password ? ":" + this._password : "") + "@";
}
return this.protocol + (this._isRelative ? "//" + authority + this.host : "") + this.pathname + this._query + this._fragment;
},
set href(href) {
clear.call(this);
parse.call(this, href);
},
get protocol() {
return this._scheme + ":";
},
set protocol(protocol) {
if (this._isInvalid) return;
parse.call(this, protocol + ":", "scheme start");
},
get host() {
return this._isInvalid ? "" : this._port ? this._host + ":" + this._port : this._host;
},
set host(host) {
if (this._isInvalid || !this._isRelative) return;
parse.call(this, host, "host");
},
get hostname() {
return this._host;
},
set hostname(hostname) {
if (this._isInvalid || !this._isRelative) return;
parse.call(this, hostname, "hostname");
},
get port() {
return this._port;
},
set port(port) {
if (this._isInvalid || !this._isRelative) return;
parse.call(this, port, "port");
},
get pathname() {
return this._isInvalid ? "" : this._isRelative ? "/" + this._path.join("/") : this._schemeData;
},
set pathname(pathname) {
if (this._isInvalid || !this._isRelative) return;
this._path = [];
parse.call(this, pathname, "relative path start");
},
get search() {
return this._isInvalid || !this._query || "?" == this._query ? "" : this._query;
},
set search(search) {
if (this._isInvalid || !this._isRelative) return;
this._query = "?";
if ("?" == search[0]) search = search.slice(1);
parse.call(this, search, "query");
},
get hash() {
return this._isInvalid || !this._fragment || "#" == this._fragment ? "" : this._fragment;
},
set hash(hash) {
if (this._isInvalid) return;
this._fragment = "#";
if ("#" == hash[0]) hash = hash.slice(1);
parse.call(this, hash, "fragment");
},
get origin() {
var host;
if (this._isInvalid || !this._scheme) {
return "";
}
switch (this._scheme) {
case "data":
case "file":
case "javascript":
case "mailto":
return "null";
}
host = this.host;
if (!host) {
return "";
}
return this._scheme + "://" + host;
}
};
var OriginalURL = scope.URL;
if (OriginalURL) {
jURL.createObjectURL = function(blob) {
return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
};
jURL.revokeObjectURL = function(url) {
OriginalURL.revokeObjectURL(url);
};
}
scope.URL = jURL;
})(self);
if (typeof WeakMap === "undefined") {
(function() {
var defineProperty = Object.defineProperty;
var counter = Date.now() % 1e9;
var WeakMap = function() {
this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__");
};
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, {
value: [ key, value ],
writable: true
});
return this;
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined;
},
"delete": function(key) {
var entry = key[this.name];
if (!entry || entry[0] !== key) return false;
entry[0] = entry[1] = undefined;
return true;
},
has: function(key) {
var entry = key[this.name];
if (!entry) return false;
return entry[0] === key;
}
};
window.WeakMap = WeakMap;
})();
}
(function(global) {
if (global.JsMutationObserver) {
return;
}
var registrationsTable = new WeakMap();
var setImmediate;
if (/Trident|Edge/.test(navigator.userAgent)) {
setImmediate = setTimeout;
} else if (window.setImmediate) {
setImmediate = window.setImmediate;
} else {
var setImmediateQueue = [];
var sentinel = String(Math.random());
window.addEventListener("message", function(e) {
if (e.data === sentinel) {
var queue = setImmediateQueue;
setImmediateQueue = [];
queue.forEach(function(func) {
func();
});
}
});
setImmediate = function(func) {
setImmediateQueue.push(func);
window.postMessage(sentinel, "*");
};
}
var isScheduled = false;
var scheduledObservers = [];
function scheduleCallback(observer) {
scheduledObservers.push(observer);
if (!isScheduled) {
isScheduled = true;
setImmediate(dispatchCallbacks);
}
}
function wrapIfNeeded(node) {
return window.ShadowDOMPolyfill && window.ShadowDOMPolyfill.wrapIfNeeded(node) || node;
}
function dispatchCallbacks() {
isScheduled = false;
var observers = scheduledObservers;
scheduledObservers = [];
observers.sort(function(o1, o2) {
return o1.uid_ - o2.uid_;
});
var anyNonEmpty = false;
observers.forEach(function(observer) {
var queue = observer.takeRecords();
removeTransientObserversFor(observer);
if (queue.length) {
observer.callback_(queue, observer);
anyNonEmpty = true;
}
});
if (anyNonEmpty) dispatchCallbacks();
}
function removeTransientObserversFor(observer) {
observer.nodes_.forEach(function(node) {
var registrations = registrationsTable.get(node);
if (!registrations) return;
registrations.forEach(function(registration) {
if (registration.observer === observer) registration.removeTransientObservers();
});
});
}
function forEachAncestorAndObserverEnqueueRecord(target, callback) {
for (var node = target; node; node = node.parentNode) {
var registrations = registrationsTable.get(node);
if (registrations) {
for (var j = 0; j < registrations.length; j++) {
var registration = registrations[j];
var options = registration.options;
if (node !== target && !options.subtree) continue;
var record = callback(options);
if (record) registration.enqueue(record);
}
}
}
}
var uidCounter = 0;
function JsMutationObserver(callback) {
this.callback_ = callback;
this.nodes_ = [];
this.records_ = [];
this.uid_ = ++uidCounter;
}
JsMutationObserver.prototype = {
observe: function(target, options) {
target = wrapIfNeeded(target);
if (!options.childList && !options.attributes && !options.characterData || options.attributeOldValue && !options.attributes || options.attributeFilter && options.attributeFilter.length && !options.attributes || options.characterDataOldValue && !options.characterData) {
throw new SyntaxError();
}
var registrations = registrationsTable.get(target);
if (!registrations) registrationsTable.set(target, registrations = []);
var registration;
for (var i = 0; i < registrations.length; i++) {
if (registrations[i].observer === this) {
registration = registrations[i];
registration.removeListeners();
registration.options = options;
break;
}
}
if (!registration) {
registration = new Registration(this, target, options);
registrations.push(registration);
this.nodes_.push(target);
}
registration.addListeners();
},
disconnect: function() {
this.nodes_.forEach(function(node) {
var registrations = registrationsTable.get(node);
for (var i = 0; i < registrations.length; i++) {
var registration = registrations[i];
if (registration.observer === this) {
registration.removeListeners();
registrations.splice(i, 1);
break;
}
}
}, this);
this.records_ = [];
},
takeRecords: function() {
var copyOfRecords = this.records_;
this.records_ = [];
return copyOfRecords;
}
};
function MutationRecord(type, target) {
this.type = type;
this.target = target;
this.addedNodes = [];
this.removedNodes = [];
this.previousSibling = null;
this.nextSibling = null;
this.attributeName = null;
this.attributeNamespace = null;
this.oldValue = null;
}
function copyMutationRecord(original) {
var record = new MutationRecord(original.type, original.target);
record.addedNodes = original.addedNodes.slice();
record.removedNodes = original.removedNodes.slice();
record.previousSibling = original.previousSibling;
record.nextSibling = original.nextSibling;
record.attributeName = original.attributeName;
record.attributeNamespace = original.attributeNamespace;
record.oldValue = original.oldValue;
return record;
}
var currentRecord, recordWithOldValue;
function getRecord(type, target) {
return currentRecord = new MutationRecord(type, target);
}
function getRecordWithOldValue(oldValue) {
if (recordWithOldValue) return recordWithOldValue;
recordWithOldValue = copyMutationRecord(currentRecord);
recordWithOldValue.oldValue = oldValue;
return recordWithOldValue;
}
function clearRecords() {
currentRecord = recordWithOldValue = undefined;
}
function recordRepresentsCurrentMutation(record) {
return record === recordWithOldValue || record === currentRecord;
}
function selectRecord(lastRecord, newRecord) {
if (lastRecord === newRecord) return lastRecord;
if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) return recordWithOldValue;
return null;
}
function Registration(observer, target, options) {
this.observer = observer;
this.target = target;
this.options = options;
this.transientObservedNodes = [];
}
Registration.prototype = {
enqueue: function(record) {
var records = this.observer.records_;
var length = records.length;
if (records.length > 0) {
var lastRecord = records[length - 1];
var recordToReplaceLast = selectRecord(lastRecord, record);
if (recordToReplaceLast) {
records[length - 1] = recordToReplaceLast;
return;
}
} else {
scheduleCallback(this.observer);
}
records[length] = record;
},
addListeners: function() {
this.addListeners_(this.target);
},
addListeners_: function(node) {
var options = this.options;
if (options.attributes) node.addEventListener("DOMAttrModified", this, true);
if (options.characterData) node.addEventListener("DOMCharacterDataModified", this, true);
if (options.childList) node.addEventListener("DOMNodeInserted", this, true);
if (options.childList || options.subtree) node.addEventListener("DOMNodeRemoved", this, true);
},
removeListeners: function() {
this.removeListeners_(this.target);
},
removeListeners_: function(node) {
var options = this.options;
if (options.attributes) node.removeEventListener("DOMAttrModified", this, true);
if (options.characterData) node.removeEventListener("DOMCharacterDataModified", this, true);
if (options.childList) node.removeEventListener("DOMNodeInserted", this, true);
if (options.childList || options.subtree) node.removeEventListener("DOMNodeRemoved", this, true);
},
addTransientObserver: function(node) {
if (node === this.target) return;
this.addListeners_(node);
this.transientObservedNodes.push(node);
var registrations = registrationsTable.get(node);
if (!registrations) registrationsTable.set(node, registrations = []);
registrations.push(this);
},
removeTransientObservers: function() {
var transientObservedNodes = this.transientObservedNodes;
this.transientObservedNodes = [];
transientObservedNodes.forEach(function(node) {
this.removeListeners_(node);
var registrations = registrationsTable.get(node);
for (var i = 0; i < registrations.length; i++) {
if (registrations[i] === this) {
registrations.splice(i, 1);
break;
}
}
}, this);
},
handleEvent: function(e) {
e.stopImmediatePropagation();
switch (e.type) {
case "DOMAttrModified":
var name = e.attrName;
var namespace = e.relatedNode.namespaceURI;
var target = e.target;
var record = new getRecord("attributes", target);
record.attributeName = name;
record.attributeNamespace = namespace;
var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue;
forEachAncestorAndObserverEnqueueRecord(target, function(options) {
if (!options.attributes) return;
if (options.attributeFilter && options.attributeFilter.length && options.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(namespace) === -1) {
return;
}
if (options.attributeOldValue) return getRecordWithOldValue(oldValue);
return record;
});
break;
case "DOMCharacterDataModified":
var target = e.target;
var record = getRecord("characterData", target);
var oldValue = e.prevValue;
forEachAncestorAndObserverEnqueueRecord(target, function(options) {
if (!options.characterData) return;
if (options.characterDataOldValue) return getRecordWithOldValue(oldValue);
return record;
});
break;
case "DOMNodeRemoved":
this.addTransientObserver(e.target);
case "DOMNodeInserted":
var changedNode = e.target;
var addedNodes, removedNodes;
if (e.type === "DOMNodeInserted") {
addedNodes = [ changedNode ];
removedNodes = [];
} else {
addedNodes = [];
removedNodes = [ changedNode ];
}
var previousSibling = changedNode.previousSibling;
var nextSibling = changedNode.nextSibling;
var record = getRecord("childList", e.target.parentNode);
record.addedNodes = addedNodes;
record.removedNodes = removedNodes;
record.previousSibling = previousSibling;
record.nextSibling = nextSibling;
forEachAncestorAndObserverEnqueueRecord(e.relatedNode, function(options) {
if (!options.childList) return;
return record;
});
}
clearRecords();
}
};
global.JsMutationObserver = JsMutationObserver;
if (!global.MutationObserver) {
global.MutationObserver = JsMutationObserver;
JsMutationObserver._isPolyfilled = true;
}
})(self);
(function() {
var needsTemplate = typeof HTMLTemplateElement === "undefined";
if (/Trident/.test(navigator.userAgent)) {
(function() {
var importNode = document.importNode;
document.importNode = function() {
var n = importNode.apply(document, arguments);
if (n.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
var f = document.createDocumentFragment();
f.appendChild(n);
return f;
} else {
return n;
}
};
})();
}
var needsCloning = function() {
if (!needsTemplate) {
var t = document.createElement("template");
var t2 = document.createElement("template");
t2.content.appendChild(document.createElement("div"));
t.content.appendChild(t2);
var clone = t.cloneNode(true);
return clone.content.childNodes.length === 0 || clone.content.firstChild.content.childNodes.length === 0;
}
}();
var TEMPLATE_TAG = "template";
var TemplateImpl = function() {};
if (needsTemplate) {
var contentDoc = document.implementation.createHTMLDocument("template");
var canDecorate = true;
var templateStyle = document.createElement("style");
templateStyle.textContent = TEMPLATE_TAG + "{display:none;}";
var head = document.head;
head.insertBefore(templateStyle, head.firstElementChild);
TemplateImpl.prototype = Object.create(HTMLElement.prototype);
TemplateImpl.decorate = function(template) {
if (template.content) {
return;
}
template.content = contentDoc.createDocumentFragment();
var child;
while (child = template.firstChild) {
template.content.appendChild(child);
}
template.cloneNode = function(deep) {
return TemplateImpl.cloneNode(this, deep);
};
if (canDecorate) {
try {
Object.defineProperty(template, "innerHTML", {
get: function() {
var o = "";
for (var e = this.content.firstChild; e; e = e.nextSibling) {
o += e.outerHTML || escapeData(e.data);
}
return o;
},
set: function(text) {
contentDoc.body.innerHTML = text;
TemplateImpl.bootstrap(contentDoc);
while (this.content.firstChild) {
this.content.removeChild(this.content.firstChild);
}
while (contentDoc.body.firstChild) {
this.content.appendChild(contentDoc.body.firstChild);
}
},
configurable: true
});
} catch (err) {
canDecorate = false;
}
}
TemplateImpl.bootstrap(template.content);
};
TemplateImpl.bootstrap = function(doc) {
var templates = doc.querySelectorAll(TEMPLATE_TAG);
for (var i = 0, l = templates.length, t; i < l && (t = templates[i]); i++) {
TemplateImpl.decorate(t);
}
};
document.addEventListener("DOMContentLoaded", function() {
TemplateImpl.bootstrap(document);
});
var createElement = document.createElement;
document.createElement = function() {
"use strict";
var el = createElement.apply(document, arguments);
if (el.localName === "template") {
TemplateImpl.decorate(el);
}
return el;
};
var escapeDataRegExp = /[&\u00A0<>]/g;
function escapeReplace(c) {
switch (c) {
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
case " ":
return " ";
}
}
function escapeData(s) {
return s.replace(escapeDataRegExp, escapeReplace);
}
}
if (needsTemplate || needsCloning) {
var nativeCloneNode = Node.prototype.cloneNode;
TemplateImpl.cloneNode = function(template, deep) {
var clone = nativeCloneNode.call(template, false);
if (this.decorate) {
this.decorate(clone);
}
if (deep) {
clone.content.appendChild(nativeCloneNode.call(template.content, true));
this.fixClonedDom(clone.content, template.content);
}
return clone;
};
TemplateImpl.fixClonedDom = function(clone, source) {
if (!source.querySelectorAll) return;
var s$ = source.querySelectorAll(TEMPLATE_TAG);
var t$ = clone.querySelectorAll(TEMPLATE_TAG);
for (var i = 0, l = t$.length, t, s; i < l; i++) {
s = s$[i];
t = t$[i];
if (this.decorate) {
this.decorate(s);
}
t.parentNode.replaceChild(s.cloneNode(true), t);
}
};
var originalImportNode = document.importNode;
Node.prototype.cloneNode = function(deep) {
var dom = nativeCloneNode.call(this, deep);
if (deep) {
TemplateImpl.fixClonedDom(dom, this);
}
return dom;
};
document.importNode = function(element, deep) {
if (element.localName === TEMPLATE_TAG) {
return TemplateImpl.cloneNode(element, deep);
} else {
var dom = originalImportNode.call(document, element, deep);
if (deep) {
TemplateImpl.fixClonedDom(dom, element);
}
return dom;
}
};
if (needsCloning) {
HTMLTemplateElement.prototype.cloneNode = function(deep) {
return TemplateImpl.cloneNode(this, deep);
};
}
}
if (needsTemplate) {
window.HTMLTemplateElement = TemplateImpl;
}
})();
(function(scope) {
"use strict";
if (!(window.performance && window.performance.now)) {
var start = Date.now();
window.performance = {
now: function() {
return Date.now() - start;
}
};
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function() {
var nativeRaf = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
return nativeRaf ? function(callback) {
return nativeRaf(function() {
callback(performance.now());
});
} : function(callback) {
return window.setTimeout(callback, 1e3 / 60);
};
}();
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function() {
return window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function(id) {
clearTimeout(id);
};
}();
}
var workingDefaultPrevented = function() {
var e = document.createEvent("Event");
e.initEvent("foo", true, true);
e.preventDefault();
return e.defaultPrevented;
}();
if (!workingDefaultPrevented) {
var origPreventDefault = Event.prototype.preventDefault;
Event.prototype.preventDefault = function() {
if (!this.cancelable) {
return;
}
origPreventDefault.call(this);
Object.defineProperty(this, "defaultPrevented", {
get: function() {
return true;
},
configurable: true
});
};
}
var isIE = /Trident/.test(navigator.userAgent);
if (!window.CustomEvent || isIE && typeof window.CustomEvent !== "function") {
window.CustomEvent = function(inType, params) {
params = params || {};
var e = document.createEvent("CustomEvent");
e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable), params.detail);
return e;
};
window.CustomEvent.prototype = window.Event.prototype;
}
if (!window.Event || isIE && typeof window.Event !== "function") {
var origEvent = window.Event;
window.Event = function(inType, params) {
params = params || {};
var e = document.createEvent("Event");
e.initEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable));
return e;
};
window.Event.prototype = origEvent.prototype;
}
})(window.WebComponents);
window.HTMLImports = window.HTMLImports || {
flags: {}
};
(function(scope) {
var IMPORT_LINK_TYPE = "import";
var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement("link"));
var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill);
var wrap = function(node) {
return hasShadowDOMPolyfill ? window.ShadowDOMPolyfill.wrapIfNeeded(node) : node;
};
var rootDocument = wrap(document);
var currentScriptDescriptor = {
get: function() {
var script = window.HTMLImports.currentScript || document.currentScript || (document.readyState !== "complete" ? document.scripts[document.scripts.length - 1] : null);
return wrap(script);
},
configurable: true
};
Object.defineProperty(document, "_currentScript", currentScriptDescriptor);
Object.defineProperty(rootDocument, "_currentScript", currentScriptDescriptor);
var isIE = /Trident/.test(navigator.userAgent);
function whenReady(callback, doc) {
doc = doc || rootDocument;
whenDocumentReady(function() {
watchImportsLoad(callback, doc);
}, doc);
}
var requiredReadyState = isIE ? "complete" : "interactive";
var READY_EVENT = "readystatechange";
function isDocumentReady(doc) {
return doc.readyState === "complete" || doc.readyState === requiredReadyState;
}
function whenDocumentReady(callback, doc) {
if (!isDocumentReady(doc)) {
var checkReady = function() {
if (doc.readyState === "complete" || doc.readyState === requiredReadyState) {
doc.removeEventListener(READY_EVENT, checkReady);
whenDocumentReady(callback, doc);
}
};
doc.addEventListener(READY_EVENT, checkReady);
} else if (callback) {
callback();
}
}
function markTargetLoaded(event) {
event.target.__loaded = true;
}
function watchImportsLoad(callback, doc) {
var imports = doc.querySelectorAll("link[rel=import]");
var parsedCount = 0, importCount = imports.length, newImports = [], errorImports = [];
function checkDone() {
if (parsedCount == importCount && callback) {
callback({
allImports: imports,
loadedImports: newImports,
errorImports: errorImports
});
}
}
function loadedImport(e) {
markTargetLoaded(e);
newImports.push(this);
parsedCount++;
checkDone();
}
function errorLoadingImport(e) {
errorImports.push(this);
parsedCount++;
checkDone();
}
if (importCount) {
for (var i = 0, imp; i < importCount && (imp = imports[i]); i++) {
if (isImportLoaded(imp)) {
newImports.push(this);
parsedCount++;
checkDone();
} else {
imp.addEventListener("load", loadedImport);
imp.addEventListener("error", errorLoadingImport);
}
}
} else {
checkDone();
}
}
function isImportLoaded(link) {
return useNative ? link.__loaded || link.import && link.import.readyState !== "loading" : link.__importParsed;
}
if (useNative) {
new MutationObserver(function(mxns) {
for (var i = 0, l = mxns.length, m; i < l && (m = mxns[i]); i++) {
if (m.addedNodes) {
handleImports(m.addedNodes);
}
}
}).observe(document.head, {
childList: true
});
function handleImports(nodes) {
for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
if (isImport(n)) {
handleImport(n);
}
}
}
function isImport(element) {
return element.localName === "link" && element.rel === "import";
}
function handleImport(element) {
var loaded = element.import;
if (loaded) {
markTargetLoaded({
target: element
});
} else {
element.addEventListener("load", markTargetLoaded);
element.addEventListener("error", markTargetLoaded);
}
}
(function() {
if (document.readyState === "loading") {
var imports = document.querySelectorAll("link[rel=import]");
for (var i = 0, l = imports.length, imp; i < l && (imp = imports[i]); i++) {
handleImport(imp);
}
}
})();
}
whenReady(function(detail) {
window.HTMLImports.ready = true;
window.HTMLImports.readyTime = new Date().getTime();
var evt = rootDocument.createEvent("CustomEvent");
evt.initCustomEvent("HTMLImportsLoaded", true, true, detail);
rootDocument.dispatchEvent(evt);
});
scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE;
scope.useNative = useNative;
scope.rootDocument = rootDocument;
scope.whenReady = whenReady;
scope.isIE = isIE;
})(window.HTMLImports);
(function(scope) {
var modules = [];
var addModule = function(module) {
modules.push(module);
};
var initializeModules = function() {
modules.forEach(function(module) {
module(scope);
});
};
scope.addModule = addModule;
scope.initializeModules = initializeModules;
})(window.HTMLImports);
window.HTMLImports.addModule(function(scope) {
var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g;
var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g;
var path = {
resolveUrlsInStyle: function(style, linkUrl) {
var doc = style.ownerDocument;
var resolver = doc.createElement("a");
style.textContent = this.resolveUrlsInCssText(style.textContent, linkUrl, resolver);
return style;
},
resolveUrlsInCssText: function(cssText, linkUrl, urlObj) {
var r = this.replaceUrls(cssText, urlObj, linkUrl, CSS_URL_REGEXP);
r = this.replaceUrls(r, urlObj, linkUrl, CSS_IMPORT_REGEXP);
return r;
},
replaceUrls: function(text, urlObj, linkUrl, regexp) {
return text.replace(regexp, function(m, pre, url, post) {
var urlPath = url.replace(/["']/g, "");
if (linkUrl) {
urlPath = new URL(urlPath, linkUrl).href;
}
urlObj.href = urlPath;
urlPath = urlObj.href;
return pre + "'" + urlPath + "'" + post;
});
}
};
scope.path = path;
});
window.HTMLImports.addModule(function(scope) {
var xhr = {
async: true,
ok: function(request) {
return request.status >= 200 && request.status < 300 || request.status === 304 || request.status === 0;
},
load: function(url, next, nextContext) {
var request = new XMLHttpRequest();
if (scope.flags.debug || scope.flags.bust) {
url += "?" + Math.random();
}
request.open("GET", url, xhr.async);
request.addEventListener("readystatechange", function(e) {
if (request.readyState === 4) {
var redirectedUrl = null;
try {
var locationHeader = request.getResponseHeader("Location");
if (locationHeader) {
redirectedUrl = locationHeader.substr(0, 1) === "/" ? location.origin + locationHeader : locationHeader;
}
} catch (e) {
console.error(e.message);
}
next.call(nextContext, !xhr.ok(request) && request, request.response || request.responseText, redirectedUrl);
}
});
request.send();
return request;
},
loadDocument: function(url, next, nextContext) {
this.load(url, next, nextContext).responseType = "document";
}
};
scope.xhr = xhr;
});
window.HTMLImports.addModule(function(scope) {
var xhr = scope.xhr;
var flags = scope.flags;
var Loader = function(onLoad, onComplete) {
this.cache = {};
this.onload = onLoad;
this.oncomplete = onComplete;
this.inflight = 0;
this.pending = {};
};
Loader.prototype = {
addNodes: function(nodes) {
this.inflight += nodes.length;
for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
this.require(n);
}
this.checkDone();
},
addNode: function(node) {
this.inflight++;
this.require(node);
this.checkDone();
},
require: function(elt) {
var url = elt.src || elt.href;
elt.__nodeUrl = url;
if (!this.dedupe(url, elt)) {
this.fetch(url, elt);
}
},
dedupe: function(url, elt) {
if (this.pending[url]) {
this.pending[url].push(elt);
return true;
}
var resource;
if (this.cache[url]) {
this.onload(url, elt, this.cache[url]);
this.tail();
return true;
}
this.pending[url] = [ elt ];
return false;
},
fetch: function(url, elt) {
flags.load && console.log("fetch", url, elt);
if (!url) {
setTimeout(function() {
this.receive(url, elt, {
error: "href must be specified"
}, null);
}.bind(this), 0);
} else if (url.match(/^data:/)) {
var pieces = url.split(",");
var header = pieces[0];
var body = pieces[1];
if (header.indexOf(";base64") > -1) {
body = atob(body);
} else {
body = decodeURIComponent(body);
}
setTimeout(function() {
this.receive(url, elt, null, body);
}.bind(this), 0);
} else {
var receiveXhr = function(err, resource, redirectedUrl) {
this.receive(url, elt, err, resource, redirectedUrl);
}.bind(this);
xhr.load(url, receiveXhr);
}
},
receive: function(url, elt, err, resource, redirectedUrl) {
this.cache[url] = resource;
var $p = this.pending[url];
for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) {
this.onload(url, p, resource, err, redirectedUrl);
this.tail();
}
this.pending[url] = null;
},
tail: function() {
--this.inflight;
this.checkDone();
},
checkDone: function() {
if (!this.inflight) {
this.oncomplete();
}
}
};
scope.Loader = Loader;
});
window.HTMLImports.addModule(function(scope) {
var Observer = function(addCallback) {
this.addCallback = addCallback;
this.mo = new MutationObserver(this.handler.bind(this));
};
Observer.prototype = {
handler: function(mutations) {
for (var i = 0, l = mutations.length, m; i < l && (m = mutations[i]); i++) {
if (m.type === "childList" && m.addedNodes.length) {
this.addedNodes(m.addedNodes);
}
}
},
addedNodes: function(nodes) {
if (this.addCallback) {
this.addCallback(nodes);
}
for (var i = 0, l = nodes.length, n, loading; i < l && (n = nodes[i]); i++) {
if (n.children && n.children.length) {
this.addedNodes(n.children);
}
}
},
observe: function(root) {
this.mo.observe(root, {
childList: true,
subtree: true
});
}
};
scope.Observer = Observer;
});
window.HTMLImports.addModule(function(scope) {
var path = scope.path;
var rootDocument = scope.rootDocument;
var flags = scope.flags;
var isIE = scope.isIE;
var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE;
var IMPORT_SELECTOR = "link[rel=" + IMPORT_LINK_TYPE + "]";
var importParser = {
documentSelectors: IMPORT_SELECTOR,
importsSelectors: [ IMPORT_SELECTOR, "link[rel=stylesheet]:not([type])", "style:not([type])", "script:not([type])", 'script[type="application/javascript"]', 'script[type="text/javascript"]' ].join(","),
map: {
link: "parseLink",
script: "parseScript",
style: "parseStyle"
},
dynamicElements: [],
parseNext: function() {
var next = this.nextToParse();
if (next) {
this.parse(next);
}
},
parse: function(elt) {
if (this.isParsed(elt)) {
flags.parse && console.log("[%s] is already parsed", elt.localName);
return;
}
var fn = this[this.map[elt.localName]];
if (fn) {
this.markParsing(elt);
fn.call(this, elt);
}
},
parseDynamic: function(elt, quiet) {
this.dynamicElements.push(elt);
if (!quiet) {
this.parseNext();
}
},
markParsing: function(elt) {
flags.parse && console.log("parsing", elt);
this.parsingElement = elt;
},
markParsingComplete: function(elt) {
elt.__importParsed = true;
this.markDynamicParsingComplete(elt);
if (elt.__importElement) {
elt.__importElement.__importParsed = true;
this.markDynamicParsingComplete(elt.__importElement);
}
this.parsingElement = null;
flags.parse && console.log("completed", elt);
},
markDynamicParsingComplete: function(elt) {
var i = this.dynamicElements.indexOf(elt);
if (i >= 0) {
this.dynamicElements.splice(i, 1);
}
},
parseImport: function(elt) {
elt.import = elt.__doc;
if (window.HTMLIm